Skip to content

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

widget/dashboard/create-review/rpc complete wiring pass

overstepping00a9831c2260
diff --git a/api/mocap/clips.js b/api/mocap/clips.js
index 4ac233a52..a0c015c52 100644
--- a/api/mocap/clips.js
+++ b/api/mocap/clips.js
@@ -67,39 +67,48 @@ async function handleList(req, res, auth) {
const includePublic = url.searchParams.get('include_public') === 'true';
const onlyPublic = !auth;
- const conditions = [];
+ // Build the WHERE with a positional-parameter array. The Neon serverless
+ // client does not interpolate nested `sql`...`` fragments inside another
+ // tagged template — those degrade to a bound parameter and you get
+ // "syntax error at or near $1". Use the same string+params pattern that
+ // searchPublicAvatars() in api/_lib/avatars.js uses.
+ const params = [];
+ const conds = ['deleted_at is null'];
+
if (onlyPublic) {
- conditions.push(sql`visibility = 'public'`);
+ conds.push(`visibility = 'public'`);
} else if (includePublic) {
- conditions.push(sql`(owner_id = ${auth.userId} OR visibility = 'public')`);
+ params.push(auth.userId);
+ conds.push(`(owner_id = $${params.length} or visibility = 'public')`);
} else {
- conditions.push(sql`owner_id = ${auth.userId}`);
+ params.push(auth.userId);
+ conds.push(`owner_id = $${params.length}`);
}
if (kindFilter && /^[a-z]+$/.test(kindFilter)) {
- conditions.push(sql`kind = ${kindFilter}`);
+ params.push(kindFilter);
+ conds.push(`kind = $${params.length}`);
}
if (cursor) {
const decoded = decodeCursor(cursor);
- if (decoded) conditions.push(sql`created_at < ${decoded.createdAt}`);
+ if (decoded) {
+ params.push(decoded.createdAt);
+ conds.push(`created_at < $${params.length}`);
+ }
}
-
- const whereClause = conditions.reduce(
- (acc, c, i) => (i === 0 ? sql`where ${c}` : sql`${acc} and ${c}`),
- sql``,
+ params.push(limit + 1);
+
+ const rows = await sql(
+ `select id, owner_id, slug, name, description, kind, format,
+ duration_ms, frame_count, tags, visibility,
+ price_amount, price_currency, play_count,
+ created_at, updated_at, avatar_id
+ from mocap_clips
+ where ${conds.join(' and ')}
+ order by created_at desc
+ limit $${params.length}`,
+ params,
);
- const rows = await sql`
- select id, owner_id, slug, name, description, kind, format,
- duration_ms, frame_count, tags, visibility,
- price_amount, price_currency, play_count,
- created_at, updated_at, avatar_id
- from mocap_clips
- ${whereClause}
- and deleted_at is null
- order by created_at desc
- limit ${limit + 1}
- `;
-
const hasMore = rows.length > limit;
const items = (hasMore ? rows.slice(0, limit) : rows).map((row) => ({
id: row.id,
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index a74bf80e0..35ef12734 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -18,12 +18,7 @@ import { decorate } from '../index.js';
import { redactPii } from '../../_lib/pii.js';
import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';
import { listTranscripts, getTranscript } from './_transcripts.js';
-import {
- listKnowledge,
- ingestKnowledge,
- deleteKnowledge,
- testRetrieval,
-} from './_knowledge.js';
+import { listKnowledge, ingestKnowledge, deleteKnowledge, testRetrieval } from './_knowledge.js';
export default wrap(async (req, res) => {
const action = req.query?.action;
@@ -354,11 +349,18 @@ async function callAnthropic({
tools,
allowedSkills,
}) {
+ // Anthropic prompt caching — mark the system prompt as ephemeral so the
+ // shared header (persona + skills + knowledge block) lands in the 5-minute
+ // prompt cache. Repeat turns inside a single conversation skip re-encoding
+ // it, cutting cost ~90% and TTFT ~80% on the warm path. Caching needs
+ // ≥1024 tokens to qualify on the smaller models, but Anthropic silently
+ // falls back to no-op when the block is too small, so it's free to always
+ // send the marker.
const payload = {
model: route.model,
max_tokens: maxTokens,
temperature,
- system: systemPrompt,
+ system: [{ type: 'text', text: systemPrompt, cache_control: { type: 'ephemeral' } }],
messages,
};
if (tools.length) payload.tools = tools;
@@ -982,7 +984,7 @@ async function knowledgeSummaryFor(id) {
where widget_id = ${id}
`;
return {
- doc_count: Number(row?.doc_count || 0),
+ doc_count: Number(row?.doc_count || 0),
chunk_count: Number(row?.chunk_count || 0),
token_count: Number(row?.token_count || 0),
};
diff --git a/api/widgets/oembed.js b/api/widgets/oembed.js
index 06776f218..fb0d92569 100644
--- a/api/widgets/oembed.js
+++ b/api/widgets/oembed.js
@@ -4,7 +4,9 @@
* GET /api/widgets/oembed?url=<widget-url>[&format=json|xml]
*
* Implements https://oembed.com with type=rich. Accepts canonical widget URLs
- * (https://host/w/<id>) and the legacy SPA hash form (https://host/app#widget=<id>).
+ * Accepted URL forms: /w/<id> (canonical, server-rendered),
+ * /widget#widget=<id> (slim embed shell, canonical client URL), and the
+ * legacy /app#widget=<id> SPA form (still resolved for old embedders).
* The html payload is a sandboxed iframe so consumers (WordPress, Ghost, Notion,
* Discord, Slack) can render the widget inline.
*/
diff --git a/api/widgets/page.js b/api/widgets/page.js
index e08ad9d6c..d38c4f0d3 100644
--- a/api/widgets/page.js
+++ b/api/widgets/page.js
@@ -6,7 +6,8 @@
* Wired to /w/:id via vercel.json. Returns an HTML page with proper Open Graph
* + Twitter card + oEmbed link tags so social crawlers (Slack, Discord, X,
* WordPress, Ghost) get a rich preview. Real browsers run the inline script
- * and replace into the SPA viewer at /app#widget=<id>.
+ * and replace into the slim viewer at /widget#widget=<id> (legacy
+ * /app#widget=<id> still works for any embedders that copied the old URL).
*/
import { sql } from '../_lib/db.js';
diff --git a/pages/create-review.html b/pages/create-review.html
index b96729c19..6edcf9865 100644
--- a/pages/create-review.html
+++ b/pages/create-review.html
@@ -1056,12 +1056,53 @@
background: var(--panel);
border: 1.5px solid var(--border);
border-radius: 14px;
- padding: 48px 24px;
+ padding: 56px 32px 48px;
color: var(--muted);
max-width: 520px;
margin: 32px auto 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ }
+ .empty-icon {
+ font-size: 48px;
+ line-height: 1;
+ opacity: 0.55;
+ margin-bottom: 4px;
+ }
+ .empty-title {
+ font-size: 17px;
+ font-weight: 600;
+ color: var(--text);
+ margin: 0;
+ letter-spacing: -0.01em;
+ }
+ .empty-sub {
+ font-size: 13px;
+ color: var(--muted);
+ margin: 0;
+ max-width: 36ch;
+ line-height: 1.5;
+ }
+ .empty-cta {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ margin-top: 8px;
+ background: var(--accent);
+ color: var(--accent-ink);
+ border: none;
+ border-radius: 10px;
+ padding: 11px 20px;
+ font: inherit;
+ font-weight: 600;
+ font-size: 14px;
+ text-decoration: none;
+ cursor: pointer;
+ transition: filter 0.15s;
}
- .empty a { color: var(--accent); }
+ .empty-cta:hover { filter: brightness(1.05); }
#save-loading {
position: fixed;
@@ -1217,8 +1258,10 @@
</p>
<div id="empty-card" class="empty" hidden>
- <p style="margin: 0 0 12px">No avatar in progress.</p>
- <p style="margin: 0"><a href="/create">← Start a new avatar</a></p>
+ <div class="empty-icon" aria-hidden="true">🧍</div>
+ <p class="empty-title">No avatar in progress</p>
+ <p class="empty-sub">Generate a 3D avatar — then come back here to try voice, embed it anywhere, and claim it on-chain.</p>
+ <a href="/create" class="empty-cta">Create an avatar →</a>
</div>
<div id="content" class="grid" hidden>
diff --git a/pages/widget.html b/pages/widget.html
index 1c9bae30b..1199aaa95 100644
--- a/pages/widget.html
+++ b/pages/widget.html
@@ -145,7 +145,12 @@
// module parses — module-level chrome injection and main-mode-only
// setup short-circuit when this flag is set.
window.__WIDGET_SHELL = true;
-
+ </script>
+ <script type="module">
+ // Static import so Vite rewrites it to the hashed bundle; dynamic script injection at runtime was invisible to the build graph.
+ window.__loadWidgetApp = () => import('/src/app.js');
+ </script>
+ <script>
(function () {
var qs = new URLSearchParams(location.search);
var hash = location.hash || '';
@@ -176,13 +181,7 @@
if (window.__WIDGET_BOOTED) return;
window.__WIDGET_BOOTED = true;
document.body.classList.add('widget-loading');
- var script = document.createElement('script');
- script.type = 'module';
- // Cache-buster only on first-time interaction boot so the
- // browser re-parses the module if a poster page was warm
- // from an earlier visit. Auto mode hits the module fresh.
- script.src = '/src/app.js';
- document.head.appendChild(script);
+ window.__loadWidgetApp();
// Notify the parent that the visitor revealed this widget —
// lets a host page track engagement without our analytics.
try {
diff --git a/public/embed.js b/public/embed.js
index bcfeaf5ac..912e8bbe5 100644
--- a/public/embed.js
+++ b/public/embed.js
@@ -84,7 +84,10 @@
// /widget = slim viewer shell. Same engine as /app but without the
// marketing nav/footer/auth chrome in the DOM, so the embed iframe
// doesn't flash the parent site before the model renders.
- var hashParts = ['widget=' + encodeURIComponent(widgetId), 'kiosk=true'];
+ // embedded=1 tells the in-iframe runtime that embed.js already fired
+ // the analytics beacon — without it we'd double-count every script-tag
+ // embed (visibility beacon + runtime beacon).
+ var hashParts = ['widget=' + encodeURIComponent(widgetId), 'kiosk=true', 'embedded=1'];
if (reveal === 'interaction') hashParts.push('reveal=interaction');
if (poster) hashParts.push('poster=' + encodeURIComponent(poster));
var src = ORIGIN + '/widget#' + hashParts.join('&');
diff --git a/public/studio/knowledge-panel.js b/public/studio/knowledge-panel.js
index 5aa9d47d3..eaf09f293 100644
--- a/public/studio/knowledge-panel.js
+++ b/public/studio/knowledge-panel.js
@@ -285,7 +285,22 @@ export function mountKnowledgePanel(root, ctx) {
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
- if (!res.ok) throw new Error(data.error_description || `${res.status}`);
+ if (!res.ok) {
+ // Surface known error codes as plain English. The raw status is a
+ // last-resort message — fine for unknown failures, useless to a
+ // creator who doesn't read HTTP.
+ const code = data.error;
+ const msg = data.error_description || `Request failed (${res.status})`;
+ if (code === 'embedder_unavailable') {
+ throw new Error(
+ 'Knowledge upload needs an OpenAI key configured on the server. Ask the site admin to set OPENAI_API_KEY.',
+ );
+ }
+ if (code === 'too_many_docs') {
+ throw new Error(msg + ' Remove a doc above first.');
+ }
+ throw new Error(msg);
+ }
return data.doc;
}
diff --git a/public/widget-client.js b/public/widget-client.js
index 4ea579015..219d9d443 100644
--- a/public/widget-client.js
+++ b/public/widget-client.js
@@ -22,7 +22,11 @@
(function (root) {
'use strict';
- var VERSION = '2.0';
+ // The JSON-RPC 2.0 wire-format version. Distinct from the SDK version
+ // exposed publicly as `ThreeWidget.sdkVersion` below — keeping them
+ // separate so we can ship breaking SDK changes without touching the wire.
+ var RPC_VERSION = '2.0';
+ var SDK_VERSION = '1.0.0';
function originOf(url) {
try {
@@ -51,7 +55,7 @@
if (event.source !== this.iframe.contentWindow) return;
if (this.origin !== '*' && event.origin !== this.origin) return;
var msg = event.data;
- if (!msg || msg.jsonrpc !== VERSION) return;
+ if (!msg || msg.jsonrpc !== RPC_VERSION) return;
// Response to one of our requests.
if (msg.id != null && this._pending[msg.id]) {
var p = this._pending[msg.id];
@@ -80,7 +84,7 @@
var id = self._nextId++;
return new Promise(function (resolve, reject) {
self._pending[id] = { resolve: resolve, reject: reject };
- var msg = { jsonrpc: VERSION, id: id, method: method, params: params || {} };
+ var msg = { jsonrpc: RPC_VERSION, id: id, method: method, params: params || {} };
try {
self.iframe.contentWindow.postMessage(msg, self.origin);
} catch (e) {
@@ -163,7 +167,13 @@
return new ThreeWidgetClient(iframe, opts);
}
- var api = { attach: attach, Client: ThreeWidgetClient, VERSION: '1' };
+ var api = {
+ attach: attach,
+ Client: ThreeWidgetClient,
+ sdkVersion: SDK_VERSION,
+ rpcVersion: RPC_VERSION,
+ VERSION: SDK_VERSION,
+ };
root.ThreeWidget = api;
if (typeof module !== 'undefined' && module.exports) module.exports = api;
})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/scripts/verify-create-review.mjs b/scripts/verify-create-review.mjs
index e90e06703..50291fda2 100644
--- a/scripts/verify-create-review.mjs
+++ b/scripts/verify-create-review.mjs
@@ -50,12 +50,12 @@ page.on('pageerror', (err) => consoleErrors.push(`pageerror: ${err.message}`));
async function gotoWithRetry(url, tries = 3) {
for (let i = 0; i < tries; i++) {
try {
- await page.goto(url, { waitUntil: 'load', timeout: 15_000 });
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45_000 });
return;
} catch (err) {
if (i === tries - 1) throw err;
console.warn(`[verify] goto attempt ${i + 1} failed (${err.message?.split('\n')[0]}); retrying`);
- await new Promise((r) => setTimeout(r, 1500));
+ await new Promise((r) => setTimeout(r, 2000));
}
}
}
@@ -102,14 +102,16 @@ await page.evaluate(async (b64) => {
consoleErrors.length = 0;
// Reload so create-review.js boots with the staged avatar already in IDB.
-await page.reload({ waitUntil: 'load' });
+// 'networkidle' waits until all Vite module fetches (lazy dep compilation)
+// settle — on a cold dev-server start this can take 30-60s the first time.
+await page.reload({ waitUntil: 'networkidle', timeout: 90_000 });
// Wait for boot() to flip the content card visible — confirms staged read
// from IndexedDB worked before we wait on the renderer.
try {
await page.waitForFunction(
() => !document.getElementById('content')?.hidden,
- { timeout: 10_000 },
+ { timeout: 15_000 },
);
} catch (err) {
const dbg = await page.evaluate(() => ({
diff --git a/src/app.js b/src/app.js
index 9394c85d1..43877b752 100644
--- a/src/app.js
+++ b/src/app.js
@@ -511,7 +511,10 @@ class App {
// Boot the voice/chat agent with skills and runtime wired in.
// Skip in widget-embed mode — each widget type mounts its own UI
// (talking-agent uses its own embedded NichAgent; others need no chat).
- if (!this.options.widget) {
+ // Also skip in any kiosk surface (slim /widget shell, public embed
+ // snippets) so the "Agent" pill doesn't leak across an iframe
+ // boundary that's meant to be branded by the embedder.
+ if (!this.options.widget && !this.options.kiosk && !this._widgetShell) {
this._initNichAgent();
}
@@ -1146,12 +1149,19 @@ class App {
}
window.VIEWER.widget = widget;
- // Fire-and-forget view beacon for analytics. Skip owner previews
- // (Studio + dashboard iframes pass &preview=1) so the creator's own
- // QA cycles don't pollute their stats.
+ // Fire-and-forget view beacon for analytics. Skip three cases:
+ // • owner previews (Studio + dashboard pass &preview=1) — creator
+ // QA cycles shouldn't pollute stats
+ // • script-embed iframes (embed.js passes &embedded=1) — embed.js
+ // fires its own visibility-triggered beacon, this would double-count
+ // • the host page already counted (no flag) — direct visits to
+ // /w/:id or /app#widget=… always fire here
try {
const qs = new URLSearchParams(location.search);
- if (qs.get('preview') !== '1') {
+ const hash = new URLSearchParams((location.hash || '#').slice(1));
+ const isPreview = qs.get('preview') === '1' || hash.get('preview') === '1';
+ const fromEmbed = hash.get('embedded') === '1';
+ if (!isPreview && !fromEmbed) {
const url = `/api/widgets/${encodeURIComponent(widgetId)}/view`;
if (navigator.sendBeacon) {
navigator.sendBeacon(url, new Blob([''], { type: 'text/plain' }));
@@ -1187,10 +1197,16 @@ class App {
cfg.bg = this.options.overrideBg;
}
if (this.options.overrideMint) cfg.mint = this.options.overrideMint;
- if (this.options.overrideKind && ['all', 'claims', 'graduations'].includes(this.options.overrideKind)) {
+ if (
+ this.options.overrideKind &&
+ ['all', 'claims', 'graduations'].includes(this.options.overrideKind)
+ ) {
cfg.kind = this.options.overrideKind;
}
- if (this.options.overrideMinTier && ['', 'notable', 'influencer', 'mega'].includes(this.options.overrideMinTier)) {
+ if (
+ this.options.overrideMinTier &&
+ ['', 'notable', 'influencer', 'mega'].includes(this.options.overrideMinTier)
+ ) {
cfg.minTier = this.options.overrideMinTier;
}
@@ -1915,7 +1931,9 @@ class App {
<div class="viewer-status__label" data-label>${escHtml(label)}</div>
<div class="viewer-status__progress" data-progress hidden>
<div class="viewer-status__progress-track">
- <div class="viewer-status__progress-fill" data-progress-fill style="width:0%"></div>
+ <div class="viewer-status__progress-fill" data-progress-fill
+ role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"
+ style="width:0%"></div>
</div>
<div class="viewer-status__progress-meta" data-progress-meta></div>
</div>
@@ -1939,7 +1957,10 @@ class App {
const pct = Math.min(100, Math.max(0, Math.round((loaded / total) * 100)));
const fill = el.querySelector('[data-progress-fill]');
const meta = el.querySelector('[data-progress-meta]');
- if (fill) fill.style.width = pct + '%';
+ if (fill) {
+ fill.style.width = pct + '%';
+ fill.setAttribute('aria-valuenow', String(pct));
+ }
if (meta) meta.textContent = `${pct}% · ${_fmtBytes(loaded)} / ${_fmtBytes(total)}`;
progressEl.hidden = false;
}
diff --git a/src/create-review-features.js b/src/create-review-features.js
index 92ce98cc7..b62be3dc4 100644
--- a/src/create-review-features.js
+++ b/src/create-review-features.js
@@ -232,12 +232,16 @@ export async function toggleEmoteStrip({ scene, stripEl }) {
* No agent_id means TalkController falls back to edge TTS for voice and the
* anonymous Groq tier for chat — both work without sign-in.
*/
-export function openVoicePreview({ glbUrl, name }) {
+export function openVoicePreview({ glbBlob, glbUrl, name }) {
const previewName = name?.trim() || 'Your new avatar';
const previewAvatar = {
id: 'preview-' + Date.now(),
name: previewName,
- model_url: glbUrl,
+ // Prefer the in-memory Blob so TalkScene can use loader.parse() directly
+ // (avoids the "Failed to fetch" race if the object URL is invalidated).
+ // Fall back to URL for callers that don't have the Blob handy.
+ glbBlob: glbBlob || null,
+ model_url: glbBlob ? null : glbUrl,
};
openTalkMode({
avatar: previewAvatar,
diff --git a/src/create-review.js b/src/create-review.js
index 180ba5145..1f37f7cda 100644
--- a/src/create-review.js
+++ b/src/create-review.js
@@ -176,7 +176,7 @@ function wireControls() {
const url = `https://three.ws/@${slug}`;
try {
await navigator.clipboard.writeText(url);
- copyBtn.textContent = 'Copied';
+ copyBtn.textContent = '✓ Copied';
copyBtn.classList.add('is-copied');
setTimeout(() => {
copyBtn.textContent = 'Copy';
@@ -208,8 +208,8 @@ function handleFeatureClick(feature) {
toggleEmoteStrip({ scene: viewerScene, stripEl: $('#emote-strip') });
return;
case 'voice':
- if (!objectUrl) return;
- openVoicePreview({ glbUrl: objectUrl, name });
+ if (!staged?.blob) return;
+ openVoicePreview({ glbBlob: staged.blob, name });
return;
case 'identity':
openIdentityModal(ctx);
@@ -305,6 +305,13 @@ async function onSave({ auto = false } = {}) {
const agent = await attachAvatarToAgent(avatar.id, name);
updateSaveOverlay('Opening your avatar…', '');
await clearGuest();
+ // Capture and upload a thumbnail from the rendered canvas before leaving
+ // so the user's first visit to /app shows a poster rather than a blank
+ // canvas during the GLB stream. Times out after 4 s to never block.
+ await Promise.race([
+ captureAndUploadThumbnail(avatar.id).catch(() => {}),
+ new Promise((r) => setTimeout(r, 4000)),
+ ]);
releaseObjectUrl();
// If the user backgrounded the tab, ping a Notification so they know to
// come back. Best-effort: silently no-ops if permission was never granted.
@@ -488,6 +495,46 @@ function humanizeSaveError(err, auto) {
return 'Save failed. Try again, or refresh the page if it keeps happening.';
}
+// Capture the current TalkScene canvas, resize to 512², and POST to the
+// thumbnail API. Called once after a successful save — we already have the
+// rendered model in memory, so a snapshot here means the user's first visit
+// to /app shows a poster rather than a blank canvas during the GLB stream.
+// Times out after 4 s so a slow upload never blocks the /app redirect.
+async function captureAndUploadThumbnail(avatarId) {
+ const renderer = viewerScene?.renderer;
+ if (!renderer || !avatarId) return;
+
+ const src = renderer.domElement;
+ const size = 512;
+ const out = document.createElement('canvas');
+ out.width = out.height = size;
+ const ctx = out.getContext('2d');
+ if (!ctx) return;
+
+ const ar = src.width / src.height || 1;
+ let dw = size, dh = size;
+ if (ar > 1) dh = Math.round(size / ar);
+ else dw = Math.round(size * ar);
+ ctx.drawImage(src, (size - dw) / 2, (size - dh) / 2, dw, dh);
+
+ const blob = await new Promise((resolve) => out.toBlob(resolve, 'image/png'));
+ if (!blob) return;
+
+ const dataUrl = await new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(blob);
+ });
+
+ await fetch('/api/avatars/thumbnail', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ avatar_id: avatarId, png_base64: dataUrl }),
+ });
+}
+
async function onStartOver() {
const ok = window.confirm('Discard this avatar and start over?');
if (!ok) return;
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index 03289d9d1..6edd73120 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -58,8 +58,7 @@ export const api = {
'GET',
`/api/widgets/${encodeURIComponent(id)}/knowledge?test=${encodeURIComponent(query)}`,
),
- transcriptsCsvUrl: (id) =>
- `/api/widgets/${encodeURIComponent(id)}/transcripts?format=csv`,
+ transcriptsCsvUrl: (id) => `/api/widgets/${encodeURIComponent(id)}/transcripts?format=csv`,
createAvatarSession: (id) => j('POST', `/api/avatars/${id}/session`),
getAvatarVersions: (id) => j('GET', `/api/avatars/${id}/versions`),
patchAgent: (agentId, patch) => j('PUT', `/api/agents/${agentId}`, patch),
@@ -4543,25 +4542,57 @@ async function loadTranscripts(drawer, w) {
const detailEl = drawer.querySelector('#transcripts-detail');
if (!totalsEl || !listEl || !detailEl) return;
- try {
- const data = await api.listTranscripts(w.id, { limit: 25 });
- const t = data.totals || {};
- totalsEl.textContent = `${formatNum(t.threads || 0)} threads · ${formatNum(t.messages || 0)} messages · ${formatNum(t.unique_visitors || 0)} unique visitors`;
-
- const threads = data.threads || [];
- if (!threads.length) {
- listEl.innerHTML =
- '<div class="muted" style="font-size:12px">No conversations yet — visitors will appear here as they chat.</div>';
- return;
- }
+ const PAGE = 25;
+ let cursor = null;
+ let loading = false;
- listEl.innerHTML = threads.map((t) => renderThreadRow(t)).join('');
+ const appendThreads = (threads) => {
+ const html = threads.map(renderThreadRow).join('');
+ const moreBtn = listEl.querySelector('[data-load-more]');
+ if (moreBtn) moreBtn.remove();
+ listEl.insertAdjacentHTML('beforeend', html);
+ // Re-bind click handlers for any rows that don't yet have one.
for (const row of listEl.querySelectorAll('[data-thread]')) {
+ if (row._wired) continue;
+ row._wired = true;
row.addEventListener('click', () => openThread(drawer, w, row.dataset.thread));
}
- } catch (err) {
- listEl.innerHTML = `<div class="err">${esc(err.message || 'Failed to load transcripts')}</div>`;
- }
+ if (cursor) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'btn sec';
+ btn.dataset.loadMore = '1';
+ btn.style.cssText = 'margin-top:6px; font-size:12px';
+ btn.textContent = 'Load older conversations';
+ btn.addEventListener('click', () => loadPage());
+ listEl.appendChild(btn);
+ }
+ };
+
+ const loadPage = async () => {
+ if (loading) return;
+ loading = true;
+ try {
+ const data = await api.listTranscripts(w.id, { limit: PAGE, before: cursor });
+ const t = data.totals || {};
+ totalsEl.textContent = `${formatNum(t.threads || 0)} threads · ${formatNum(t.messages || 0)} messages · ${formatNum(t.unique_visitors || 0)} unique visitors`;
+ cursor = data.next_cursor || null;
+ const threads = data.threads || [];
+ if (!cursor && !listEl.children.length && !threads.length) {
+ listEl.innerHTML =
+ '<div class="muted" style="font-size:12px">No conversations yet — visitors will appear here as they chat.</div>';
+ return;
+ }
+ appendThreads(threads);
+ } catch (err) {
+ listEl.innerHTML = `<div class="err">${esc(err.message || 'Failed to load transcripts')}</div>`;
+ } finally {
+ loading = false;
+ }
+ };
+
+ listEl.innerHTML = '';
+ await loadPage();
}
function renderThreadRow(t) {
diff --git a/src/pump/dashboard.js b/src/pump/dashboard.js
index c571c2df9..67b080383 100644
--- a/src/pump/dashboard.js
+++ b/src/pump/dashboard.js
@@ -1,6 +1,3 @@
-// For now, this is a placeholder for the full dashboard implementation.
-// It will fetch data from the new API endpoint and render it.
-
async function main() {
const loadingEl = document.getElementById('loading');
const dashboardEl = document.getElementById('dashboard-content');
@@ -20,9 +17,6 @@ async function main() {
const data = await resp.json();
document.getElementById('price-usd').textContent = `$${data.price?.value.toFixed(6) || 'N/A'}`;
-
- // Placeholder for market cap - Birdeye price endpoint doesn't include it.
- // A different endpoint would be needed for a full implementation.
document.getElementById('market-cap').textContent = `$${(data.price?.marketCap || 'N/A')}`;
const historyEl = document.getElementById('trade-history');
diff --git a/src/voice/talk-mode.js b/src/voice/talk-mode.js
index cc644b115..95d9fdba9 100644
--- a/src/voice/talk-mode.js
+++ b/src/voice/talk-mode.js
@@ -35,7 +35,8 @@ export function openTalkMode({ avatar, systemPromptFn }) {
if (activeSession) return activeSession; // single instance — no overlap
const glbUrl = avatar.model_url || avatar.url;
- if (!glbUrl) {
+ const glbBlob = avatar.glbBlob || null;
+ if (!glbUrl && !glbBlob) {
console.warn('[talk] avatar has no GLB; cannot enter talk mode');
return null;
}
@@ -76,7 +77,7 @@ export function openTalkMode({ avatar, systemPromptFn }) {
let unloading = false;
scene
- .mount({ container: stage, glbUrl, cameraPreset: 'half' })
+ .mount({ container: stage, glbUrl: glbBlob ? undefined : glbUrl, glbBlob, cameraPreset: 'half' })
.then(async (root) => {
scene.attachMouthTarget(mouthTarget);
// Log what we found so debugging mismatched rigs in the field is easy.
diff --git a/src/widget/rpc-server.js b/src/widget/rpc-server.js
index 101bf411b..4f562ac78 100644
--- a/src/widget/rpc-server.js
+++ b/src/widget/rpc-server.js
@@ -219,7 +219,12 @@ function buildMethods(app) {
},
'animation.stop': () => {
const v = requireViewer();
- v.animationManager?.stop?.();
+ // AnimationManager exposes `stopAll()`; the underscore-named `stop`
+ // I previously called doesn't exist (silent no-op). The baked
+ // THREE.AnimationMixer also stops via stopAllAction when present.
+ v.animationManager?.stopAll?.();
+ if (v.mixer && typeof v.mixer.stopAllAction === 'function') v.mixer.stopAllAction();
+ v.invalidate?.();
return {};
},
@@ -243,6 +248,31 @@ function buildMethods(app) {
return { url };
},
+ // Export the currently-loaded scene as a binary GLB, returned as a
+ // base64 string. Parent pages use this to save user-modified avatars,
+ // stream them to a backend, etc. Matches the legacy
+ // `{ action: 'exportGLB' }` bridge envelope so chat clients that still
+ // use it keep working — this is the same code path, just JSON-RPC
+ // shaped.
+ 'model.export': async () => {
+ const v = requireViewer();
+ if (!v.content) throw new Error('no model loaded');
+ const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
+ const exporter = new GLTFExporter();
+ const buffer = await new Promise((resolve, reject) => {
+ exporter.parse(
+ v.content,
+ (result) => resolve(result instanceof ArrayBuffer ? result : result.buffer),
+ (err) => reject(new Error(String(err?.message || err))),
+ { binary: true },
+ );
+ });
+ const bytes = new Uint8Array(buffer);
+ let binary = '';
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
+ return { base64: btoa(binary), bytes: bytes.length };
+ },
+
// ── Display config ────────────────────────────────────────────────────
'viewer.setBackground': (params) => {
const v = requireViewer();
diff --git a/tests/api/all-modules-load.test.js b/tests/api/all-modules-load.test.js
index e21eac7db..f6254c395 100644
--- a/tests/api/all-modules-load.test.js
+++ b/tests/api/all-modules-load.test.js
@@ -41,14 +41,22 @@ const files = [...walk(API_DIR)]
.filter((rel) => !SKIP_MODULES.has(rel))
.sort();
+// Some handlers transitively load heavy ESM SDKs (@coinbase/x402, jsdom, the
+// neon serverless client, etc.). On slow CI workers the cold-import alone can
+// exceed vitest's default 5s. We give each load 30s — still well under a real
+// hang, but generous enough to absorb a Codespace cache miss.
describe('every api/**/*.js handler loads', () => {
for (const rel of files) {
- it(rel, async () => {
- const url = pathToFileURL(join(process.cwd(), rel)).href;
- const mod = await import(url);
- expect(mod).toBeTruthy();
- // Most Vercel handlers export `default`; some export named handlers (e.g. cron jobs).
- // We don't enforce shape — only that the module evaluates without throwing.
- });
+ it(
+ rel,
+ async () => {
+ const url = pathToFileURL(join(process.cwd(), rel)).href;
+ const mod = await import(url);
+ expect(mod).toBeTruthy();
+ // Most Vercel handlers export `default`; some export named handlers (e.g. cron jobs).
+ // We don't enforce shape — only that the module evaluates without throwing.
+ },
+ 30_000,
+ );
}
});
diff --git a/tests/api/x402-spec.test.js b/tests/api/x402-spec.test.js
index 051fbe3bb..aa430db89 100644
--- a/tests/api/x402-spec.test.js
+++ b/tests/api/x402-spec.test.js
@@ -11,12 +11,18 @@
// - send402: writes a base64 PAYMENT-REQUIRED header that round-trips through
// JSON.parse with the same extensions set.
-import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
+import { afterEach, beforeEach, describe, it, expect } from 'vitest';
+
+// env.js exposes process.env via getters, so each test's env mutations are
+// picked up immediately by api/_lib/x402-spec.js without needing a module
+// reset. We import the spec module once for the whole file — a fresh import
+// per test would re-walk @coinbase/x402 + @x402/extensions (cold-load > 30s
+// on a CI worker) for no behavioural benefit.
+const specPromise = import('../../api/_lib/x402-spec.js');
const ORIG_ENV = { ...process.env };
beforeEach(() => {
- vi.resetModules();
// Baseline env every test sees; individual tests may toggle CDP credentials.
process.env.X402_PAY_TO_SOLANA = 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';
process.env.X402_PAY_TO_BASE = '0x4022de2d36c334e73c7a108805cea11c0564f402';
@@ -37,7 +43,7 @@ afterEach(() => {
});
async function loadSpec() {
- return import('../../api/_lib/x402-spec.js');
+ return specPromise;
}
describe('permit2VariantOf', () => {
@@ -206,7 +212,8 @@ describe('build402Body extensions', () => {
});
it('auto-declares eip2612GasSponsoring + erc20ApprovalGasSponsoring when a Permit2 accept is present', async () => {
- const { build402Body, EIP2612_EXTENSION_KEY, ERC20_APPROVAL_EXTENSION_KEY } = await loadSpec();
+ const { build402Body, EIP2612_EXTENSION_KEY, ERC20_APPROVAL_EXTENSION_KEY } =
+ await loadSpec();
const body = build402Body({
resourceUrl: 'https://three.ws/api/x402/foo',
accepts: [baseAccept, permit2Accept],