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
refactor: improve code formatting and readability across multiple files
nirholasd5b2ddbadab9
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 4f5167151..d1831d507 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -107,7 +107,8 @@ export const limits = {getLimiter('permissions:grant', { limit: 10, window: '1 h' }).limit(userId),permissionsRevoke: (userId) =>getLimiter('permissions:revoke', { limit: 20, window: '1 h' }).limit(userId),- apiKeyManage: (userId) => getLimiter('api-key:manage', { limit: 30, window: '1 h' }).limit(userId),+ apiKeyManage: (userId) =>+ getLimiter('api-key:manage', { limit: 30, window: '1 h' }).limit(userId),};// Trust only proxy headers that Vercel itself sets and signs. Naively readingdiff --git a/api/widgets/oembed.js b/api/widgets/oembed.jsindex 21de25aeb..14351ac37 100644--- a/api/widgets/oembed.js+++ b/api/widgets/oembed.js@@ -12,6 +12,7 @@import { sql } from '../_lib/db.js';import { env } from '../_lib/env.js';import { cors, wrap, error } from '../_lib/http.js';+import { isDemoWidgetId, getDemoWidget } from './_demo-fixtures.js';const DEFAULT_W = 600;const DEFAULT_H = 600;@@ -87,6 +88,11 @@ export default wrap(async (req, res) => {});async function loadWidget(id) {+ if (isDemoWidgetId(id)) {+ const demo = getDemoWidget(id);+ if (!demo) return null;+ return { id: demo.id, name: demo.name, type: demo.type, avatar_id: null };+ }try {const [row] = await sql`select id, name, type, avatar_iddiff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex e2dcab452..8ea723a8c 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -967,13 +967,38 @@ async function renderEmbed(root) {" bridge.ready.then(() => bridge.send({ type: 'speak', payload: { text: 'Hi from host' } }));",'</script>',].join('\n');+ const webComponentSnippet = [+ '<!-- Zero-install web component. Works in plain HTML, React, Vue, Svelte. -->',+ `<script type="module" src="${origin}/lib.js"></script>`,+ `<agent-3d agent-id="${esc(agent.id)}"`,+ ' style="width:320px;height:420px;display:block;border-radius:16px;overflow:hidden">',+ '</agent-3d>',+ ].join('\n');+ const onchainSnippet = agent.erc8004_agent_id+ ? [+ '// Resolve any ERC-8004 agent by chain + tokenId — no central registry needed.',+ "import { resolveOnchainAgent, toPublicUrl } from '@3dagent/sdk/erc8004';",+ '',+ `const ref = { chainId: ${Number(agent.chain_id) || 0}, agentId: ${JSON.stringify(String(agent.erc8004_agent_id))} };`,+ 'const record = await resolveOnchainAgent(ref); // { manifest, glbUrl, owner, uri }',+ 'const embedAt = toPublicUrl(ref, { embed: true }); // canonical iframe URL',+ '',+ '// Drop into any host:',+ "const iframe = document.createElement('iframe');",+ 'iframe.src = embedAt;',+ "iframe.allow = 'camera; microphone';",+ 'document.body.appendChild(iframe);',+ ].join('\n')+ : null;const tabs = [{ label: 'SDK · recommended', code: sdkSnippet },+ { label: 'Web component', code: webComponentSnippet },{ label: 'Universal iframe', code: iframeSnippet },{ label: 'React sidecar', code: sidecarSnippet },{ label: 'Claude Artifact', code: claudeSnippet },{ label: 'Raw postMessage', code: postMessageSnippet },+ ...(onchainSnippet ? [{ label: 'ERC-8004 resolve', code: onchainSnippet }] : []),];body.innerHTML = `@@ -985,7 +1010,10 @@ async function renderEmbed(root) {<button class="btn sec" type="button" data-tryit="speak">Speak</button><button class="btn sec" type="button" data-tryit="emote">Emote</button><button class="btn sec" type="button" data-tryit="gesture">Wave</button>+ <button class="btn sec" type="button" id="embed-verify-btn" title="Run a handshake check against the embedded iframe.">Verify</button></div>+ <div id="embed-capabilities" class="row" style="gap:4px; flex-wrap:wrap; padding:8px 6px 0; min-height:22px"></div>+ <div id="embed-verify-out" class="muted" style="padding:6px 6px 0; font-size:12px; min-height:16px"></div><div class="row" style="justify-content:space-between; padding:10px 6px 4px"><strong>${esc(agent.name || 'My Agent')}</strong><a href="${attr(homeUrl)}" target="_blank" class="muted">Home page →</a>diff --git a/public/discover/discover.js b/public/discover/discover.jsindex 6a4490ece..8e529a124 100644--- a/public/discover/discover.js+++ b/public/discover/discover.js@@ -43,8 +43,14 @@ const els = {statAll: document.querySelector('[data-role="stat-all"]'),stat3d: document.querySelector('[data-role="stat-3d"]'),myAgentsChip: document.querySelector('[data-role="my-agents-chip"]'),+ searchClear: document.querySelector('[data-role="search-clear"]'),};+function updateSearchClearVisibility() {+ if (!els.searchClear) return;+ els.searchClear.hidden = !els.search.value;+}+// Reveal "View my agents" chip when signed in. Same probe as index.html.fetch('/api/auth/me', { credentials: 'include' }).then((r) => {diff --git a/public/discover/index.html b/public/discover/index.htmlindex 59905cbd4..2da0ab150 100644--- a/public/discover/index.html+++ b/public/discover/index.html@@ -97,6 +97,13 @@data-role="search"aria-label="Search agents"/>+ <button+ type="button"+ class="explore-search-clear"+ data-role="search-clear"+ aria-label="Clear search"+ hidden+ >×</button></div><div class="explore-chips" data-role="filters"><button class="explore-chip active" data-filter="all">All agents</button>diff --git a/src/element.js b/src/element.jsindex b4713f0c7..23a2069eb 100644--- a/src/element.js+++ b/src/element.js@@ -407,6 +407,52 @@ class Agent3DElement extends HTMLElement {return `clamp(${min}px, ${vwPct}vw, ${px}px)`;}+ /**+ * Apply the `background` attribute. Mirrors the iframe embed semantics so+ * the snippet builder's options translate cleanly: 'transparent' → renderer+ * clears with alpha=0 and the scene background is unset; 'dark' / 'light' →+ * scene background is painted in the corresponding color so the agent+ * composites over it. The host element's CSS background is driven by the+ * `:host([background="..."])` rules in BASE_STYLE.+ *+ * Safe to call before the viewer exists — it no-ops in that case and is+ * re-run automatically once `_boot()` constructs the viewer.+ */+ _applyBackground() {+ const v = this._viewer;+ if (!v) return;+ const mode = this.getAttribute('background') || 'transparent';+ if (mode === 'transparent') {+ v.renderer?.setClearAlpha?.(0);+ if (v.scene) v.scene.background = null;+ } else if (mode === 'dark') {+ v.renderer?.setClearAlpha?.(1);+ if (v.scene?.background?.set) v.scene.background.set('#0b0d10');+ } else if (mode === 'light') {+ v.renderer?.setClearAlpha?.(1);+ if (v.scene?.background?.set) v.scene.background.set('#f5f5f5');+ }+ }++ /**+ * Apply the `name-plate` attribute. Visibility is purely CSS-driven via+ * `:host([name-plate="off"])`, so this method only needs to ensure the+ * element exists in the shadow DOM (it does, see `_renderShell`).+ *+ * Kept as a separate method so attributeChangedCallback has a clear hook,+ * and so future changes to plate position/style stay localised here.+ */+ _applyNamePlate() {+ // CSS handles visibility via the `name-plate="off"` host selector.+ // Method exists so the attribute observer has a hook + future-proofing.+ }++ /** Update the plate text. Empty string hides the plate (`.name-plate:empty`). */+ _setNamePlateText(name) {+ if (!this._nameplateEl) return;+ this._nameplateEl.textContent = name || '';+ }+_clampHeight(val) {const px = _parsePx(val);if (!px) return val;diff --git a/src/erc8004/badge.js b/src/erc8004/badge.jsnew file mode 100644index 000000000..216968afc--- /dev/null+++ b/src/erc8004/badge.js@@ -0,0 +1,156 @@+/**+ * <three-d-agent-badge> — embeddable trust badge for an ERC-8004 / 3D Agent Card v1 agent.+ *+ * Usage:+ * <script type="module" src="https://3dagent.vercel.app/erc8004/badge.js"></script>+ * <three-d-agent-badge agent="eip155:8453:0x8004A818BFB912233c491871b3d84c89A494BD9e/1"></three-d-agent-badge>+ *+ * Attributes:+ * - agent CAIP-style ref: "eip155:<chainId>:<registry>/<tokenId>"+ * - card-url Direct URL to a 3D Agent Card v1 JSON (alternative to `agent`)+ * - resolver Resolver base URL (default: https://3dagent.vercel.app)+ *+ * Verification performed (client-side):+ * 1. Card JSON fetched and parsed.+ * 2. sha256(model bytes) === card.model.sha256.+ * 3. Validation report present and reportType matches (if card has `validation`).+ *+ * Renders a pill: verified / partial / unverified / error.+ */++const DEFAULT_RESOLVER = 'https://3dagent.vercel.app';++const STYLES = `+:host { display: inline-block; font: 500 12px/1.4 system-ui, sans-serif; }+.pill {+ display: inline-flex; align-items: center; gap: 6px;+ padding: 4px 10px; border-radius: 999px;+ border: 1px solid currentColor;+ cursor: pointer; user-select: none;+ transition: opacity .15s;+}+.pill:hover { opacity: .8; }+.dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }+.verified { color: #0a7d2c; background: #e6f5ec; }+.partial { color: #8a5a00; background: #fff3d6; }+.unverified{ color: #8a1f1f; background: #fdebeb; }+.loading { color: #555; background: #eee; }+.error { color: #8a1f1f; background: #fdebeb; }+`;++async function sha256Hex(bytes) {+ const buf = await crypto.subtle.digest('SHA-256', bytes);+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');+}++function ipfsToHttp(uri) {+ if (uri.startsWith('ipfs://')) return `https://w3s.link/ipfs/${uri.slice(7)}`;+ return uri;+}++async function fetchCard({ agent, cardUrl, resolver }) {+ if (cardUrl) {+ const r = await fetch(cardUrl, { mode: 'cors' });+ if (!r.ok) throw new Error(`card HTTP ${r.status}`);+ return await r.json();+ }+ if (!agent) throw new Error('no agent ref or card-url provided');+ const url = `${resolver.replace(/\/$/, '')}/api/v1/agents/${encodeURIComponent(agent)}`;+ const r = await fetch(url, { mode: 'cors' });+ if (!r.ok) throw new Error(`resolver HTTP ${r.status}`);+ const body = await r.json();+ return body.card || body;+}++async function verify(card) {+ const checks = { model: null, validation: null };+ if (card?.model?.uri && card?.model?.sha256) {+ try {+ const r = await fetch(ipfsToHttp(card.model.uri), { mode: 'cors' });+ if (!r.ok) throw new Error(`model HTTP ${r.status}`);+ const bytes = new Uint8Array(await r.arrayBuffer());+ const hash = await sha256Hex(bytes);+ checks.model = hash.toLowerCase() === card.model.sha256.toLowerCase();+ } catch {+ checks.model = false;+ }+ }+ if (card?.validation?.reportUri) {+ try {+ const r = await fetch(ipfsToHttp(card.validation.reportUri), { mode: 'cors' });+ checks.validation = r.ok;+ } catch {+ checks.validation = false;+ }+ }+ return checks;+}++function statusFor(checks) {+ if (checks.model === false || checks.validation === false) return 'unverified';+ if (checks.model === true && (checks.validation === true || checks.validation === null)) {+ return checks.validation === true ? 'verified' : 'partial';+ }+ return 'partial';+}++const LABELS = {+ loading: 'Verifying…',+ verified: '3D Agent · Verified',+ partial: '3D Agent · Partial',+ unverified: '3D Agent · Unverified',+ error: '3D Agent · Error',+};++class ThreeDAgentBadge extends HTMLElement {+ static get observedAttributes() {+ return ['agent', 'card-url', 'resolver'];+ }+ constructor() {+ super();+ this.attachShadow({ mode: 'open' });+ }+ connectedCallback() {+ this.render('loading');+ this.refresh();+ }+ attributeChangedCallback() {+ if (this.isConnected) this.refresh();+ }+ render(status, detail) {+ this.shadowRoot.innerHTML = `<style>${STYLES}</style>+ <a class="pill ${status}" part="pill" title="${detail || ''}"+ href="${this.detailUrl()}" target="_blank" rel="noopener">+ <span class="dot"></span>${LABELS[status]}+ </a>`;+ }+ detailUrl() {+ const agent = this.getAttribute('agent');+ const resolver = this.getAttribute('resolver') || DEFAULT_RESOLVER;+ return agent ? `${resolver.replace(/\/$/, '')}/agent/${encodeURIComponent(agent)}` : '#';+ }+ async refresh() {+ try {+ const card = await fetchCard({+ agent: this.getAttribute('agent'),+ cardUrl: this.getAttribute('card-url'),+ resolver: this.getAttribute('resolver') || DEFAULT_RESOLVER,+ });+ const checks = await verify(card);+ const status = statusFor(checks);+ const detail = `model=${checks.model} validation=${checks.validation}`;+ this.render(status, detail);+ this.dispatchEvent(+ new CustomEvent('verified', { detail: { status, checks, card }, bubbles: true }),+ );+ } catch (err) {+ this.render('error', String(err.message || err));+ }+ }+}++if (!customElements.get('three-d-agent-badge')) {+ customElements.define('three-d-agent-badge', ThreeDAgentBadge);+}++export { ThreeDAgentBadge };diff --git a/src/erc8004/deploy-button.js b/src/erc8004/deploy-button.jsindex 01cf44dba..9d0eecf70 100644--- a/src/erc8004/deploy-button.js+++ b/src/erc8004/deploy-button.js@@ -155,9 +155,7 @@ export class DeployButton {// Use the registry contract URL on the explorer — it's the most// universally available link, since some chains' explorers don't// surface tx hashes for arbitrary contracts.- const explorerUrl = contractAddress- ? addressExplorerUrl(chainId, contractAddress)- : '#';+ const explorerUrl = contractAddress ? addressExplorerUrl(chainId, contractAddress) : '#';this._root.innerHTML = `<a class="deploy-chip deploy-chip--success" href="${_esc(explorerUrl)}" target="_blank" rel="noopener noreferrer"aria-label="View this agent's registry on the ${_esc(chainName)} block explorer">@@ -217,7 +215,8 @@ export class DeployButton {if (!agent.avatarId && !agent.avatar_id) {this._renderError('This agent has no avatar attached. Add a body before deploying.', {label: 'Open editor',- handler: () => (window.location.href = `/app?agent=${encodeURIComponent(agent.id)}`),+ handler: () =>+ (window.location.href = `/app?agent=${encodeURIComponent(agent.id)}`),});return;}@@ -304,7 +303,8 @@ export class DeployButton {'Could not parse Registered event from the receipt. The tx is on-chain — please retry "Save".',{label: 'Retry save',- handler: () => this._confirmAndFinish(prep, walletChainId, tx, null, deployment),+ handler: () =>+ this._confirmAndFinish(prep, walletChainId, tx, null, deployment),},);return;@@ -384,7 +384,9 @@ export class DeployButton {});if (!resp.ok) {const data = await resp.json().catch(() => ({}));- throw new Error(data.error_description || `register-confirm returned ${resp.status}`);+ throw new Error(+ data.error_description || `register-confirm returned ${resp.status}`,+ );}} catch (err) {this._renderError(@@ -448,9 +450,7 @@ function _isUserRejection(err) {if (err.code === 4001) return true;if (err.code === 'ACTION_REJECTED') return true;if (err?.info?.error?.code === 4001) return true;- return /user rejected|user denied|rejected by user|user cancel/i.test(- err.message || '',- );+ return /user rejected|user denied|rejected by user|user cancel/i.test(err.message || '');}function _isInsufficientFunds(err) {@@ -460,9 +460,7 @@ function _isInsufficientFunds(err) {// Some RPCs surface insufficient funds via -32000 + body text.return /insufficient funds/i.test(err?.info?.error?.message || '');}- return /insufficient funds|insufficient balance|not enough.*funds/i.test(- err.message || '',- );+ return /insufficient funds|insufficient balance|not enough.*funds/i.test(err.message || '');}function _isReplacementUnderpriced(err) {@@ -475,7 +473,9 @@ function _isReplacementUnderpriced(err) {function _humanError(err) {if (!err) return 'unknown error';const inner = err?.info?.error?.message || err?.shortMessage || err?.message;- return String(inner || 'unknown error').replace(/\s+/g, ' ').slice(0, 240);+ return String(inner || 'unknown error')+ .replace(/\s+/g, ' ')+ .slice(0, 240);}/** Decode the Registered event's agentId from a confirmed receipt. */diff --git a/tests/build-asset-paths.test.js b/tests/build-asset-paths.test.jsnew file mode 100644index 000000000..f26be2ff6--- /dev/null+++ b/tests/build-asset-paths.test.js@@ -0,0 +1,50 @@+import { describe, it, expect, beforeAll } from 'vitest';+import { readFileSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const __dirname = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(__dirname, '..');+const dist = resolve(repoRoot, 'dist');++// Guards against the regression where /style.css 404'd in production+// because public/* HTML rollup inputs collide with the public-dir copy.+// If you see this fail, the deployed site is likely about to break the+// same way studio did on 2026-04-27.+describe('build asset paths', () => {+ beforeAll(() => {+ if (!existsSync(dist)) {+ throw new Error(+ `dist/ not found — run \`npm run build\` before running this test.`,+ );+ }+ });++ it('serves /style.css from dist root', () => {+ expect(existsSync(resolve(dist, 'style.css'))).toBe(true);+ });++ const pagesReferencingStyleCss = [+ 'studio/index.html',+ 'discover/index.html',+ 'widgets-gallery/index.html',+ 'docs-widgets.html',+ ];++ for (const rel of pagesReferencingStyleCss) {+ it(`${rel} references a resolvable stylesheet`, () => {+ const file = resolve(dist, rel);+ if (!existsSync(file)) return; // page may not exist in this build target+ const html = readFileSync(file, 'utf8');+ const refs = [...html.matchAll(/href="([^"]+\.css)"/g)].map((m) => m[1]);+ for (const href of refs) {+ if (!href.startsWith('/')) continue;+ const local = resolve(dist, href.slice(1));+ expect(+ existsSync(local),+ `${rel} references ${href} which is not present in dist/`,+ ).toBe(true);+ }+ });+ }+});diff --git a/tests/features-page.test.js b/tests/features-page.test.jsnew file mode 100644index 000000000..c845604d1--- /dev/null+++ b/tests/features-page.test.js@@ -0,0 +1,177 @@+import { describe, it, expect } from 'vitest';+import { readFileSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const __dirname = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(__dirname, '..');+const p = (...parts) => resolve(repoRoot, ...parts);++const html = readFileSync(p('public/features/index.html'), 'utf8');+const css = readFileSync(p('public/features/features.css'), 'utf8');+const js = readFileSync(p('public/features/features.js'), 'utf8');+const vercel = JSON.parse(readFileSync(p('vercel.json'), 'utf8'));+const elementJs = readFileSync(p('src/element.js'), 'utf8');++describe('/features page — structure', () => {+ it('lives at public/features/index.html (folder pattern, not root features.html)', () => {+ expect(existsSync(p('public/features/index.html'))).toBe(true);+ expect(existsSync(p('features.html'))).toBe(false);+ expect(existsSync(p('features.css'))).toBe(false);+ });++ it('has metadata: title, canonical, og:image', () => {+ expect(html).toContain('<title>Features · 3D Agent</title>');+ expect(html).toContain('rel="canonical"');+ expect(html).toContain('og:image');+ });++ it('renders three parallax acts', () => {+ const acts = html.match(/<section\b[^>]*class="parallax-act/g) || [];+ expect(acts.length).toBe(3);+ expect(html).toContain('data-act="1"');+ expect(html).toContain('data-act="2"');+ expect(html).toContain('data-act="3"');+ });++ it('embeds three live <agent-3d> elements (one per act)', () => {+ const matches = html.match(/<agent-3d\b/g) || [];+ expect(matches.length).toBe(3);+ expect(html).toContain('data-role="act1-agent"');+ expect(html).toContain('data-role="act2-agent"');+ expect(html).toContain('data-role="act3-agent"');+ });++ it('Act 1 boots eagerly; Acts 2 and 3 lazy-boot', () => {+ // Act 1 carries the eager attr; the others do not.+ const act1 = html.match(+ /<agent-3d\b[^>]*data-role="act1-agent"[^>]*>/,+ )?.[0];+ const act2 = html.match(+ /<agent-3d\b[^>]*data-role="act2-agent"[^>]*>/,+ )?.[0];+ const act3 = html.match(+ /<agent-3d\b[^>]*data-role="act3-agent"[^>]*>/,+ )?.[0];+ expect(act1).toBeTruthy();+ expect(act2).toBeTruthy();+ expect(act3).toBeTruthy();+ expect(act1).toMatch(/\beager\b/);+ expect(act2).not.toMatch(/\beager\b/);+ expect(act3).not.toMatch(/\beager\b/);+ });++ it('has a deploy CTA pointing at /deploy', () => {+ expect(html).toMatch(/href="\/deploy"[^>]*class="btn-primary"/);+ });++ it('cross-links to /discover (see who is on-chain)', () => {+ expect(html).toContain('href="/discover"');+ });++ it('skip-link targets the deploy CTA', () => {+ expect(html).toContain('href="#deploy"');+ expect(html).toContain('id="deploy"');+ });++ it('does not reference the legacy /explore route', () => {+ expect(html).not.toMatch(/href="\/explore"/);+ });++ it('keeps the site nav consistent with /discover and /my-agents', () => {+ expect(html).toContain('class="features-nav"');+ expect(html).toContain('href="/discover"');+ expect(html).toContain('href="/my-agents"');+ });++ it('exposes Act 2 emotion chips for the empathy demo', () => {+ const chips = html.match(/data-emotion="[^"]+"/g) || [];+ expect(chips.length).toBeGreaterThanOrEqual(4);+ // Vocabulary must match agent-avatar.js emotion keys+ expect(html).toContain('data-emotion="celebration"');+ expect(html).toContain('data-emotion="curiosity"');+ expect(html).toContain('data-emotion="empathy"');+ expect(html).toContain('data-emotion="concern"');+ });+});++describe('/features page — CSS contract', () => {+ it('establishes a perspective scroll container', () => {+ expect(css).toContain('perspective: var(--features-perspective)');+ expect(css).toMatch(/--features-perspective:\s*[\d.]+rem/);+ });++ it('layers use translateZ + scale to compensate for depth', () => {+ expect(css).toContain('translateZ(calc(var(--features-perspective)');+ expect(css).toContain('scale(calc(var(--depth) + 1))');+ });++ it('honors prefers-reduced-motion (collapses parallax)', () => {+ expect(css).toMatch(/@media \(prefers-reduced-motion: reduce\)/);+ });++ it('has a narrow-viewport flat layout', () => {+ expect(css).toMatch(/@media \(max-width: 768px\)/);+ });+});++describe('/features page — JS wiring', () => {+ it('lazy-boots Acts 2 and 3 via IntersectionObserver', () => {+ expect(js).toContain('IntersectionObserver');+ expect(js).toContain('agent-3d:not([eager])');+ });++ it('triggers expressEmotion() on emotion-chip click', () => {+ expect(js).toContain('expressEmotion');+ expect(js).toContain('data-emotion');+ });++ it('fetches a real on-chain agent via /api/agents/suggest', () => {+ expect(js).toContain('/api/agents/suggest');+ });++ it('paints a chain ribbon for Act 3', () => {+ expect(js).toContain('chain-pill');+ expect(js).toContain('CHAIN_LABELS');+ });+});++describe('<agent-3d> public API — expressEmotion()', () => {+ it('exposes expressEmotion as a public method', () => {+ // The method calls into the protocol with ACTION_TYPES.EMOTE.+ expect(elementJs).toMatch(/expressEmotion\s*\(/);+ expect(elementJs).toContain('ACTION_TYPES.EMOTE');+ });+});++describe('/features routing — vercel.json', () => {+ const routes = vercel.routes || [];++ it('serves /features from /features/index.html', () => {+ const r = routes.find((x) => x.src === '/features');+ expect(r?.dest).toBe('/features/index.html');+ });++ it('serves /features/ from /features/index.html', () => {+ const r = routes.find((x) => x.src === '/features/');+ expect(r?.dest).toBe('/features/index.html');+ });++ it('rewrites /features/(.*) to /features/$1 for assets', () => {+ const r = routes.find((x) => x.src === '/features/(.*)');+ expect(r?.dest).toBe('/features/$1');+ });++ it('redirects legacy /features.html → /features (301)', () => {+ const r = routes.find((x) => x.src === '/features.html');+ expect(r).toBeTruthy();+ expect(r.status).toBe(301);+ expect(r.headers?.Location).toBe('/features');+ });++ it('redirects come before catch-all rewrites', () => {+ const idx = (src) => routes.findIndex((x) => x.src === src);+ // /features.html redirect must precede /features rewrite+ expect(idx('/features.html')).toBeLessThan(idx('/features'));+ });+});