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: rename explore references to discover in code and comments
nirholas76c0f14742f7
diff --git a/README.md b/README.mdindex 5a9c0c56f..e06d2ea9a 100644--- a/README.md+++ b/README.md@@ -37,7 +37,7 @@ Save any avatar as a **widget** — a configured, shareable view that any site c```html<iframe- src="https://3dagent.vercel.app/#widget=wdgt_abc123"+ src="https://3dagent.vercel.app/app#widget=wdgt_abc123"width="600"height="600"style="border:0"@@ -176,7 +176,7 @@ Open **http://localhost:3000** for the landing page, or **http://localhost:3000/│ ├── cron/ → erc8004-crawl, index-delegations, run-dca, run-subscriptions│ ├── animations/, tts/, pinning/, api-keys/ → Supporting services│ └── _lib/ → Shared server helpers + `schema.sql`-├── public/ → Static subapps (studio, dashboard, widgets-gallery, agent, artifact, cz, my-agents, explore, validation, hydrate, lobehub, wallet, login.html, register.html) and default avatars+├── public/ → Static subapps (studio, dashboard, widgets-gallery, agent, artifact, cz, my-agents, discover, validation, hydrate, lobehub, wallet, login.html, register.html) and default avatars├── contracts/ → Smart contract sources├── sdk/, lobehub-plugin/ → Embedding SDK + Lobehub plugin├── scripts/ → Build, publish, icon, animation scriptsdiff --git a/api/widgets/page.js b/api/widgets/page.jsindex f408a195e..3ffc40215 100644--- a/api/widgets/page.js+++ b/api/widgets/page.js@@ -110,7 +110,7 @@ export default wrap(async (req, res) => {return;}- const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;+ const embedUrl = `${origin}/app#widget=${widget.id}&kiosk=true`;const oembedJs = `${origin}/api/widgets/oembed?url=${encodeURIComponent(pageUrl)}&format=json`;const title = widget.name || 'Widget';const typeLbl = TYPE_LABEL[widget.type] || 'Widget';diff --git a/docs/SMOKE_TEST.md b/docs/SMOKE_TEST.mdindex a6d3467cd..5a650adb3 100644--- a/docs/SMOKE_TEST.md+++ b/docs/SMOKE_TEST.md@@ -17,7 +17,7 @@| D. Share + embed | BLOCKED | Requires browser + running agent. Static analysis: `src/share-panel.js` exports `SharePanel`. CORS headers set in `api/_lib/http.js`. `agent-embed.html` has `frame-ancestors` CSP meta tag. || E. Embed bridge round-trip | BLOCKED | Requires browser. Static analysis: `src/embed-host-bridge.js` and `src/embed-action-bridge.js` implement ping/pong handshake. `op: 'speak'` mapped to `speak` action in bridge. || F. Idle loop | FAIL | `src/idle-animation.js` exports `IdleAnimation` class but it is **never imported anywhere** in the codebase. Blink + head-drift are not wired into the agent avatar system. Escalated — see defects below. |-| G. Discover page | BLOCKED | Requires seeded Base Sepolia wallet. Static analysis: `/public/explore/index.html` + `explore.js` present. `/api/explore.js` endpoint present. Import flow routes to `/hydrate`. |+| G. Discover page | BLOCKED | Requires seeded Base Sepolia wallet. Static analysis: `/public/discover/index.html` + `discover.js` present. `/api/explore.js` endpoint present. Import flow routes to `/hydrate`. || H. Deploy on-chain | BLOCKED | Requires MetaMask + Base Sepolia test ETH. Static analysis: `src/erc8004/agent-registry.js` + `src/agent-home-orphans.js` implement `DeployButton` wiring into `agent-home.html`. || I. LobeHub plugin | FAIL | `lobehub-plugin/dev/index.html` dev harness **does not exist** (required by Flow I step 2). `lobehub-plugin/` has `src/`, `dist/`, `package.json` but no `dev/` directory. Escalated — see defects below. || J. Dashboard sidebar | BLOCKED | Requires authenticated session. Static analysis: all 6 pages present (`index.html`, `actions.html`, `sessions.html`, `wallets.html`, `usage.html`, `embed-policy.html`). All import from `dashboard.js`. |@@ -42,7 +42,7 @@- [ ] **`lobehub-plugin/dev/index.html` does not exist** — `lobehub-plugin/dev/` — Prompt 05 (`final-integration/05-lobehub-real-integration.md`) specifies a dev harness at `lobehub-plugin/dev/index.html` that mocks the LobeChat host message contract and renders the avatar iframe. The directory does not exist. Flow I is fully BLOCKED. Fix: create `lobehub-plugin/dev/index.html` with a mock host page that posts a fake `assistant` message via the bridge and shows the iframe. This is new file creation — escalated per QA rules (> one file, requires functional knowledge of bridge.ts contract).-- [ ] **No `DISCOVER_LINK` nav entry wired in dashboard sidebar** — `public/dashboard/index.html` — The discover/explore page (`/explore`) has no sidebar link in the dashboard navigation. Users who discover an agent via Flow G must navigate directly to the URL. Low-priority UX gap; one-line fix in `public/dashboard/index.html` sidebar nav HTML, but deferred to avoid touching anchor-owned dashboard code during this pass.+- [ ] **No `DISCOVER_LINK` nav entry wired in dashboard sidebar** — `public/dashboard/index.html` — The community discover page (`/discover`) has no sidebar link in the dashboard navigation. Users who discover an agent via Flow G must navigate directly to the URL. Low-priority UX gap; one-line fix in `public/dashboard/index.html` sidebar nav HTML, but deferred to avoid touching anchor-owned dashboard code during this pass.- [ ] **`agent-embed.html` frame-ancestors CSP set via JS meta tag** — `agent-embed.html:136–145` — The `frame-ancestors` policy is dynamically injected as a `<meta http-equiv="Content-Security-Policy">` tag at runtime, which browsers ignore for frame-ancestors directives (CSP `frame-ancestors` must be set via HTTP header, not meta tag). This means any origin can embed the agent iframe. Real fix requires a Vercel edge function or server-side header injection — out of scope for a ≤10-line patch.diff --git a/docs/WIDGETS.md b/docs/WIDGETS.mdindex 00f8bea01..70aaa2f48 100644--- a/docs/WIDGETS.md+++ b/docs/WIDGETS.md@@ -48,7 +48,7 @@ Every widget has three canonical URLs.| URL | Use it for || ------------------------------------------------ | --------------------------------------------------------------- || `https://3dagent.vercel.app/w/<id>` | Sharing in Slack/Discord/X — server-rendered with rich OG card. |-| `https://3dagent.vercel.app/#widget=<id>` | The SPA viewer with the widget config applied. |+| `https://3dagent.vercel.app/app#widget=<id>` | The SPA viewer with the widget config applied. || `https://3dagent.vercel.app/api/widgets/<id>/og` | The 1200×630 preview image. |`/w/<id>` is the recommended share URL — bots get an OG preview, browsers fall through to the SPA.@@ -73,7 +73,7 @@ The viewer supports the following hash params (combine with `&`):```html<iframe- src="https://3dagent.vercel.app/#widget=wdgt_abc123def456&kiosk=true"+ src="https://3dagent.vercel.app/app#widget=wdgt_abc123def456&kiosk=true"width="600"height="600"style="border:0;border-radius:12px;max-width:100%"@@ -200,7 +200,7 @@ Returns standard [oEmbed v1.0](https://oembed.com) JSON, type `rich`.}```-Accepts both `https://host/w/<id>` and `https://host/#widget=<id>` forms. Optional `maxwidth` / `maxheight` clamp the returned iframe dimensions.+Accepts both `https://host/w/<id>` and `https://host/app#widget=<id>` forms. Optional `maxwidth` / `maxheight` clamp the returned iframe dimensions.---diff --git a/home.html b/home.htmlindex c264bfd43..fdb73188d 100644--- a/home.html+++ b/home.html@@ -225,7 +225,7 @@<div class="h-embed-code h-reveal"><span class="tag"><iframe</span><span class="attr"> src</span>=<span class="attr"- >"https://3dagent.vercel.app/#widget=wdgt_abc123"</span+ >"https://3dagent.vercel.app/app#widget=wdgt_abc123"</span><span class="tag">/></span></div>diff --git a/index.html b/index.htmlindex fefe8bd0f..454e00a1e 100644--- a/index.html+++ b/index.html@@ -487,6 +487,24 @@}}</style>+ <script>+ // Legacy embed redirect: pre-`/app` widget iframes used `/#widget=<id>`+ // (and `?kiosk=true&...`) directly against the marketing landing.+ // Keep those working by forwarding to the SPA viewer at /app.+ (function () {+ try {+ var h = window.location.hash || '';+ var s = window.location.search || '';+ if (+ /(?:^|[#&?])widget=[A-Za-z0-9_-]+/.test(h) ||+ /(?:^|[#&?])kiosk=true\b/.test(h) ||+ /(?:^|[?&])kiosk=true\b/.test(s)+ ) {+ window.location.replace('/app' + s + h);+ }+ } catch (e) {}+ })();+ </script></head><body class="features-page"><a href="#main-content" class="skip-link">Skip to main content</a>diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex 09ad7bae4..8c8203275 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -104,27 +104,28 @@ async function renderAvatars(root) {function avatarCard(a) {const el = document.createElement('div');el.className = 'card';- const preview = a.model_url- ? `<model-viewer src="${attr(a.model_url)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces"></model-viewer>`- : `<span>Private · preview requires signed URL</span>`;el.innerHTML = `- <div class="preview">${preview}</div>+ <div class="preview" data-preview></div><h3>${esc(a.name)}</h3><p class="meta">${a.size_bytes ? fmtSize(a.size_bytes) : ''} · ${esc(a.visibility)} · ${new Date(a.created_at).toLocaleDateString()}</p>- <div class="row" style="gap:6px; margin-bottom:10px">${a.tags.map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div>- <div class="row" style="justify-content:space-between">- <select data-vis>${['private', 'unlisted', 'public'].map((v) => `<option ${v === a.visibility ? 'selected' : ''} value="${v}">${v}</option>`).join('')}</select>- <div class="row" style="gap:6px">+ <div class="row" style="gap:6px; margin-bottom:10px; flex-wrap:wrap">${a.tags.map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div>+ <div class="footer">+ <select data-vis aria-label="Visibility">${['private', 'unlisted', 'public'].map((v) => `<option ${v === a.visibility ? 'selected' : ''} value="${v}">${v}</option>`).join('')}</select>+ <div class="actions"><a class="btn sec" href="#edit/${encodeURIComponent(a.id)}">Edit</a><button class="btn sec" data-replace>Replace GLB</button><a class="btn sec" href="/deploy?avatar=${encodeURIComponent(a.id)}" title="Mint as ERC-8004 agent">Deploy on-chain</a>- <button class="btn sec" data-del>Delete</button>+ <button class="btn sec danger" data-del>Delete</button></div></div>`;+ const previewEl = el.querySelector('[data-preview]');+ mountAvatarPreview(previewEl, a);+el.querySelector('[data-vis]').addEventListener('change', async (e) => {try {await api.patchAvatar(a.id, { visibility: e.target.value });+ a.visibility = e.target.value;} catch (err) {alert(err.message);}@@ -142,6 +143,71 @@ function avatarCard(a) {return el;}+// Lazy-load preview when card scrolls into view. For private avatars, fetch+// a short-lived signed URL via /api/avatars/:id. Falls back to a thumbnail or+// placeholder if no preview is available.+function mountAvatarPreview(host, a) {+ const showPlaceholder = (msg) => {+ host.innerHTML = `<div class="ph">${esc(msg)}</div>`;+ };+ const showSpinner = () => {+ host.innerHTML = '<div class="spinner" aria-label="Loading preview"></div>';+ };+ const showModel = (url) => {+ host.innerHTML = `<model-viewer src="${attr(url)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces" loading="lazy" reveal="auto"></model-viewer>`;+ };+ const showThumb = (url) => {+ host.innerHTML = `<img class="thumb" src="${attr(url)}" alt="${attr(a.name)} thumbnail" loading="lazy">`;+ };++ let loaded = false;+ const load = async () => {+ if (loaded) return;+ loaded = true;+ if (a.model_url) {+ showModel(a.model_url);+ return;+ }+ // Private — request a signed URL.+ showSpinner();+ try {+ const { avatar } = await api.getAvatar(a.id);+ const url = avatar?.url || avatar?.model_url;+ if (url) {+ showModel(url);+ } else if (avatar?.thumbnail_url) {+ showThumb(avatar.thumbnail_url);+ } else {+ showPlaceholder('Preview unavailable');+ }+ } catch (err) {+ loaded = false;+ host.innerHTML = `<div class="ph">Preview unavailable<br><button data-retry>Retry</button></div>`;+ host.querySelector('[data-retry]').addEventListener('click', load);+ }+ };++ if (a.thumbnail_url) showThumb(a.thumbnail_url);+ else host.innerHTML = '<div class="ph">Loading preview…</div>';++ if ('IntersectionObserver' in window) {+ const io = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting) {+ io.disconnect();+ load();+ }+ }+ },+ { rootMargin: '200px' },+ );+ io.observe(host);+ } else {+ load();+ }+}+// ── Replace GLB ─────────────────────────────────────────────────────────────// Shows an inline warning banner on the card, then opens a file picker.// Validates extension, MIME, and GLB magic number before uploading.@@ -775,7 +841,7 @@ function renderMcp(root) {async function renderEmbed(root) {root.innerHTML = `<h1>Embed your agent</h1>- <p class="sub">Drop your agent into Lobehub, Claude Artifacts, your site, or anywhere that can render an iframe. The agent reacts to chat messages via a postMessage bridge.</p>+ <p class="sub">Drop your agent into chat hosts, Claude Artifacts, your site, or anywhere that can render an iframe. The agent reacts to chat messages via a postMessage bridge.</p><div id="embed-body"><div class="muted">Loading your agent…</div></div>`;const body = root.querySelector('#embed-body');@@ -800,7 +866,7 @@ async function renderEmbed(root) {const homeUrl = `${origin}/agent/${encodeURIComponent(agent.id)}`;const iframeSnippet = `<iframe src="${embedUrl}" allow="camera; microphone" style="width:320px;height:420px;border:0;border-radius:16px;overflow:hidden" title="${esc(agent.name || 'Agent')}"></iframe>`;const lobehubSnippet = [- '// Drop into a Lobehub fork — renders the agent alongside the chat panel',+ '// Drop into a chat host — renders the agent alongside the chat panel','// and forwards assistant messages to it so the avatar speaks/emotes.',"import { useEffect, useRef } from 'react';",'',@@ -885,13 +951,13 @@ async function renderEmbed(root) {</div><div>${snippetBlock('Universal iframe (any site)', iframeSnippet, 'html')}- ${snippetBlock('Lobehub React sidecar', lobehubSnippet, 'tsx')}+ ${snippetBlock('Chat host React sidecar', lobehubSnippet, 'tsx')}${snippetBlock('Claude Artifact', claudeSnippet, 'html')}${snippetBlock('postMessage bridge (speak + listen)', postMessageSnippet, 'js')}${snippetBlock('Custom embed (Agent3D SDK · Bridge v1)', sdkSnippet, 'html')}<div class="card" style="margin-top:14px"><h3 style="margin:0 0 6px">Who can embed?</h3>- <p class="muted" style="margin:0 0 10px">By default anyone. Lock it down to specific hosts (your Lobehub deploy, your Substack…) on the <a href="/dashboard/embed-policy?agent=${encodeURIComponent(agent.id)}">embed-policy page</a>.</p>+ <p class="muted" style="margin:0 0 10px">By default anyone. Lock it down to specific hosts (your chat app, your Substack…) on the <a href="/dashboard/embed-policy?agent=${encodeURIComponent(agent.id)}">embed-policy page</a>.</p></div>${onchainCard(agent)}${myAgentsCard()}@@ -928,7 +994,7 @@ function snippetBlock(title, code, _lang) {<strong>${esc(title)}</strong><button class="btn sec" data-copy="#${id}" type="button">Copy</button></div>- <pre id="${id}" style="margin:0; max-height:260px">${esc(code)}</pre>+ <pre id="${id}" style="margin:0; max-height:260px; overflow:auto; white-space:pre">${esc(code)}</pre></div>`;}@@ -1515,7 +1581,7 @@ function widgetCard(w, ctx) {card.className = 'widget-card card';card.dataset.id = w.id;- const previewSrc = `/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;+ const previewSrc = `/app#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;const previewHtml = w.avatar? `<iframe data-src="${attr(previewSrc)}" loading="lazy" tabindex="-1" title="Preview of ${attr(w.name || 'widget')}"></iframe>`: `<div class="placeholder">Avatar unavailable.<br>Edit to pick a replacement.</div>`;@@ -1689,7 +1755,7 @@ async function openWidgetDrawer(w, ctx) {drawer.setAttribute('aria-label', `Widget details — ${w.name || 'untitled'}`);drawer.tabIndex = -1;- const previewSrc = `/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;+ const previewSrc = `/app#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;const iframeSnippet = makeIframeSnippet(w, pageUrl, 600, 600);const scriptSnippet = `<script async src="${location.origin}/embed.js" data-widget="${esc(w.id)}"></script>`;@@ -1904,7 +1970,7 @@ function openShareModal(w) {const maxW = 320,maxH = 320;const scale = Math.min(maxW / dim.width, maxH / dim.height, 1);- previewEl.innerHTML = `<iframe src="/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1" style="width:${dim.width}px; height:${dim.height}px; border:0; transform:scale(${scale}); transform-origin:center" title="Preview"></iframe>`;+ previewEl.innerHTML = `<iframe src="/app#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1" style="width:${dim.width}px; height:${dim.height}px; border:0; transform:scale(${scale}); transform-origin:center" title="Preview"></iframe>`;previewEl.style.width = `${dim.width * scale}px`;previewEl.style.height = `${dim.height * scale}px`;}diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 64d3684a4..edd734cc0 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -121,11 +121,77 @@place-items: center;color: #555;font-size: 12px;+ position: relative;}.preview model-viewer {width: 100%;height: 100%;}+ .preview img.thumb {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }+ .preview .ph {+ padding: 12px;+ text-align: center;+ color: #666;+ }+ .preview .ph button {+ margin-top: 8px;+ padding: 6px 12px;+ border-radius: 7px;+ border: 1px solid var(--border);+ background: #1a1a24;+ color: #ddd;+ font-size: 12px;+ cursor: pointer;+ }+ .preview .ph button:hover {+ background: #22222e;+ }+ .preview .spinner {+ width: 22px;+ height: 22px;+ border: 2px solid #2a2a36;+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 0.7s linear infinite;+ }+ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }+ .card .footer {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }+ .card .footer select[data-vis] {+ align-self: flex-start;+ padding: 6px 10px;+ font-size: 12px;+ }+ .card .actions {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ }+ .card .actions .btn,+ .card .actions a.btn {+ padding: 6px 10px;+ font-size: 12px;+ border-radius: 7px;+ font-weight: 500;+ }+ .card .actions .danger {+ color: #ffb3b3;+ }+ .card .actions .danger:hover {+ background: rgba(204, 64, 64, 0.18);+ }.row {display: flex;align-items: center;@@ -630,6 +696,173 @@}}+ /* ── Animations tab ──────────────────────────────────────────────── */+ .anim-cols {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);+ gap: 28px;+ align-items: start;+ }+ @media (max-width: 880px) {+ .anim-cols {+ grid-template-columns: 1fr;+ }+ }+ .anim-cols h3 {+ margin: 0 0 12px;+ font-size: 14px;+ font-weight: 600;+ color: #ddd;+ }+ .anim-notice {+ background: rgba(106, 92, 255, 0.08);+ border: 1px solid rgba(106, 92, 255, 0.35);+ color: #d6cffd;+ border-radius: 10px;+ padding: 12px 14px;+ margin-bottom: 18px;+ font-size: 13px;+ line-height: 1.55;+ }+ .anim-notice strong {+ color: #fff;+ }+ .clip-row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto auto auto;+ align-items: center;+ gap: 10px;+ padding: 10px 12px;+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ margin-bottom: 8px;+ }+ .clip-row .clip-name {+ font-size: 13px;+ color: #eee;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .clip-row .clip-source {+ font-size: 11px;+ padding: 2px 8px;+ border-radius: 99px;+ background: #20202c;+ color: #aaa;+ text-transform: capitalize;+ }+ .clip-row .loop-toggle {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 12px;+ color: #aaa;+ cursor: pointer;+ user-select: none;+ }+ .clip-row .loop-toggle input {+ margin: 0;+ accent-color: var(--accent);+ }+ .clip-row .clip-actions {+ display: inline-flex;+ gap: 6px;+ }+ .clip-row .clip-actions button {+ padding: 5px 10px;+ border-radius: 7px;+ border: 1px solid var(--border);+ background: #1a1a24;+ color: #ddd;+ font-size: 12px;+ cursor: pointer;+ }+ .clip-row .clip-actions button:hover {+ background: #22222e;+ }+ .clip-row .clip-actions button.danger:hover {+ background: rgba(204, 64, 64, 0.18);+ border-color: rgba(204, 64, 64, 0.5);+ color: #ffb3b3;+ }+ .preset-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));+ gap: 10px;+ }+ .preset-tile {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 12px 8px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ cursor: pointer;+ transition:+ border-color 0.15s,+ background 0.15s,+ transform 0.15s;+ user-select: none;+ position: relative;+ }+ .preset-tile:hover {+ border-color: var(--accent);+ background: rgba(106, 92, 255, 0.08);+ transform: translateY(-1px);+ }+ .preset-tile .icon {+ font-size: 26px;+ line-height: 1;+ }+ .preset-tile .label {+ font-size: 12px;+ color: #ddd;+ text-align: center;+ }+ .preset-tile.attached {+ opacity: 0.45;+ cursor: default;+ }+ .preset-tile.attached:hover {+ border-color: var(--border);+ background: var(--panel);+ transform: none;+ }+ .preset-tile.attached::after {+ content: '✓';+ position: absolute;+ top: 4px;+ right: 6px;+ font-size: 11px;+ color: #6a5cff;+ }+ .anim-upload {+ display: flex;+ flex-direction: column;+ gap: 6px;+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 14px;+ }+ .anim-upload label {+ font-size: 12px;+ color: #aaa;+ }+ .anim-upload input[type='text'],+ .anim-upload input[type='file'] {+ font-size: 13px;+ }+ .anim-inline-err {+ color: #ffb3b3;+ font-size: 12px;+ min-height: 16px;+ }+/* visually-hidden utility for screen-reader-only labels */.sr-only {position: absolute;diff --git a/public/discover/discover.js b/public/discover/discover.jsindex 99ea42de3..c6a6cb255 100644--- a/public/discover/discover.js+++ b/public/discover/discover.js@@ -1,7 +1,8 @@/*** /discover — ERC-8004 agent marketplace grid.*- * Pulls from GET /api/explore. Filters + infinite pagination via cursor.+ * Pulls from GET /api/explore (legacy endpoint name, indexes ERC-8004 directory).+ * Filters + infinite pagination via cursor.* Clicking a card opens the on-chain token page on the source chain's* explorer; clicking the 3D preview (when present) loads the GLB in the* main viewer via /#model=<url>.@@ -41,8 +42,16 @@ const els = {loadMore: document.querySelector('[data-role="load-more"]'),statAll: document.querySelector('[data-role="stat-all"]'),stat3d: document.querySelector('[data-role="stat-3d"]'),+ myAgentsChip: document.querySelector('[data-role="my-agents-chip"]'),};+// Reveal "View my agents" chip when signed in. Same probe as index.html.+fetch('/api/auth/me', { credentials: 'include' })+ .then((r) => {+ if (r.ok && els.myAgentsChip) els.myAgentsChip.hidden = false;+ })+ .catch(() => {});+// Populate chain dropdown.for (const c of CHAINS) {const opt = document.createElement('option');diff --git a/public/discover/index.html b/public/discover/index.htmlindex 900f7badd..9dae5241d 100644--- a/public/discover/index.html+++ b/public/discover/index.html@@ -37,9 +37,19 @@<main class="features-main explore-main"><section class="explore-hero">- <div class="explore-hero-chip">- <span class="explore-hero-dot"></span>- <span>ERC-8004 Agent Directory</span>+ <div class="explore-hero-chips">+ <div class="explore-hero-chip">+ <span class="explore-hero-dot"></span>+ <span>ERC-8004 Agent Directory</span>+ </div>+ <a+ href="/my-agents"+ class="explore-hero-chip explore-hero-chip--link"+ data-role="my-agents-chip"+ hidden+ >+ <span>View my agents →</span>+ </a></div><h2>Every agent, every chain.</h2><p class="explore-sub">diff --git a/public/docs-widgets.html b/public/docs-widgets.htmlindex b671b445a..b5e1774ff 100644--- a/public/docs-widgets.html+++ b/public/docs-widgets.html@@ -229,7 +229,7 @@<td>Sharing in Slack/Discord/X — server-rendered with rich OG card.</td></tr><tr>- <td><code>/#widget=<id></code></td>+ <td><code>/app#widget=<id></code></td><td>The SPA viewer with the widget config applied.</td></tr><tr>@@ -282,7 +282,7 @@<h2 id="embedding">Embedding</h2><h3>iframe (recommended)</h3><pre><code><iframe- src="https://3dagent.vercel.app/#widget=wdgt_abc123def456&kiosk=true"+ src="https://3dagent.vercel.app/app#widget=wdgt_abc123def456&kiosk=true"width="600"height="600"style="border:0;border-radius:12px;max-width:100%"@@ -387,7 +387,7 @@<p>Returns standard <a href="https://oembed.com">oEmbed v1.0</a> JSON, type<code>rich</code>. Accepts both <code>/w/<id></code> and- <code>/#widget=<id></code> forms.+ <code>/app#widget=<id></code> forms.</p><h2 id="csp-cors">CSP / CORS</h2>diff --git a/public/embed.js b/public/embed.jsindex 8836141d9..3394c393c 100644--- a/public/embed.js+++ b/public/embed.js@@ -41,7 +41,7 @@var radius = attr(scriptEl, 'data-radius', '12');var border = attr(scriptEl, 'data-border', '0');- var src = ORIGIN + '/#widget=' + encodeURIComponent(widgetId) + '&kiosk=true';+ var src = ORIGIN + '/app#widget=' + encodeURIComponent(widgetId) + '&kiosk=true';var iframe = document.createElement('iframe');iframe.src = src;diff --git a/public/my-agents/my-agents.css b/public/my-agents/my-agents.cssindex dbffd8e4e..42a5dae18 100644--- a/public/my-agents/my-agents.css+++ b/public/my-agents/my-agents.css@@ -317,6 +317,21 @@ a:hover {margin: 0 0 18px;}+.my-agents-secondary {+ display: inline-block;+ margin-top: 14px;+ font-size: 13px;+ color: #888;+ text-decoration: none;+ border-bottom: 1px solid transparent;+ transition: color 0.15s ease, border-color 0.15s ease;+}+.my-agents-secondary:hover,+.my-agents-secondary:focus-visible {+ color: #ccc;+ border-bottom-color: #ccc;+}+/* ── Error banner ────────────────────────────────────────────────────── */.discover-error-banner {padding: 14px 16px;diff --git a/public/my-agents/my-agents.js b/public/my-agents/my-agents.jsindex 29b81a35a..a2ad5ab11 100644--- a/public/my-agents/my-agents.js+++ b/public/my-agents/my-agents.js@@ -211,6 +211,7 @@ async function loadAgents() {'🔭','No on-chain agents yet','No ERC-8004 agents found in your linked wallets.',+ { label: 'Browse community agents →', href: '/discover' },);return;}diff --git a/public/robots.txt b/public/robots.txtindex fb4b4747d..5943df60e 100644--- a/public/robots.txt+++ b/public/robots.txt@@ -1,3 +1,4 @@User-agent: *Allow: /+Disallow: /my-agentsSitemap: https://3dagent.vercel.app/sitemap.xmldiff --git a/public/studio/studio.js b/public/studio/studio.jsindex 6a6d3c80f..2a5caa7a4 100644--- a/public/studio/studio.js+++ b/public/studio/studio.js@@ -492,7 +492,7 @@ async function save({ generate }) {function openEmbedModal(widget) {const origin = location.origin;const shareUrl = `${origin}/w/${widget.id}`;- const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;+ const embedUrl = `${origin}/app#widget=${widget.id}&kiosk=true`;$('#embed-share-url').value = shareUrl;$('#embed-iframe-snippet').value =`<iframe src="${embedUrl}" width="600" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" loading="lazy"></iframe>`;diff --git a/scripts/tmp-http-sweep.mjs b/scripts/tmp-http-sweep.mjsindex c97808506..510c6e416 100644--- a/scripts/tmp-http-sweep.mjs+++ b/scripts/tmp-http-sweep.mjs@@ -27,7 +27,7 @@ const paths = ['/dashboard/embed-policy.html','/hydrate/','/studio/',- '/explore/',+ '/discover/','/artifact/','/widgets-gallery/','/docs-widgets.html',diff --git a/scripts/tmp-page-sweep.mjs b/scripts/tmp-page-sweep.mjsindex 9ea3aaef1..4a755e229 100644--- a/scripts/tmp-page-sweep.mjs+++ b/scripts/tmp-page-sweep.mjs@@ -28,7 +28,7 @@ const paths = ['/public/dashboard/embed-policy.html','/public/hydrate/index.html','/public/studio/index.html',- '/public/explore/index.html',+ '/public/discover/index.html','/public/artifact/index.html','/public/widgets-gallery/index.html','/public/docs-widgets.html',diff --git a/src/app.js b/src/app.jsindex c86d2e147..dd7c06c71 100644--- a/src/app.js+++ b/src/app.js@@ -136,7 +136,6 @@ class App {widget: hash.widget || '',deploy: hash.deploy !== undefined || location.pathname === '/deploy',onchain, // { chainId, agentId, registry? } | null- explore: location.pathname === '/explore',showcase: location.pathname === '/showcase' || location.pathname === '/showcase/',// pending=1 signals a post-login save round-trippending: qp.get('pending') === '1',@@ -199,13 +198,6 @@ class App {return;}- // /explore — gallery of on-chain agents with 3D avatars.- if (options.explore) {- this._showExplorePage();- this._initAgentSystem();- return;- }-// /showcase — browsable marketplace of every indexed 3D agent.if (options.showcase) {this._showShowcasePage();@@ -1342,29 +1334,6 @@ class App {`;}- async _showExplorePage() {- try {- const main = this.el.querySelector('main.wrap') || this.el;- this.dropEl?.classList.add('hidden');- const dropzone = this.el.querySelector('.dropzone');- if (dropzone) dropzone.style.display = 'none';- if (this.viewerContainerEl) this.viewerContainerEl.style.display = 'none';- const authGate = this.el.querySelector('#auth-gate');- if (authGate) authGate.style.display = 'none';- const presence = this.el.querySelector('.agent-presence-sidebar');- if (presence) presence.style.display = 'none';-- const page = document.createElement('section');- page.className = 'explore-page';- main.appendChild(page);-- const { renderExplorePage } = await import('./erc8004/explore.js');- renderExplorePage(page);- } catch (err) {- console.error('[3d-agent] explore page load failed', err);- }- }-async _showShowcasePage() {try {const main = this.el.querySelector('main.wrap') || this.el;diff --git a/src/erc8004/explore.js b/src/erc8004/explore.jsdeleted file mode 100644index 59cb5343a..000000000--- a/src/erc8004/explore.js+++ /dev/null@@ -1,938 +0,0 @@-/**- * /explore — the public on-chain avatar browser.- *- * Paste any of the following into the big input and see every matching- * ERC-8004 registered 3D avatar on every supported chain:- *- * - EVM address (0x…40 hex) → all agents owned by that wallet- * - ENS name (vitalik.eth) → resolved to address then fanned out- * - Transaction hash (0x…64 hex) → every Registered event in that tx- * - Agent ID (6443) → same id on every chain (fan-out)- * - agent:// URI (agent://base/123) → precise single lookup- *- * Empty query → latest Registered events on Base mainnet (fallback: BSC Testnet).- *- * Clicking a card opens /a/<chainId>/<agentId> which renders the 3D avatar via- * app.js `_loadOnChainAgent`.- *- * Lazy-loaded by src/app.js `_showExplorePage`.- */--import {- autoResolve,- detectInputType,- hydrateAgent,- INPUT_TYPES,- DEFAULT_FAN_OUT_CHAINS,- splitChainsByNet,-} from './resolve-avatar.js';-import { listRegisteredEvents } from './queries.js';-import { CHAIN_META } from './chain-meta.js';-import { resolveURI } from '../ipfs.js';--const RECENT_KEY = '3dagent.explore.recent';-const CHAINS_KEY = '3dagent.explore.chains';-const RECENT_MAX = 8;-const FEATURED_CHAIN_ID = 8453;-const FEATURED_FALLBACK_CHAIN_ID = 97;-const FEATURED_COUNT = 12;-const FEATURED_SCAN_BLOCKS = 250000;--const esc = (s) =>- String(s ?? '').replace(- /[&<>"']/g,- (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],- );--const shortAddr = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : '');--const INPUT_TYPE_LABEL = {- [INPUT_TYPES.ADDRESS]: 'Wallet address',- [INPUT_TYPES.ENS]: 'ENS name',- [INPUT_TYPES.TX_HASH]: 'Transaction hash',- [INPUT_TYPES.AGENT_ID]: 'Agent ID',- [INPUT_TYPES.AGENT_URI]: 'agent:// URI',- [INPUT_TYPES.UNKNOWN]: 'Unrecognized',-};--const EXAMPLES = [- { label: 'Agent #1 on Base', value: 'agent://base/1' },- { label: 'vitalik.eth', value: 'vitalik.eth' },- { label: 'Agent #1', value: '1' },-];--/**- * Entry point called by app.js `_showExplorePage`.- * @param {HTMLElement} container- */-export function renderExplorePage(container) {- const page = new ExplorePage(container);- page.mount();- return page;-}--// ───────────────────────────────────────────────────────────────────────────-// ExplorePage-// ───────────────────────────────────────────────────────────────────────────--class ExplorePage {- /** @param {HTMLElement} container */- constructor(container) {- this.container = container;- this._chains = loadChainSelection();- this._results = [];- this._query = '';- this._queryType = INPUT_TYPES.UNKNOWN;- this._resolvedAddress = '';- this._loading = false;- this._perChainState = new Map();- this._filter = 'all';- this._abortCounter = 0;- this._onHashChange = () => this._loadFromURL({ replace: false });- }-- mount() {- this.container.innerHTML = `- <div class="explore-shell">- <header class="explore-hero">- <div class="explore-hero-inner">- <div class="explore-eyebrow">ERC-8004 · On-chain avatars</div>- <h1 class="explore-title">See anyone's 3D self.</h1>- <p class="explore-subtitle">- Paste a wallet, ENS name, transaction, or agent ID to resolve every- on-chain avatar they've minted — across every supported chain.- </p>- <form class="explore-form" data-role="form" autocomplete="off">- <div class="explore-input-wrap">- <input- class="explore-input"- name="q"- placeholder="0xabc… · vitalik.eth · tx hash · agent ID"- spellcheck="false"- autocapitalize="off"- />- <button type="submit" class="explore-btn explore-btn--primary">Resolve</button>- </div>- <div class="explore-input-meta" data-role="inputMeta"></div>- </form>- <div class="explore-examples" data-role="examples"></div>- </div>- </header>-- <section class="explore-controls">- <div class="explore-controls-row">- <strong class="explore-controls-lbl">Chains</strong>- <div class="explore-chain-chips" data-role="chainChips"></div>- <div class="explore-controls-spacer"></div>- <div class="explore-progress" data-role="progress" hidden></div>- </div>- </section>-- <section class="explore-results" data-role="results"></section>- </div>- `;-- this._renderExamples();- this._renderChainChips();- this._bindForm();-- window.addEventListener('hashchange', this._onHashChange);- window.addEventListener('popstate', this._onHashChange);-- this._loadFromURL({ replace: true });- }-- destroy() {- window.removeEventListener('hashchange', this._onHashChange);- window.removeEventListener('popstate', this._onHashChange);- }-- // ── URL ↔ state ───────────────────────────────────────────────────────-- _loadFromURL({ replace }) {- const { q } = parseURL();- const input = this.container.querySelector('.explore-input');- if (q) {- input.value = q;- this._query = q;- this._runResolve(q, { pushHistory: false });- } else {- input.value = '';- this._query = '';- this._results = [];- this._showFeatured();- }- this._updateInputMeta(input.value);- }-- _pushURL(q) {- const url = new URL(location.href);- if (q) url.searchParams.set('q', q);- else url.searchParams.delete('q');- history.pushState({}, '', url.toString());- }-- // ── Input ─────────────────────────────────────────────────────────────-- _bindForm() {- const form = this.container.querySelector('[data-role="form"]');- const input = form.querySelector('.explore-input');- form.addEventListener('submit', (e) => {- e.preventDefault();- const q = input.value.trim();- if (!q) return;- this._pushURL(q);- this._runResolve(q);- });- input.addEventListener('input', () => this._updateInputMeta(input.value));- }-- _updateInputMeta(value) {- const el = this.container.querySelector('[data-role="inputMeta"]');- const v = String(value || '').trim();- if (!v) {- el.innerHTML = '';- el.className = 'explore-input-meta';- return;- }- const type = detectInputType(v);- const label = INPUT_TYPE_LABEL[type];- const cls =- type === INPUT_TYPES.UNKNOWN ? 'explore-inputmeta--warn' : 'explore-inputmeta--ok';- el.className = `explore-input-meta ${cls}`;- el.textContent = `Detected: ${label}`;- }-- _renderExamples() {- const recent = loadRecent();- const root = this.container.querySelector('[data-role="examples"]');- const entries = recent.length ? recent : EXAMPLES;- root.innerHTML = `- <span class="explore-examples-lbl">${recent.length ? 'Recent:' : 'Try:'}</span>- ${entries- .map(- (e) => `- <button type="button" class="explore-example" data-q="${esc(e.value || e)}">${esc(e.label || e.value || e)}</button>- `,- )- .join('')}- `;- this._wireExampleClicks(root);- }-- // ── Chain chips ───────────────────────────────────────────────────────-- _renderChainChips() {- const root = this.container.querySelector('[data-role="chainChips"]');- const { mainnet, testnet } = splitChainsByNet();- const chipHTML = (id) => {- const m = CHAIN_META[id];- if (!m) return '';- const active = this._chains.includes(id);- return `- <button type="button"- class="explore-chain-chip ${active ? 'explore-chain-chip--active' : ''} ${m.testnet ? 'explore-chain-chip--testnet' : ''}"- data-chain="${id}"- title="${esc(m.name)}"- >- <span class="explore-chain-dot"></span>- ${esc(m.shortName || m.name)}- </button>- `;- };- root.innerHTML = `- <div class="explore-chain-group">${mainnet.map(chipHTML).join('')}</div>- <div class="explore-chain-divider">·</div>- <div class="explore-chain-group explore-chain-group--testnet">- ${testnet.map(chipHTML).join('')}- </div>- <button type="button" class="explore-chain-presets-btn" data-role="preset-main">Mainnets</button>- <button type="button" class="explore-chain-presets-btn" data-role="preset-all">All</button>- `;- root.querySelectorAll('.explore-chain-chip').forEach((chip) => {- chip.addEventListener('click', () => {- const id = Number(chip.dataset.chain);- const idx = this._chains.indexOf(id);- if (idx >= 0) this._chains.splice(idx, 1);- else this._chains.push(id);- saveChainSelection(this._chains);- this._renderChainChips();- if (this._query) this._runResolve(this._query, { pushHistory: false });- });- });- root.querySelector('[data-role="preset-main"]').addEventListener('click', () => {- const { mainnet } = splitChainsByNet();- this._chains = mainnet.slice();- saveChainSelection(this._chains);- this._renderChainChips();- if (this._query) this._runResolve(this._query, { pushHistory: false });- });- root.querySelector('[data-role="preset-all"]').addEventListener('click', () => {- const { mainnet, testnet } = splitChainsByNet();- this._chains = [...mainnet, ...testnet];- saveChainSelection(this._chains);- this._renderChainChips();- if (this._query) this._runResolve(this._query, { pushHistory: false });- });- }-- // ── Resolve ───────────────────────────────────────────────────────────-- async _runResolve(rawInput, { pushHistory = true } = {}) {- const q = String(rawInput || '').trim();- if (!q) return;-- this._query = q;- this._queryType = detectInputType(q);- this._resolvedAddress = '';- this._perChainState = new Map();- this._loading = true;- this._abortCounter++;- const thisAbort = this._abortCounter;-- pushRecent(q);- this._renderExamples();-- const chains = this._chains.length ? this._chains.slice() : DEFAULT_FAN_OUT_CHAINS.slice();- this._renderProgress(chains);- this._renderResultsSkeleton();-- try {- const { type, resolvedAddress, results } = await autoResolve({- input: q,- chainIds: chains,- ethProvider: window.ethereum,- onProgress: (chainId, stage, payload) => {- if (thisAbort !== this._abortCounter) return;- this._perChainState.set(chainId, { stage, payload });- this._renderProgress(chains);- },- });- if (thisAbort !== this._abortCounter) return;-- this._queryType = type;- this._resolvedAddress = resolvedAddress || '';- this._results = results || [];- this._loading = false;- this._renderResults();- this._hideProgress();- } catch (err) {- if (thisAbort !== this._abortCounter) return;- this._loading = false;- this._hideProgress();- this._renderError(err.message || String(err));- }- }-- // ── Progress HUD ──────────────────────────────────────────────────────-- _renderProgress(chains) {- const root = this.container.querySelector('[data-role="progress"]');- if (!this._loading) {- root.hidden = true;- return;- }- root.hidden = false;- const done = chains.filter((c) => this._perChainState.get(c)?.stage === 'done').length;- const errored = chains.filter((c) => this._perChainState.get(c)?.stage === 'error').length;- root.innerHTML = `- <span class="explore-progress-spinner"></span>- <span>Resolving ${done}/${chains.length} chains${errored ? ` · ${errored} errored` : ''}</span>- `;- }-- _hideProgress() {- const root = this.container.querySelector('[data-role="progress"]');- root.hidden = true;- }-- // ── Results ───────────────────────────────────────────────────────────-- _renderResultsSkeleton() {- const out = this.container.querySelector('[data-role="results"]');- const chains = this._chains.length ? this._chains : DEFAULT_FAN_OUT_CHAINS;- const n = this._queryType === INPUT_TYPES.AGENT_ID ? chains.length : 6;- out.innerHTML = `- <div class="explore-grid" aria-busy="true">- ${Array.from({ length: n })- .map(- () => `- <div class="explore-card explore-card--skel">- <div class="explore-skel-img"></div>- <div class="explore-skel-line"></div>- <div class="explore-skel-line explore-skel-line--short"></div>- </div>- `,- )- .join('')}- </div>- `;- }-- _renderResults() {- const out = this.container.querySelector('[data-role="results"]');- const results = this._results;- const summary = this._renderSummary();-- if (!results.length) {- out.innerHTML = `- ${summary}- <div class="explore-empty">- <div class="explore-empty-art">🫥</div>- <h3>No on-chain avatars found.</h3>- <p>${renderNoMatchCopy(this._queryType, this._query)}</p>- <div class="explore-empty-ideas">- ${EXAMPLES.map(- (e) => `- <button type="button" class="explore-example" data-q="${esc(e.value)}">${esc(e.label)}</button>- `,- ).join('')}- </div>- </div>- `;- this._wireExampleClicks(out);- return;- }-- const filterBar = results.length >= 3 ? this._renderFilterBar() : '';- const visible = this._applyFilter(results);-- out.innerHTML = `- ${summary}- ${filterBar}- <div class="explore-grid">- ${visible.map((r) => renderCard(r)).join('')}- </div>- `;-- this._wireCards(out);- if (filterBar) this._wireFilterBar(out);- }-- _renderSummary() {- const n = this._results.length;- if (!this._query) return '';- const type = this._queryType;- let title = '';- let sub = '';-- const with3D = this._results.filter((r) => !!r.avatarUri).length;-- if (type === INPUT_TYPES.ADDRESS || type === INPUT_TYPES.ENS) {- const who = this._resolvedAddress || this._query;- title =- n === 0- ? `No agents owned by ${esc(shortAddr(who))}`- : `${n} agent${n === 1 ? '' : 's'} owned by ${esc(shortAddr(who))}`;- if (type === INPUT_TYPES.ENS && this._resolvedAddress) {- sub = `${esc(this._query)} → <code>${esc(this._resolvedAddress)}</code>`;- } else if (who) {- sub = `<code>${esc(who)}</code>`;- }- } else if (type === INPUT_TYPES.TX_HASH) {- title =- n === 0- ? `No Registered events in this transaction`- : `${n} agent${n === 1 ? '' : 's'} minted in this transaction`;- sub = `<code>${esc(this._query)}</code>`;- } else if (type === INPUT_TYPES.AGENT_ID) {- title =- n === 0- ? `Agent #${esc(this._query)} not found on any selected chain`- : `Agent #${esc(this._query)} on ${n} chain${n === 1 ? '' : 's'}`;- } else if (type === INPUT_TYPES.AGENT_URI) {- title =- n === 0 ? `Agent not found` : `Agent on ${esc(this._results[0]?.chainName || '?')}`;- sub = `<code>${esc(this._query)}</code>`;- }-- return `- <div class="explore-summary">- <div class="explore-summary-head">- <h2 class="explore-summary-title">${title}</h2>- ${n ? `<span class="explore-summary-stat">${with3D} with 3D body · ${n - with3D} metadata-only</span>` : ''}- </div>- ${sub ? `<div class="explore-summary-sub">${sub}</div>` : ''}- </div>- `;- }-- _renderFilterBar() {- const filters = [- { id: 'all', label: 'All' },- { id: '3d', label: '3D body' },- { id: 'x402', label: 'x402 💳' },- { id: 'a2a', label: 'A2A' },- { id: 'mcp', label: 'MCP' },- ];- return `- <div class="explore-filterbar" data-role="filterbar">- ${filters- .map(- (f) => `- <button type="button"- class="explore-filter ${this._filter === f.id ? 'explore-filter--active' : ''}"- data-filter="${f.id}"- >${esc(f.label)}</button>- `,- )- .join('')}- </div>- `;- }-- _wireFilterBar(out) {- out.querySelectorAll('[data-role="filterbar"] .explore-filter').forEach((btn) => {- btn.addEventListener('click', () => {- this._filter = btn.dataset.filter;- this._renderResults();- });- });- }-- _applyFilter(results) {- switch (this._filter) {- case '3d':- return results.filter((r) => !!r.avatarUri);- case 'x402':- return results.filter((r) => !!r.x402);- case 'a2a':- return results.filter((r) => r.serviceTypes?.includes('A2A'));- case 'mcp':- return results.filter((r) => r.serviceTypes?.includes('MCP'));- default:- return results;- }- }-- _wireCards(root) {- root.querySelectorAll('[data-role="card-copy"]').forEach((btn) => {- btn.addEventListener('click', (e) => {- e.preventDefault();- e.stopPropagation();- const url = new URL(btn.dataset.share, location.origin).href;- if (navigator.clipboard?.writeText) {- navigator.clipboard.writeText(url).then(- () => flashToast('Link copied'),- () => flashToast('Copy failed', true),- );- } else {- flashToast(url);- }- });- });- root.querySelectorAll('[data-role="card-embed"]').forEach((btn) => {- btn.addEventListener('click', (e) => {- e.preventDefault();- e.stopPropagation();- openEmbedModal({- chainId: Number(btn.dataset.chainId),- agentId: btn.dataset.agentId,- name: btn.dataset.name,- });- });- });- }-- _wireExampleClicks(root) {- root.querySelectorAll('.explore-example').forEach((btn) => {- btn.addEventListener('click', () => {- const q = btn.dataset.q;- this.container.querySelector('.explore-input').value = q;- this._updateInputMeta(q);- this._pushURL(q);- this._runResolve(q);- });- });- }-- _renderError(message) {- const out = this.container.querySelector('[data-role="results"]');- out.innerHTML = `- <div class="explore-error">- <strong>Couldn't resolve.</strong>- <p>${esc(message)}</p>- <div class="explore-empty-ideas">- ${EXAMPLES.map(- (e) => `- <button type="button" class="explore-example" data-q="${esc(e.value)}">${esc(e.label)}</button>- `,- ).join('')}- </div>- </div>- `;- this._wireExampleClicks(out);- }-- // ── Featured (no query) ───────────────────────────────────────────────-- async _showFeatured() {- const out = this.container.querySelector('[data-role="results"]');- out.innerHTML = `- <div class="explore-featured-head">- <h2>Recently minted on ${esc(CHAIN_META[FEATURED_CHAIN_ID]?.name || 'Base')}</h2>- <p class="explore-muted">Latest <code>Registered</code> events on the canonical Identity Registry.</p>- </div>- <div class="explore-grid" aria-busy="true" data-role="featured">- ${Array.from({ length: FEATURED_COUNT })- .map(- () => `- <div class="explore-card explore-card--skel">- <div class="explore-skel-img"></div>- <div class="explore-skel-line"></div>- <div class="explore-skel-line explore-skel-line--short"></div>- </div>- `,- )- .join('')}- </div>- `;-- const featured = await fetchFeatured();- const grid = this.container.querySelector('[data-role="featured"]');- if (!grid) return;-- if (!featured.length) {- grid.outerHTML = `- <div class="explore-empty">- <div class="explore-empty-art">✨</div>- <h3>No recent Registered events indexed.</h3>- <p class="explore-muted">Paste an address or agent ID above to look one up.</p>- </div>- `;- return;- }-- grid.innerHTML = featured.map((r) => renderCard(r)).join('');- this._wireCards(grid.parentElement || grid);- }-}--// ───────────────────────────────────────────────────────────────────────────-// Card-// ───────────────────────────────────────────────────────────────────────────--/** @param {import('./resolve-avatar.js').AvatarResult} r */-function renderCard(r) {- const chainMeta = CHAIN_META[r.chainId];- const img = r.image ? resolveURI(r.image) : '';- const chainShort = chainMeta?.shortName || chainMeta?.name || `#${r.chainId}`;- const chainBadge = `- <span class="explore-chain-badge ${chainMeta?.testnet ? 'explore-chain-badge--testnet' : ''}" title="${esc(chainMeta?.name || '')}">- ${esc(chainShort)}- </span>- `;- const title = esc(r.name || `Agent #${r.agentId}`);- const id = `#${esc(r.agentId)}`;- const ownerLine = r.owner- ? `<a class="explore-owner" href="${esc(r.ownerExplorerUrl)}" target="_blank" rel="noopener" title="${esc(r.owner)}">Owner ${esc(shortAddr(r.owner))} ↗</a>`- : '';- const descLine = r.description- ? `<p class="explore-card-desc">${esc(truncate(r.description, 140))}</p>`- : '';-- const tags = [];- if (r.avatarUri) tags.push(`<span class="explore-tag explore-tag--3d">3D</span>`);- if (r.x402) tags.push(`<span class="explore-tag explore-tag--x402">x402 💳</span>`);- for (const t of r.serviceTypes || []) {- if (t === 'A2A') tags.push(`<span class="explore-tag">A2A</span>`);- else if (t === 'MCP') tags.push(`<span class="explore-tag">MCP</span>`);- else if (t === 'OASF') tags.push(`<span class="explore-tag">OASF</span>`);- }-- const errLine = r.error ? `<div class="explore-card-err">${esc(r.error)}</div>` : '';- const viewerUrl = r.viewerUrl;- const explorerUrl = r.tokenExplorerUrl;-- return `- <article class="explore-card">- <a class="explore-card-thumb" href="${esc(viewerUrl)}" aria-label="Open Agent #${esc(r.agentId)} in 3D viewer">- ${img ? `<img src="${esc(img)}" alt="" loading="lazy" />` : `<div class="explore-card-ph">🤖</div>`}- ${chainBadge}- ${r.avatarUri ? `<span class="explore-card-3dpill">▶ 3D</span>` : ''}- </a>- <div class="explore-card-body">- <div class="explore-card-head">- <a class="explore-card-title" href="${esc(viewerUrl)}">${title}</a>- <span class="explore-card-id">${id}</span>- </div>- ${descLine}- <div class="explore-card-tags">${tags.join('')}</div>- ${ownerLine}- ${errLine}- <div class="explore-card-actions">- <a class="explore-btn explore-btn--sm explore-btn--primary" href="${esc(viewerUrl)}">Open 3D ↗</a>- ${explorerUrl ? `<a class="explore-btn explore-btn--sm" href="${esc(explorerUrl)}" target="_blank" rel="noopener">Explorer ↗</a>` : ''}- <button type="button" class="explore-btn explore-btn--sm explore-btn--ghost"- data-role="card-embed"- data-chain-id="${esc(String(r.chainId))}"- data-agent-id="${esc(String(r.agentId))}"- data-name="${esc(r.name || `Agent #${r.agentId}`)}"- title="Get embed snippets">Embed</button>- <button type="button" class="explore-btn explore-btn--sm explore-btn--ghost"- data-role="card-copy" data-share="${esc(viewerUrl)}" title="Copy shareable link">Share</button>- </div>- </div>- </article>- `;-}--function truncate(s, n) {- s = String(s || '');- return s.length > n ? s.slice(0, n - 1) + '…' : s;-}--function renderNoMatchCopy(type, query) {- switch (type) {- case INPUT_TYPES.ADDRESS:- return `We scanned the selected chains — this wallet hasn't minted any ERC-8004 agents there yet.`;- case INPUT_TYPES.ENS:- return `ENS resolved, but the address owns no ERC-8004 agents on the selected chains.`;- case INPUT_TYPES.TX_HASH:- return `This tx has no <code>Registered</code> events from the ERC-8004 Identity Registry on the selected chains.`;- case INPUT_TYPES.AGENT_ID:- return `Agent #${esc(query)} isn't minted on any selected chain. Try enabling more chains above.`;- default:- return `Nothing resolved. Try an address, ENS name, tx hash, or agent ID.`;- }-}--// ───────────────────────────────────────────────────────────────────────────-// Embed modal-// ───────────────────────────────────────────────────────────────────────────--const LIB_CDN_URL = 'https://3dagent.vercel.app/agent-3d/latest/agent-3d.js';--/**- * Open a modal with copy-paste embed snippets for an on-chain agent.- * @param {{ chainId: number, agentId: string, name: string }} p- */-function openEmbedModal({ chainId, agentId, name }) {- // Remove any existing- document.querySelector('.embed-modal')?.remove();-- const origin = location.origin;- const pageUrl = `${origin}/a/${chainId}/${agentId}`;- const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;- const agentUri = `agent://${chainId}/${agentId}`;- const displayName = name || `Agent #${agentId}`;-- const snippets = {- iframe: `<iframe src="${embedUrl}" width="480" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups" title="${displayName}"></iframe>`,- webComponent: `<script type="module" src="${LIB_CDN_URL}"></script>-<agent-3d src="${agentUri}" mode="inline" width="480px" responsive></agent-3d>`,- markdown: `[](${pageUrl})`,- link: pageUrl,- farcaster: pageUrl,- };-- const modal = document.createElement('div');- modal.className = 'embed-modal';- modal.setAttribute('role', 'dialog');- modal.setAttribute('aria-modal', 'true');- modal.setAttribute('aria-label', `Embed ${displayName}`);- modal.innerHTML = `- <div class="embed-modal__backdrop" data-role="close"></div>- <div class="embed-modal__panel" role="document">- <header class="embed-modal__head">- <div>- <h2 class="embed-modal__title">Embed ${esc(displayName)}</h2>- <p class="embed-modal__sub">Drop this anywhere — any site, any doc, any chat.</p>- </div>- <button type="button" class="embed-modal__close" data-role="close" aria-label="Close">×</button>- </header>- <div class="embed-modal__tabs" role="tablist">- <button type="button" class="embed-tab is-active" data-tab="webComponent" role="tab" aria-selected="true">Web component</button>- <button type="button" class="embed-tab" data-tab="iframe" role="tab" aria-selected="false">iframe</button>- <button type="button" class="embed-tab" data-tab="link" role="tab" aria-selected="false">Link</button>- <button type="button" class="embed-tab" data-tab="markdown" role="tab" aria-selected="false">Markdown</button>- <button type="button" class="embed-tab" data-tab="farcaster" role="tab" aria-selected="false">Farcaster</button>- </div>- <div class="embed-modal__body">- <div class="embed-pane is-active" data-pane="webComponent">- <p class="embed-pane__hint">Full fidelity — loads the avatar + runtime. Requires modules.</p>- <textarea class="embed-snippet" readonly rows="3">${esc(snippets.webComponent)}</textarea>- <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="webComponent">Copy</button>- </div>- <div class="embed-pane" data-pane="iframe">- <p class="embed-pane__hint">Works everywhere that allows iframes — Notion, Substack, Ghost, your own site.</p>- <textarea class="embed-snippet" readonly rows="3">${esc(snippets.iframe)}</textarea>- <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="iframe">Copy</button>- </div>- <div class="embed-pane" data-pane="link">- <p class="embed-pane__hint">Share anywhere — unfurls in Slack, X, Discord, iMessage with a preview card.</p>- <input class="embed-snippet embed-snippet--input" readonly value="${esc(snippets.link)}" />- <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="link">Copy</button>- </div>- <div class="embed-pane" data-pane="markdown">- <p class="embed-pane__hint">Drop into a README or blog that renders markdown — shows a preview card that links to the 3D viewer.</p>- <textarea class="embed-snippet" readonly rows="2">${esc(snippets.markdown)}</textarea>- <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="markdown">Copy</button>- </div>- <div class="embed-pane" data-pane="farcaster">- <p class="embed-pane__hint">Cast this link. The page has Frame meta tags — Warpcast and compatible clients render an interactive card with View 3D + Explore buttons.</p>- <input class="embed-snippet embed-snippet--input" readonly value="${esc(snippets.farcaster)}" />- <button type="button" class="explore-btn explore-btn--sm explore-btn--primary" data-role="copy" data-key="farcaster">Copy</button>- </div>- </div>- <footer class="embed-modal__foot">- <a href="${esc(pageUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Open standalone page ↗</a>- <a href="${esc(embedUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Preview iframe ↗</a>- </footer>- </div>- `;- document.body.appendChild(modal);-- const close = () => {- modal.remove();- document.removeEventListener('keydown', onEsc);- };- const onEsc = (e) => {- if (e.key === 'Escape') close();- };- document.addEventListener('keydown', onEsc);- modal- .querySelectorAll('[data-role="close"]')- .forEach((el) => el.addEventListener('click', close));-- modal.querySelectorAll('.embed-tab').forEach((tab) => {- tab.addEventListener('click', () => {- modal.querySelectorAll('.embed-tab').forEach((t) => {- t.classList.toggle('is-active', t === tab);- t.setAttribute('aria-selected', t === tab ? 'true' : 'false');- });- modal.querySelectorAll('.embed-pane').forEach((p) => {- p.classList.toggle('is-active', p.dataset.pane === tab.dataset.tab);- });- });- });-- modal.querySelectorAll('[data-role="copy"]').forEach((btn) => {- btn.addEventListener('click', () => {- const key = btn.dataset.key;- const text = snippets[key];- if (!text) return;- const done = (ok) => {- btn.textContent = ok ? 'Copied ✓' : 'Copy failed';- setTimeout(() => (btn.textContent = 'Copy'), 1400);- };- if (navigator.clipboard?.writeText) {- navigator.clipboard.writeText(text).then(- () => done(true),- () => done(false),- );- } else {- const ta = modal.querySelector(`[data-pane="${key}"] .embed-snippet`);- ta?.select();- try {- document.execCommand('copy');- done(true);- } catch {- done(false);- }- }- });- });-- // Focus first field for quick copy- setTimeout(() => {- const first = modal.querySelector('.embed-pane.is-active .embed-snippet');- first?.focus();- first?.select?.();- }, 50);-}--// ───────────────────────────────────────────────────────────────────────────-// Toast-// ───────────────────────────────────────────────────────────────────────────--function flashToast(text, isError = false) {- const toast = document.createElement('div');- toast.className = 'erc8004-toast' + (isError ? ' erc8004-toast--error' : '');- toast.textContent = text;- document.body.appendChild(toast);- setTimeout(() => toast.remove(), 1800);-}--// ───────────────────────────────────────────────────────────────────────────-// Featured loader-// ───────────────────────────────────────────────────────────────────────────--async function fetchFeatured() {- const tryChain = async (chainId) => {- try {- const events = await listRegisteredEvents({- chainId,- blocks: FEATURED_SCAN_BLOCKS,- limit: FEATURED_COUNT,- ethProvider: window.ethereum,- });- if (!events.length) return [];- const hydrated = await Promise.all(- events.map((ev) =>- hydrateAgent({ chainId, agentId: ev.agentId, ethProvider: window.ethereum }),- ),- );- return hydrated;- } catch {- return [];- }- };- const primary = await tryChain(FEATURED_CHAIN_ID);- if (primary.length) return primary;- return tryChain(FEATURED_FALLBACK_CHAIN_ID);-}--// ───────────────────────────────────────────────────────────────────────────-// Persistence-// ───────────────────────────────────────────────────────────────────────────--function parseURL() {- const url = new URL(location.href);- const q = url.searchParams.get('q') || '';- return { q };-}--function loadRecent() {- try {- const raw = localStorage.getItem(RECENT_KEY);- if (!raw) return [];- const arr = JSON.parse(raw);- if (!Array.isArray(arr)) return [];- return arr.slice(0, RECENT_MAX);- } catch {- return [];- }-}--function pushRecent(value) {- try {- const recent = loadRecent();- const idx = recent.findIndex((r) => (r.value || r) === value);- if (idx >= 0) recent.splice(idx, 1);- recent.unshift({ label: value, value });- localStorage.setItem(RECENT_KEY, JSON.stringify(recent.slice(0, RECENT_MAX)));- } catch {- /* quota / disabled */- }-}--function loadChainSelection() {- try {- const raw = localStorage.getItem(CHAINS_KEY);- if (!raw) return DEFAULT_FAN_OUT_CHAINS.slice();- const arr = JSON.parse(raw);- if (!Array.isArray(arr) || !arr.length) return DEFAULT_FAN_OUT_CHAINS.slice();- return arr.map(Number).filter(Boolean);- } catch {- return DEFAULT_FAN_OUT_CHAINS.slice();- }-}--function saveChainSelection(arr) {- try {- localStorage.setItem(CHAINS_KEY, JSON.stringify(arr));- } catch {- /* quota / disabled */- }-}diff --git a/src/erc8004/resolve-avatar.js b/src/erc8004/resolve-avatar.jsindex d5801ab6e..a65f5117a 100644--- a/src/erc8004/resolve-avatar.js+++ b/src/erc8004/resolve-avatar.js@@ -7,7 +7,6 @@* results ready to render as a gallery.** Used by:- * - src/erc8004/explore.js (the public /explore gallery page)* - src/erc8004/register-ui.js ("Find Avatar" tab for creators)** Chain reads happen through public RPCs (CHAIN_META) so no wallet required.diff --git a/src/erc8004/resolver.js b/src/erc8004/resolver.jsindex 2728ef78f..9216ad6aa 100644--- a/src/erc8004/resolver.js+++ b/src/erc8004/resolver.js@@ -146,7 +146,7 @@ export function resolveUrlCandidates(uri) {// ---------------------------------------------------------------------------// Lightweight in-memory cache keyed by canonical ref string. The resolver is-// a hot path on /explore and in consumer embeds; don't hit the chain twice+// a hot path on /discover and in consumer embeds; don't hit the chain twice// for the same agent within a page session.const _cache = new Map();function cacheKey(ref) {diff --git a/src/erc8004/showcase.js b/src/erc8004/showcase.jsindex c291d4fc0..d5890a567 100644--- a/src/erc8004/showcase.js+++ b/src/erc8004/showcase.js@@ -2,9 +2,9 @@* /showcase — browsable directory of every ERC-8004 agent with a 3D avatar.** Reads from GET /api/showcase (backed by erc8004_agents_index, populated by- * api/cron/erc8004-crawl.js). Unlike /explore (search-by-input), this page is- * pure browse: pick a net + chains, scroll a grid of newest-minted agents,- * click a card to open its 3D viewer at /a/<chainId>/<agentId>.+ * api/cron/erc8004-crawl.js). Unlike /discover (search-by-input via /api/explore),+ * this page is pure browse: pick a net + chains, scroll a grid of newest-minted+ * agents, click a card to open its 3D viewer at /a/<chainId>/<agentId>.** Lazy-loaded by src/app.js `_showShowcasePage`.*/diff --git a/src/share-panel-builders.js b/src/share-panel-builders.jsnew file mode 100644index 000000000..c2fc5ca0a--- /dev/null+++ b/src/share-panel-builders.js@@ -0,0 +1,80 @@+/**+ * Pure, side-effect-free helpers for building share/embed snippets.+ * Kept separate from share-panel.js so tests can import them without+ * pulling in the CSS or any DOM-coupled code.+ *+ * @module share-panel-builders+ */++/** @type {{ readonly bg: 'transparent' | 'dark' | 'light', readonly name: boolean, readonly size: 'small' | 'medium' | 'large' }} */+export const DEFAULT_OPTIONS = Object.freeze({+ bg: 'transparent',+ name: true,+ size: 'medium',+});++/** Iframe pixel dimensions per size keyword. */+export const SIZES = Object.freeze({+ small: { width: 320, height: 420 },+ medium: { width: 420, height: 520 },+ large: { width: 520, height: 680 },+});++/**+ * Build the canonical embed URL for an agent with the given options. Default+ * options are omitted from the query string so the canonical URL stays short.+ *+ * @param {{ origin: string, agentId: string, opts?: Partial<typeof DEFAULT_OPTIONS> }} args+ * @returns {string}+ */+export function buildEmbedUrl({ origin, agentId, opts = {} }) {+ const merged = { ...DEFAULT_OPTIONS, ...opts };+ const url = new URL(`${origin}/agent/${agentId}/embed`);+ if (merged.bg !== DEFAULT_OPTIONS.bg) url.searchParams.set('bg', merged.bg);+ if (merged.name !== DEFAULT_OPTIONS.name) url.searchParams.set('name', '0');+ return url.toString();+}++/**+ * Build the iframe embed snippet. Uses the canonical /agent/{id}/embed URL,+ * declares a transparent CSS background so external sites composite cleanly,+ * and lazy-loads to avoid a network hit on hosts that paginate embeds.+ *+ * @param {{ origin: string, agentId: string, opts?: Partial<typeof DEFAULT_OPTIONS> }} args+ * @returns {string}+ */+export function buildIframeSnippet({ origin, agentId, opts = {} }) {+ const merged = { ...DEFAULT_OPTIONS, ...opts };+ const { width, height } = SIZES[merged.size] || SIZES.medium;+ const src = buildEmbedUrl({ origin, agentId, opts: merged });+ const allow = 'autoplay; xr-spatial-tracking; microphone; camera';+ return (+ `<iframe\n` ++ ` src="${src}"\n` ++ ` width="${width}" height="${height}"\n` ++ ` style="border:0;border-radius:12px;background:transparent"\n` ++ ` allow="${allow}"\n` ++ ` loading="lazy"\n` ++ ` referrerpolicy="strict-origin-when-cross-origin"\n` ++ `></iframe>`+ );+}++/**+ * Build the <agent-3d> web-component embed snippet. The web component renders+ * a richer surface (chat shell + viewer) than the iframe page, so the bg /+ * name-plate toggles intentionally do not propagate here.+ *+ * @param {{ origin: string, agentId: string, opts?: Partial<typeof DEFAULT_OPTIONS> }} args+ * @returns {string}+ */+export function buildWebComponentSnippet({ origin, agentId, opts = {} }) {+ const merged = { ...DEFAULT_OPTIONS, ...opts };+ const { width, height } = SIZES[merged.size] || SIZES.medium;+ return (+ `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n` ++ `<agent-3d agent-id="${agentId}"\n` ++ ` style="display:block;width:${width}px;height:${height}px"\n` ++ `></agent-3d>`+ );+}diff --git a/src/share-panel.js b/src/share-panel.jsindex 7cb7b4f55..e87a105b4 100644--- a/src/share-panel.js+++ b/src/share-panel.js@@ -1,6 +1,22 @@import { renderQRToCanvas, renderQRToSVG } from './erc8004/qr.js';+import {+ DEFAULT_OPTIONS,+ SIZES,+ buildEmbedUrl,+ buildIframeSnippet,+ buildWebComponentSnippet,+} from './share-panel-builders.js';import './share-panel.css';+// Re-export the pure helpers so existing imports keep working.+export {+ buildEmbedUrl,+ buildIframeSnippet,+ buildWebComponentSnippet,+ DEFAULT_OPTIONS,+ SIZES,+} from './share-panel-builders.js';+/*** One-click share modal for an agent: link, customisable iframe + web-component* snippets with a live preview, OG card, and QR code.@@ -13,18 +29,6 @@ import './share-panel.css';* panel.open();*/-const DEFAULT_OPTIONS = Object.freeze({- bg: 'transparent', // 'transparent' | 'dark' | 'light'- name: true, // show name plate- size: 'medium', // 'small' | 'medium' | 'large'-});--const SIZES = {- small: { width: 320, height: 420 },- medium: { width: 420, height: 520 },- large: { width: 520, height: 680 },-};-export class SharePanel {/*** @param {{@@ -198,55 +202,14 @@ export class SharePanel {this._opener = null;}- // ── Snippet building ─────────────────────────────────────────────────────────-- /**- * Build the canonical embed URL with current options as query params.- * Defaults are omitted to keep the URL readable.- *- * @returns {string}- */- _buildEmbedUrl() {- const id = this._agent.id;- const url = new URL(`${this._origin}/agent/${id}/embed`);- if (this._opts.bg !== DEFAULT_OPTIONS.bg) url.searchParams.set('bg', this._opts.bg);- if (this._opts.name !== DEFAULT_OPTIONS.name) url.searchParams.set('name', '0');- return url.toString();- }-- _buildIframeSnippet() {- const { width, height } = SIZES[this._opts.size];- const allow = 'autoplay; xr-spatial-tracking; microphone; camera';- return (- `<iframe\n` +- ` src="${this._buildEmbedUrl()}"\n` +- ` width="${width}" height="${height}"\n` +- ` style="border:0;border-radius:12px;background:transparent"\n` +- ` allow="${allow}"\n` +- ` loading="lazy"\n` +- ` referrerpolicy="strict-origin-when-cross-origin"\n` +- `></iframe>`- );- }-- _buildWebComponentSnippet() {- const { width, height } = SIZES[this._opts.size];- const id = this._agent.id;- return (- `<script type="module" src="${this._origin}/dist-lib/agent-3d.js"><\/script>\n` +- `<agent-3d agent-id="${id}"\n` +- ` style="display:block;width:${width}px;height:${height}px"\n` +- `></agent-3d>`- );- }+ // ── Snippet rendering ────────────────────────────────────────────────────────_renderSnippets() {const m = this._backdrop;if (!m) return;- const iframeCode = this._buildIframeSnippet();- const wcCode = this._buildWebComponentSnippet();- m.querySelector('[data-role="iframe-code"]').textContent = iframeCode;- m.querySelector('[data-role="wc-code"]').textContent = wcCode;+ const args = { origin: this._origin, agentId: this._agent.id, opts: this._opts };+ m.querySelector('[data-role="iframe-code"]').textContent = buildIframeSnippet(args);+ m.querySelector('[data-role="wc-code"]').textContent = buildWebComponentSnippet(args);}// ── Live preview ─────────────────────────────────────────────────────────────@@ -262,7 +225,13 @@ export class SharePanel {_renderPreview() {if (!this._previewMount) return;const { width, height } = SIZES[this._opts.size];- const url = new URL(this._buildEmbedUrl());+ const url = new URL(+ buildEmbedUrl({+ origin: this._origin,+ agentId: this._agent.id,+ opts: this._opts,+ }),+ );// Always set preview=1 so the embed page skips its origin allow-list// gate when the dialog runs on a non-allowlisted host.url.searchParams.set('preview', '1');@@ -354,63 +323,6 @@ export class SharePanel {}}-// ── Pure helpers (exported for tests) ────────────────────────────────────────────--/**- * Build an embed URL for the given agent and options. Pure / side-effect-free.- * Defaults are omitted from the query string so canonical URLs stay short.- *- * @param {{ origin: string, agentId: string, opts?: { bg?: string, name?: boolean } }} args- */-export function buildEmbedUrl({ origin, agentId, opts = {} }) {- const merged = { ...DEFAULT_OPTIONS, ...opts };- const url = new URL(`${origin}/agent/${agentId}/embed`);- if (merged.bg !== DEFAULT_OPTIONS.bg) url.searchParams.set('bg', merged.bg);- if (merged.name !== DEFAULT_OPTIONS.name) url.searchParams.set('name', '0');- return url.toString();-}--/**- * Build the iframe snippet string. Pure / side-effect-free.- *- * @param {{ origin: string, agentId: string, opts?: { bg?: string, name?: boolean, size?: string } }} args- */-export function buildIframeSnippet({ origin, agentId, opts = {} }) {- const merged = { ...DEFAULT_OPTIONS, ...opts };- const { width, height } = SIZES[merged.size] || SIZES.medium;- const src = buildEmbedUrl({ origin, agentId, opts: merged });- const allow = 'autoplay; xr-spatial-tracking; microphone; camera';- return (- `<iframe\n` +- ` src="${src}"\n` +- ` width="${width}" height="${height}"\n` +- ` style="border:0;border-radius:12px;background:transparent"\n` +- ` allow="${allow}"\n` +- ` loading="lazy"\n` +- ` referrerpolicy="strict-origin-when-cross-origin"\n` +- `></iframe>`- );-}--/**- * Build the web-component snippet string. Pure / side-effect-free.- *- * @param {{ origin: string, agentId: string, opts?: { bg?: string, name?: boolean, size?: string } }} args- */-export function buildWebComponentSnippet({ origin, agentId, opts = {} }) {- const merged = { ...DEFAULT_OPTIONS, ...opts };- const { width, height } = SIZES[merged.size] || SIZES.medium;- const attrs = [`agent-id="${agentId}"`];- if (merged.bg !== DEFAULT_OPTIONS.bg) attrs.push(`background="${merged.bg}"`);- if (merged.name !== DEFAULT_OPTIONS.name) attrs.push(`name-plate="off"`);- return (- `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n` +- `<agent-3d ${attrs.join(' ')}\n` +- ` style="display:block;width:${width}px;height:${height}px"\n` +- `></agent-3d>`- );-}-// ── Internal helpers ─────────────────────────────────────────────────────────────function _segmentBtn(group, value, label, currentValue) {diff --git a/style.css b/style.cssindex 3d2f5a70b..c2a97d423 100644--- a/style.css+++ b/style.css@@ -1193,11 +1193,11 @@ footer .separator {color: #ff7a7a;}-/* /explore — cross-chain on-chain avatar browser.+/* /discover — cross-chain on-chain avatar browser.** Search ANY input (address / ENS / tx / agent ID / agent:// URI) and see every* matching ERC-8004 registered 3D avatar as a gallery, grouped by chain.- * Implementation: src/erc8004/explore.js → src/erc8004/resolve-avatar.js.+ * Implementation: public/discover/discover.js → src/erc8004/resolve-avatar.js.*/.explore-shell {max-width: 1200px;@@ -5552,6 +5552,12 @@ textarea.erc8004-code {font-size: 15px;line-height: 1.55;}+.explore-hero-chips {+ display: inline-flex;+ flex-wrap: wrap;+ gap: 10px;+ justify-content: center;+}.explore-hero-chip {display: inline-flex;align-items: center;@@ -5566,6 +5572,22 @@ textarea.erc8004-code {letter-spacing: 0.02em;text-transform: uppercase;}+.explore-hero-chip--link {+ text-decoration: none;+ background: transparent;+ border-color: rgba(255, 255, 255, 0.18);+ color: rgba(255, 255, 255, 0.78);+ transition:+ border-color 0.15s ease,+ color 0.15s ease,+ background 0.15s ease;+}+.explore-hero-chip--link:hover,+.explore-hero-chip--link:focus-visible {+ border-color: var(--accent);+ color: var(--accent);+ background: var(--accent-soft);+}.explore-hero-dot {width: 6px;height: 6px;diff --git a/tests/share-panel.test.js b/tests/share-panel.test.jsnew file mode 100644index 000000000..5d5e29a94--- /dev/null+++ b/tests/share-panel.test.js@@ -0,0 +1,205 @@+import { describe, it, expect } from 'vitest';+import { readFileSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++import {+ buildEmbedUrl,+ buildIframeSnippet,+ buildWebComponentSnippet,+} from '../src/share-panel-builders.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(__dirname, '..');+const p = (...parts) => resolve(repoRoot, ...parts);++const ORIGIN = 'https://3dagent.vercel.app';+const ID = '9fc7f1ba-2f34-4d79-843b-9b34c27e0d72';++describe('share-panel — buildEmbedUrl', () => {+ it('uses the working /agent/{id}/embed path (not the broken /agent-embed.html?id=...)', () => {+ const url = buildEmbedUrl({ origin: ORIGIN, agentId: ID });+ expect(url).toBe(`${ORIGIN}/agent/${ID}/embed`);+ expect(url).not.toContain('/agent-embed.html');+ });++ it('omits default options from the query string for a clean canonical URL', () => {+ const url = buildEmbedUrl({ origin: ORIGIN, agentId: ID });+ expect(url).not.toContain('?');+ });++ it('adds bg=dark when background is dark', () => {+ const url = buildEmbedUrl({ origin: ORIGIN, agentId: ID, opts: { bg: 'dark' } });+ expect(url).toContain('bg=dark');+ });++ it('adds bg=light when background is light', () => {+ const url = buildEmbedUrl({ origin: ORIGIN, agentId: ID, opts: { bg: 'light' } });+ expect(url).toContain('bg=light');+ });++ it('adds name=0 when name plate is off', () => {+ const url = buildEmbedUrl({ origin: ORIGIN, agentId: ID, opts: { name: false } });+ expect(url).toContain('name=0');+ });++ it('combines bg and name params when both differ from defaults', () => {+ const url = buildEmbedUrl({+ origin: ORIGIN,+ agentId: ID,+ opts: { bg: 'dark', name: false },+ });+ expect(url).toContain('bg=dark');+ expect(url).toContain('name=0');+ });+});++describe('share-panel — buildIframeSnippet', () => {+ it('produces a valid iframe with the embed URL', () => {+ const snippet = buildIframeSnippet({ origin: ORIGIN, agentId: ID });+ expect(snippet).toContain(`<iframe`);+ expect(snippet).toContain(`src="${ORIGIN}/agent/${ID}/embed"`);+ expect(snippet).toContain(`</iframe>`);+ });++ it('defaults to medium size 420x520', () => {+ const snippet = buildIframeSnippet({ origin: ORIGIN, agentId: ID });+ expect(snippet).toContain('width="420"');+ expect(snippet).toContain('height="520"');+ });++ it('uses small size 320x420', () => {+ const snippet = buildIframeSnippet({ origin: ORIGIN, agentId: ID, opts: { size: 'small' } });+ expect(snippet).toContain('width="320"');+ expect(snippet).toContain('height="420"');+ });++ it('uses large size 520x680', () => {+ const snippet = buildIframeSnippet({ origin: ORIGIN, agentId: ID, opts: { size: 'large' } });+ expect(snippet).toContain('width="520"');+ expect(snippet).toContain('height="680"');+ });++ it('declares transparent background in style so external sites can composite', () => {+ const snippet = buildIframeSnippet({ origin: ORIGIN, agentId: ID });+ expect(snippet).toContain('background:transparent');+ });++ it('marks loading=lazy and a same-origin-friendly referrer policy', () => {+ const snippet = buildIframeSnippet({ origin: ORIGIN, agentId: ID });+ expect(snippet).toContain('loading="lazy"');+ expect(snippet).toContain('referrerpolicy="strict-origin-when-cross-origin"');+ });++ it('forwards the bg/name options into the iframe src', () => {+ const snippet = buildIframeSnippet({+ origin: ORIGIN,+ agentId: ID,+ opts: { bg: 'dark', name: false },+ });+ expect(snippet).toContain('bg=dark');+ expect(snippet).toContain('name=0');+ });++ it('falls back to medium size for an unknown size value', () => {+ const snippet = buildIframeSnippet({+ origin: ORIGIN,+ agentId: ID,+ opts: { size: 'xxl' },+ });+ expect(snippet).toContain('width="420"');+ expect(snippet).toContain('height="520"');+ });+});++describe('share-panel — buildWebComponentSnippet', () => {+ it('produces an <agent-3d> snippet with the correct id', () => {+ const snippet = buildWebComponentSnippet({ origin: ORIGIN, agentId: ID });+ expect(snippet).toContain(`<agent-3d agent-id="${ID}"`);+ expect(snippet).toContain(`src="${ORIGIN}/dist-lib/agent-3d.js"`);+ });++ it('respects the chosen size in the inline style', () => {+ const snippet = buildWebComponentSnippet({+ origin: ORIGIN,+ agentId: ID,+ opts: { size: 'large' },+ });+ expect(snippet).toContain('width:520px');+ expect(snippet).toContain('height:680px');+ });+});++describe('agent-embed.html — consolidated embed page', () => {+ const html = readFileSync(p('agent-embed.html'), 'utf8');++ it('defaults to a transparent background', () => {+ expect(html).toContain("const bg = params.get('bg') || 'transparent'");+ expect(html).toContain('background: transparent');+ });++ it('exposes the v1 postMessage bridge', () => {+ expect(html).toContain("BRIDGE_VERSION = '1'");+ expect(html).toContain("'agent:hello'");+ expect(html).toContain("'agent:ready'");+ expect(html).toContain("'agent:action'");+ expect(html).toContain("'agent:ping'");+ expect(html).toContain("'agent:resize'");+ });++ it('reports a ResizeObserver-driven content height to the host', () => {+ expect(html).toContain('new ResizeObserver(reportSize)');+ });++ it('resolves agentId from both the path and the ?id= query (so the legacy share snippet still works)', () => {+ expect(html).toContain("parts.indexOf('agent')");+ expect(html).toContain("params.get('id')");+ });++ it('does not inject a frame-ancestors meta tag (browsers ignore it; we use response headers instead)', () => {+ expect(html).not.toMatch(/<meta[^>]+content-security-policy/i);+ expect(html).not.toContain('insertCspMeta');+ });++ it('legacy { mode, hosts } embed-policy shape is still normalised', () => {+ expect(html).toContain('normalisePolicy');+ });+});++describe('vercel.json — embed route headers', () => {+ const vercel = JSON.parse(readFileSync(p('vercel.json'), 'utf8'));+ const routes = vercel.routes || [];++ it('rewrites /agent/{id}/embed to /agent-embed.html', () => {+ const r = routes.find((x) => x.src === '/agent/([^/]+)/embed');+ expect(r).toBeTruthy();+ expect(r.dest).toBe('/agent-embed.html');+ });++ it('sets a permissive frame-ancestors CSP header so external sites can iframe', () => {+ const r = routes.find((x) => x.src === '/agent/([^/]+)/embed');+ expect(r?.headers?.['content-security-policy']).toBe('frame-ancestors *');+ });++ it('does NOT set X-Frame-Options (would block cross-origin embedding)', () => {+ const r = routes.find((x) => x.src === '/agent/([^/]+)/embed');+ expect(r?.headers?.['x-frame-options']).toBeUndefined();+ });++ it('declares a permissions-policy that allows microphone/camera/xr from self', () => {+ const r = routes.find((x) => x.src === '/agent/([^/]+)/embed');+ expect(r?.headers?.['permissions-policy']).toContain('microphone');+ expect(r?.headers?.['permissions-policy']).toContain('camera');+ });++ it('applies the same headers to the on-chain /a/{chain}/{id}/embed route', () => {+ const r = routes.find((x) => x.src === '/a/(\\d+)/(\\d+)/embed');+ expect(r?.headers?.['content-security-policy']).toBe('frame-ancestors *');+ });+});++describe('embed page deduplication', () => {+ it('removes the unreachable duplicate at public/agent/embed.html', () => {+ expect(existsSync(p('public/agent/embed.html'))).toBe(false);+ });+});diff --git a/vercel.json b/vercel.jsonindex dc0b6067f..6dbf245e1 100644--- a/vercel.json+++ b/vercel.json@@ -124,9 +124,9 @@{ "src": "/my-agents", "dest": "/my-agents/index.html" },{ "src": "/my-agents/", "dest": "/my-agents/index.html" },{ "src": "/my-agents/(.*)", "dest": "/my-agents/$1" },- { "src": "/discover", "status": 301, "headers": { "Location": "/my-agents" } },- { "src": "/discover/", "status": 301, "headers": { "Location": "/my-agents" } },- { "src": "/discover/(.*)", "status": 301, "headers": { "Location": "/my-agents" } },+ { "src": "/discover", "dest": "/discover/index.html" },+ { "src": "/discover/", "dest": "/discover/index.html" },+ { "src": "/discover/(.*)", "dest": "/discover/$1" },{ "src": "/api/(.*)", "dest": "/api/$1" },diff --git a/vite.config.js b/vite.config.jsindex 501072944..fe666457c 100644--- a/vite.config.js+++ b/vite.config.js@@ -39,6 +39,7 @@ const appConfig = {hydrate: resolve(__dirname, 'public/hydrate/index.html'),// BEGIN:DISCOVER_ROUTE'my-agents': resolve(__dirname, 'public/my-agents/index.html'),+ discover: resolve(__dirname, 'public/discover/index.html'),// END:DISCOVER_ROUTE},},@@ -52,8 +53,6 @@ const appConfig = {'/app': resolve(root, 'app.html'),'/login': resolve(root, 'public/login.html'),'/deploy': resolve(root, 'app.html'),- '/discover': resolve(root, 'public/discover/index.html'),- '/discover/': resolve(root, 'public/discover/index.html'),'/agents': resolve(root, 'public/agents/index.html'),'/agents/': resolve(root, 'public/agents/index.html'),'/features': resolve(root, 'features.html'),@@ -73,6 +72,10 @@ const appConfig = {// BEGIN:DISCOVER_ROUTE'/my-agents': resolve(root, 'public/my-agents/index.html'),'/my-agents/': resolve(root, 'public/my-agents/index.html'),+ '/discover': resolve(root, 'public/discover/index.html'),+ '/discover/': resolve(root, 'public/discover/index.html'),+ '/explore': resolve(root, 'public/discover/index.html'),+ '/explore/': resolve(root, 'public/discover/index.html'),// END:DISCOVER_ROUTE'/agent': resolve(root, 'agent-home.html'),};