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.

app-next + create-review + dashboard polish

nirholas391e73156277
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index c160717a7..ded68aaf3 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -149,6 +149,16 @@ const handleUpload = wrap(async (req, res) => {
}
if (!buffer.length) return error(res, 400, 'empty_body', 'no bytes received');
+ // GLB header (binary glTF 2.0 spec): 12 bytes of
+ // magic uint32 0x46546C67 // 'glTF' little-endian
+ // version uint32 must be 2
+ // length uint32 total file length in bytes (must equal buffer length)
+ // Catches mis-named uploads (JPEGs, HTML error pages, truncated files) and
+ // sets the catalog up to only ever serve well-formed binary glTF.
+ if (!isValidGlbHeader(buffer)) {
+ return error(res, 415, 'invalid_glb', 'body is not a valid binary glTF 2.0 (GLB) — magic/version/length check failed');
+ }
+
try {
await enforceQuotas(userId, buffer.length);
} catch (err) {
@@ -175,6 +185,16 @@ const handleUpload = wrap(async (req, res) => {
});
});
+// Binary glTF 2.0 header check. See https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#binary-gltf-layout
+function isValidGlbHeader(buffer) {
+ if (!Buffer.isBuffer(buffer) || buffer.length < 12) return false;
+ // Magic = 0x46546C67 ("glTF" in little-endian = 0x67,0x6C,0x54,0x46 in file order)
+ if (buffer.readUInt32LE(0) !== 0x46546C67) return false;
+ if (buffer.readUInt32LE(4) !== 2) return false;
+ if (buffer.readUInt32LE(8) !== buffer.length) return false;
+ return true;
+}
+
function readRawBody(req, limit) {
return new Promise((resolve, reject) => {
const chunks = [];
diff --git a/pages/agent-embed.html b/pages/agent-embed.html
index d2171bd13..8367f140c 100644
--- a/pages/agent-embed.html
+++ b/pages/agent-embed.html
@@ -112,6 +112,7 @@
import { AgentIdentity } from '/src/agent-identity.js';
import { AgentAvatar } from '/src/agent-avatar.js';
import { protocol } from '/src/agent-protocol.js';
+ import { EmbedActionBridge } from '/src/embed-action-bridge.js';
const BRIDGE_VERSION = '1';
const CAPABILITIES = ['speak', 'gesture', 'look-at', 'emote', 'present-model'];
diff --git a/pages/app-next.html b/pages/app-next.html
index b00101824..2bc9aa59f 100644
--- a/pages/app-next.html
+++ b/pages/app-next.html
@@ -31,6 +31,69 @@
</a>
<div class="nxt-header-right">
+ <!-- Camera presets — quick framing shortcuts -->
+ <div class="nxt-preset-cluster" role="toolbar" aria-label="Camera presets">
+ <button
+ class="nxt-preset"
+ data-preset="face"
+ type="button"
+ title="Face shot (1)"
+ >
+ <span>Face</span>
+ </button>
+ <button
+ class="nxt-preset is-active"
+ data-preset="body"
+ type="button"
+ title="Body shot (2)"
+ >
+ <span>Body</span>
+ </button>
+ <button
+ class="nxt-preset"
+ data-preset="wide"
+ type="button"
+ title="Wide shot (3)"
+ >
+ <span>Wide</span>
+ </button>
+ <button
+ class="nxt-preset"
+ data-preset="hero"
+ type="button"
+ title="Hero shot (4)"
+ >
+ <span>Hero</span>
+ </button>
+ </div>
+
+ <button
+ class="nxt-icon-btn"
+ id="nxt-fullscreen-btn"
+ type="button"
+ aria-label="Fullscreen (F)"
+ title="Fullscreen (F)"
+ >
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
+ <path d="M2 6V2h4M14 6V2h-4M2 10v4h4M14 10v4h-4" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ </button>
+
+ <button
+ class="nxt-icon-btn"
+ id="nxt-share-btn"
+ type="button"
+ aria-label="Share / embed (S)"
+ title="Share / embed (S)"
+ >
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
+ <circle cx="4" cy="8" r="1.6" stroke="currentColor" stroke-width="1.4" fill="none" />
+ <circle cx="12" cy="3.5" r="1.6" stroke="currentColor" stroke-width="1.4" fill="none" />
+ <circle cx="12" cy="12.5" r="1.6" stroke="currentColor" stroke-width="1.4" fill="none" />
+ <path d="M5.4 7.2l5.2-3M5.4 8.8l5.2 3" stroke="currentColor" stroke-width="1.4" fill="none" />
+ </svg>
+ </button>
+
<button
class="nxt-more"
id="nxt-more-btn"
@@ -85,32 +148,64 @@
<!-- The 3D viewer (required by app.js) -->
<div class="viewer-container nxt-viewer" id="viewer-container"></div>
- <!-- Floor glow + edge vignette (CSS only, sits behind the canvas via z-index) -->
+ <!-- Floor glow + edge vignette (sits behind the transparent canvas) -->
<div class="nxt-stage-floor" aria-hidden="true"></div>
<div class="nxt-stage-vignette" aria-hidden="true"></div>
- <!-- Rotating "Try …" invitation — floats above the bottom bar -->
- <div class="nxt-try-pill" id="nxt-try-pill" hidden>
- <span class="nxt-try-pill__label">Try</span>
- <button class="nxt-try-pill__btn" id="nxt-try-pill-btn" type="button">
- <span class="nxt-try-pill__icon" id="nxt-try-pill-icon">👋</span>
- <span class="nxt-try-pill__name" id="nxt-try-pill-name">Wave</span>
- </button>
- <button
- class="nxt-try-pill__next"
- id="nxt-try-pill-next"
- type="button"
- aria-label="Suggest another"
- title="Suggest another"
- >
- <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
- <path d="M2 8h12M9 3l5 5-5 5" stroke="currentColor" stroke-width="1.6" fill="none" stroke-linecap="round" stroke-linejoin="round" />
+ <!-- Live agent chat reply — speech-bubble style above the avatar -->
+ <div class="nxt-agent-bubble" id="nxt-agent-bubble" hidden>
+ <div class="nxt-agent-bubble__inner">
+ <span class="nxt-agent-bubble__dot" aria-hidden="true"></span>
+ <span class="nxt-agent-bubble__text" id="nxt-agent-bubble-text"></span>
+ </div>
+ </div>
+
+ <!-- Chat dock — rotating prompt chips above pinned input -->
+ <div class="nxt-chat-dock" id="nxt-chat-dock">
+ <div class="nxt-chat-chips" id="nxt-chat-chips" role="list" aria-label="Suggested prompts">
+ <!-- chips injected by overlay JS -->
+ </div>
+ <form class="nxt-chat-input-wrap" id="nxt-chat-form">
+ <svg class="nxt-chat-input-icon" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
+ <path d="M3 5h10M3 8h7M3 11h10" stroke="currentColor" stroke-width="1.4" fill="none" stroke-linecap="round" />
</svg>
- </button>
+ <input
+ class="nxt-chat-input"
+ id="nxt-chat-input"
+ type="text"
+ placeholder="Ask the agent…"
+ autocomplete="off"
+ maxlength="500"
+ aria-label="Message the agent"
+ />
+ <button
+ class="nxt-chat-mic"
+ id="nxt-chat-mic"
+ type="button"
+ aria-label="Push to talk (hold space)"
+ title="Push to talk (hold space)"
+ hidden
+ >
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
+ <rect x="6" y="2" width="4" height="8" rx="2" stroke="currentColor" stroke-width="1.4" fill="none" />
+ <path d="M3 8a5 5 0 0010 0M8 13v2M5.5 15h5" stroke="currentColor" stroke-width="1.4" fill="none" stroke-linecap="round" />
+ </svg>
+ </button>
+ <button
+ class="nxt-chat-send"
+ id="nxt-chat-send"
+ type="submit"
+ aria-label="Send"
+ >
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
+ <path d="M2 8L14 2L9 14L7.5 9.5L2 8z" stroke="currentColor" stroke-width="1.4" fill="none" stroke-linejoin="round" />
+ </svg>
+ </button>
+ </form>
</div>
- <!-- Bottom action bar — single hierarchy, no competing CTAs -->
- <div class="nxt-action-bar">
+ <!-- Secondary action bar — animations / upload / save below the chat dock -->
+ <div class="nxt-action-bar nxt-action-bar--secondary">
<button
class="nxt-action nxt-action--ghost"
id="nxt-anim-btn"
@@ -120,7 +215,7 @@
aria-controls="nxt-anim-sheet"
title="Browse animations (A)"
>
- <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true">
+ <svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true">
<circle cx="10" cy="10" r="7.5" stroke="currentColor" stroke-width="1.5" fill="none" />
<path d="M8 7.5l4.5 2.5L8 12.5z" fill="currentColor" />
</svg>
@@ -129,7 +224,7 @@
</button>
<label class="nxt-action nxt-action--ghost" for="file-input" title="Drop or pick a GLB/glTF (U)">
- <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true">
+ <svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true">
<path d="M10 3v9m-4-4l4-4 4 4M4 15h12" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<span>Upload model</span>
@@ -142,7 +237,7 @@
id="nxt-primary"
type="button"
>
- <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true">
+ <svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true">
<path d="M5 11l3 3 7-7" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<span id="nxt-primary-label">Sign in to save</span>
@@ -169,14 +264,61 @@
</div>
</div>
+ <!-- Share / embed popover -->
+ <div class="nxt-share-popover" id="nxt-share-popover" hidden role="dialog" aria-labelledby="nxt-share-title">
+ <header class="nxt-share-popover__head">
+ <h2 id="nxt-share-title">Share this agent</h2>
+ <button class="nxt-share-close" id="nxt-share-close" type="button" aria-label="Close">×</button>
+ </header>
+ <div class="nxt-share-popover__body">
+ <label class="nxt-share-row">
+ <span class="nxt-share-label">Page URL</span>
+ <div class="nxt-share-copy">
+ <input id="nxt-share-url" type="text" readonly />
+ <button id="nxt-share-url-copy" type="button">Copy</button>
+ </div>
+ </label>
+ <label class="nxt-share-row">
+ <span class="nxt-share-label">Embed snippet</span>
+ <div class="nxt-share-copy nxt-share-copy--block">
+ <textarea id="nxt-share-embed" rows="3" readonly></textarea>
+ <button id="nxt-share-embed-copy" type="button">Copy</button>
+ </div>
+ </label>
+ <p class="nxt-share-hint">Drop the snippet on any site. Same agent, same animations, same identity — embedded.</p>
+ </div>
+ </div>
+
<!-- Spinner required by app.js -->
<div class="spinner"></div>
</main>
- <!-- Hint chip — only on first visit -->
+ <!-- First-visit hint -->
<div class="nxt-first-hint" id="nxt-first-hint" hidden>
- <span>Click the avatar — try an animation, drag to rotate, scroll to zoom.</span>
+ <span>Drag to rotate · scroll to zoom · or just <strong>ask the agent</strong> something below.</span>
<button id="nxt-first-hint-close" type="button" aria-label="Dismiss">×</button>
</div>
+
+ <!-- Keyboard help (toggled with ?) -->
+ <div class="nxt-help" id="nxt-help" hidden role="dialog" aria-labelledby="nxt-help-title">
+ <header class="nxt-help__head">
+ <h2 id="nxt-help-title">Keyboard shortcuts</h2>
+ <button class="nxt-help__close" id="nxt-help-close" type="button" aria-label="Close">×</button>
+ </header>
+ <dl class="nxt-help__grid">
+ <dt><kbd>A</kbd></dt><dd>Open animation picker</dd>
+ <dt><kbd>U</kbd></dt><dd>Upload a model</dd>
+ <dt><kbd>S</kbd></dt><dd>Share / embed</dd>
+ <dt><kbd>F</kbd></dt><dd>Fullscreen</dd>
+ <dt><kbd>/</kbd></dt><dd>Focus chat input</dd>
+ <dt><kbd>1</kbd>–<kbd>4</kbd></dt><dd>Camera presets (Face / Body / Wide / Hero)</dd>
+ <dt><kbd>Space</kbd></dt><dd>Push-to-talk (if mic available)</dd>
+ <dt><kbd>Esc</kbd></dt><dd>Close any open panel</dd>
+ <dt><kbd>?</kbd></dt><dd>Show this help</dd>
+ </dl>
+ </div>
+
+ <!-- Live toast region -->
+ <div class="nxt-toast" id="nxt-toast" role="status" aria-live="polite" hidden></div>
</body>
</html>
diff --git a/public/app-next.css b/public/app-next.css
index ef8eb8093..c85f3c428 100644
--- a/public/app-next.css
+++ b/public/app-next.css
@@ -58,10 +58,27 @@ body.app-next-body .phi-grid-label,
body.app-next-body .anim-panel,
body.app-next-body .agent-presence-sidebar,
body.app-next-body .save-toast,
-body.app-next-body .controls-toggle {
+body.app-next-body .controls-toggle,
+body.app-next-body .nich-toggle {
display: none !important;
}
+/* When NichAgent's panel is open (manually opened by overlay) restyle it to
+ match the dock — same glass, same accent. Override its absolute positioning
+ so it docks above the chat input rather than floating mid-screen. */
+body.app-next-body .nich-panel {
+ border-radius: 18px;
+ border-color: rgba(255, 255, 255, 0.08);
+ background: rgba(14, 15, 22, 0.92);
+ backdrop-filter: blur(22px) saturate(140%);
+ -webkit-backdrop-filter: blur(22px) saturate(140%);
+ box-shadow: 0 28px 80px rgba(0, 0, 0, 0.6);
+}
+
+body.app-next-body.nxt-chat-open .nxt-chat-dock {
+ z-index: 23;
+}
+
/* Override style.css `body { display: flex }` since we manage layout ourselves */
body.app-next-body {
display: block;
diff --git a/public/style.css b/public/style.css
index 8e5aebdd3..785a25646 100644
--- a/public/style.css
+++ b/public/style.css
@@ -8259,6 +8259,15 @@ body[data-layout='next'] .next-drawer__body .dg.main .close-button.close-bottom
border-color: rgba(139, 92, 246, 0.5);
color: #fff;
}
+.next-grid__icon {
+ flex-shrink: 0;
+ font-size: 16px;
+ line-height: 1;
+ width: 18px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+}
.next-grid__label {
overflow: hidden;
text-overflow: ellipsis;
diff --git a/scripts/widgets-gallery-smoke.mjs b/scripts/widgets-gallery-smoke.mjs
new file mode 100644
index 000000000..546439ea0
--- /dev/null
+++ b/scripts/widgets-gallery-smoke.mjs
@@ -0,0 +1,106 @@
+import puppeteer from 'puppeteer';
+
+const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox'],
+});
+const page = await browser.newPage();
+await page.setViewport({ width: 1280, height: 900 });
+
+const errors = [];
+page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));
+page.on('console', (msg) => {
+ if (msg.type() === 'error') errors.push(`console.error: ${msg.text()}`);
+});
+
+await page.goto('http://localhost:3000/widgets/', { waitUntil: 'networkidle2', timeout: 30000 });
+
+// Wait for gallery cards to render (not skeletons)
+await page.waitForFunction(
+ () => document.querySelectorAll('#gallery-grid .showcase:not(.showcase-skeleton)').length >= 8,
+ { timeout: 15000 },
+);
+
+const cardCount = await page.$$eval(
+ '#gallery-grid .showcase:not(.showcase-skeleton)',
+ (els) => els.length,
+);
+console.log('cards rendered:', cardCount);
+
+const types = await page.$$eval('#gallery-grid .showcase:not(.showcase-skeleton)', (els) =>
+ els.map((e) => e.dataset.type),
+);
+console.log('types:', types.join(', '));
+
+// Check tab presence on first card
+const tabCount = await page.$$eval('.frame-tabs .frame-tab', (els) => els.length);
+console.log('tabs on first cards:', tabCount, '(expected >= 16 = 8 cards × 2 tabs)');
+
+// Check customize panel + split button presence
+const customizeCount = await page.$$eval('.customize', (els) => els.length);
+const splitBtnCount = await page.$$eval('.split-btn', (els) => els.length);
+console.log('customize panels:', customizeCount, '/ split-btn count:', splitBtnCount);
+
+// Click the Code tab on the first kol-trades card; verify iframe hides + code shows
+const kolCard = await page.$('.showcase[data-type="kol-trades"]');
+if (kolCard) {
+ const tabs = await kolCard.$$('.frame-tab');
+ const codeTab = tabs[1];
+ await codeTab.click();
+ await new Promise((r) => setTimeout(r, 100));
+ const codeVisible = await kolCard.$eval('.frame-code-panel', (el) => !el.hidden);
+ const frameHidden = await kolCard.$eval('.showcase-frame', (el) => el.hidden);
+ console.log('after Code tab click: code visible =', codeVisible, ', frame hidden =', frameHidden);
+ const codeText = await kolCard.$eval('.frame-code code', (el) => el.textContent);
+ console.log('code panel includes EPjFW USDC mint:', codeText.includes('EPjFWdd5'));
+
+ // Switch back to Preview
+ await tabs[0].click();
+ await new Promise((r) => setTimeout(r, 100));
+
+ // Open customize and change mint
+ const summary = await kolCard.$('.customize > summary');
+ await summary.click();
+ await new Promise((r) => setTimeout(r, 200));
+ const mintInput = await kolCard.$('.knob-row input[type="text"]');
+ await mintInput.click({ clickCount: 3 });
+ await mintInput.type('NEWMINTaddressXYZ');
+ await new Promise((r) => setTimeout(r, 500));
+ const snippet = await kolCard.$eval('.snippet code', (el) => el.textContent);
+ console.log('after mint change, snippet contains NEWMINTaddressXYZ:', snippet.includes('NEWMINTaddressXYZ'));
+
+ // Open format dropdown
+ const toggle = await kolCard.$('.split-btn-toggle');
+ await toggle.click();
+ await new Promise((r) => setTimeout(r, 100));
+ const menuVisible = await kolCard.$eval('.split-btn-menu', (el) => !el.hidden);
+ console.log('format menu opens on toggle:', menuVisible);
+
+ // Pick JSX
+ const items = await kolCard.$$('.split-btn-menu-item');
+ await items[1].click();
+ await new Promise((r) => setTimeout(r, 100));
+ const jsxSnippet = await kolCard.$eval('.snippet code', (el) => el.textContent);
+ console.log('JSX snippet starts with <iframe and contains style={{ :', jsxSnippet.startsWith('<iframe') && jsxSnippet.includes('style={{'));
+}
+
+// Verify accent color change updates snippet hash
+const turntableCard = await page.$('.showcase[data-type="turntable"]');
+if (turntableCard) {
+ await turntableCard.$eval('.customize > summary', (el) => el.click());
+ await new Promise((r) => setTimeout(r, 200));
+ const colorInput = await turntableCard.$('.knob-row input[type="color"]');
+ await colorInput.evaluate((el) => {
+ el.value = '#ff0080';
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await new Promise((r) => setTimeout(r, 200));
+ const snip = await turntableCard.$eval('.snippet code', (el) => el.textContent);
+ console.log('turntable snippet after accent change includes accent param:', snip.includes('accent='));
+}
+
+console.log('errors:', errors.length === 0 ? 'none' : errors.join('\n '));
+await page.screenshot({ path: '/tmp/widgets-gallery.png', fullPage: false });
+console.log('screenshot saved to /tmp/widgets-gallery.png');
+
+await browser.close();
diff --git a/src/account.js b/src/account.js
index f1d1d2f28..0f8d7b2a4 100644
--- a/src/account.js
+++ b/src/account.js
@@ -159,7 +159,13 @@ export async function getMe() {
// err.redirected = true). Callers that want post-login resume should set
// their sentinel BEFORE calling — apiFetch's redirect happens synchronously.
export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
- const { onProgress } = opts;
+ const { onProgress, signal } = opts;
+ const throwIfAborted = () => {
+ if (signal?.aborted) {
+ throw stageError('upload', 'Upload aborted', { code: 'upload_aborted' });
+ }
+ };
+ throwIfAborted();
// Preflight the session ourselves so the caller can set up post-login
// resume state *before* any redirect. apiFetch's built-in 401 handler
@@ -238,16 +244,27 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
blob,
contentType,
onProgress,
+ signal,
});
storageKey = presign.storage_key;
} catch (err) {
+ if (err.code === 'upload_aborted') throw err;
if (err.code !== 'upload_blocked') {
err.stage = err.stage || 'upload';
throw err;
}
console.warn('[account] direct R2 PUT blocked; retrying via server proxy');
+ // Reset progress so the proxy attempt restarts visibly at 0% rather than
+ // looking stuck at whatever the direct PUT reached before failing.
+ onProgress?.(0);
try {
- const proxied = await uploadViaProxy({ blob, contentType, checksum, onProgress });
+ const proxied = await uploadViaProxy({
+ blob,
+ contentType,
+ checksum,
+ onProgress,
+ signal,
+ });
storageKey = proxied.storage_key;
} catch (proxyErr) {
proxyErr.stage = proxyErr.stage || 'upload';
@@ -477,8 +494,12 @@ async function captureAndTagAvatar(avatarId, storageKey) {
//
// onProgress is called with an integer 0..100. fetch() has no upload-progress
// hook in any browser, so XHR is the only path that works today.
-function putToR2({ url, blob, contentType, onProgress }) {
+function putToR2({ url, blob, contentType, onProgress, signal }) {
return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(stageError('upload', 'Upload aborted', { code: 'upload_aborted' }));
+ return;
+ }
const xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('content-type', contentType);
@@ -490,7 +511,11 @@ function putToR2({ url, blob, contentType, onProgress }) {
};
xhr.upload.onload = () => onProgress(100);
}
+ const onAbort = () => xhr.abort();
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
+ const cleanup = () => signal?.removeEventListener('abort', onAbort);
xhr.onload = () => {
+ cleanup();
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
return;
@@ -504,6 +529,7 @@ function putToR2({ url, blob, contentType, onProgress }) {
);
};
xhr.onerror = () => {
+ cleanup();
// status 0 ⇒ no HTTP response. CORS preflight failure is by far the
// most common cause; surface a hint the UI can render.
reject(
@@ -514,8 +540,10 @@ function putToR2({ url, blob, contentType, onProgress }) {
),
);
};
- xhr.onabort = () =>
+ xhr.onabort = () => {
+ cleanup();
reject(stageError('upload', 'Upload aborted', { code: 'upload_aborted' }));
+ };
xhr.send(blob);
});
}
@@ -528,7 +556,10 @@ function putToR2({ url, blob, contentType, onProgress }) {
// Uses XHR (not fetch) so onProgress works in every browser. CSRF is fetched
// from the same single-use endpoint apiFetch uses; we don't go through
// apiFetch because it can't propagate upload progress.
-async function uploadViaProxy({ blob, contentType, checksum, onProgress }) {
+async function uploadViaProxy({ blob, contentType, checksum, onProgress, signal }) {
+ if (signal?.aborted) {
+ throw stageError('upload', 'Upload aborted', { code: 'upload_aborted' });
+ }
const csrf = await getCsrfToken();
_csrfToken = null; // single-use, like apiFetch
const qs = new URLSearchParams({ content_type: contentType });
@@ -549,7 +580,11 @@ async function uploadViaProxy({ blob, contentType, checksum, onProgress }) {
};
xhr.upload.onload = () => onProgress(100);
}
+ const onAbort = () => xhr.abort();
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
+ const cleanup = () => signal?.removeEventListener('abort', onAbort);
xhr.onload = () => {
+ cleanup();
if (xhr.status === 401) {
redirectToLogin();
reject(stageError('upload', 'session expired', { status: 401, code: 'not_signed_in' }));
@@ -573,10 +608,14 @@ async function uploadViaProxy({ blob, contentType, checksum, onProgress }) {
),
);
};
- xhr.onerror = () =>
+ xhr.onerror = () => {
+ cleanup();
reject(stageError('upload', 'proxy upload network error', { code: 'proxy_upload_failed' }));
- xhr.onabort = () =>
+ };
+ xhr.onabort = () => {
+ cleanup();
reject(stageError('upload', 'proxy upload aborted', { code: 'upload_aborted' }));
+ };
xhr.send(blob);
});
}
diff --git a/src/avatar-embed.js b/src/avatar-embed.js
index c24d921c2..e6dcae1d8 100644
--- a/src/avatar-embed.js
+++ b/src/avatar-embed.js
@@ -80,10 +80,32 @@ const CAPABILITIES = [
'mocap',
'idle',
'bg',
+ 'overlay',
+ 'hotkey',
+ 'state',
+ 'mic',
];
const HEAD_BONE_NAMES = ['head', 'neck'];
+// ── Default hotkey → ARKit-52 morph map ───────────────────────────────────
+// Modeled after Veadotube/VTube Studio's quick-action panel. Keys 1-9 map to
+// named emotes that any host can override via the v1.avatar.hotkeys message.
+// Each entry is a list of { name, weight, hold } records — names go through
+// MORPH_ALIASES so combined morphs like `mouthSmile` resolve to L+R.
+const DEFAULT_HOTKEYS = Object.freeze({
+ '1': { label: 'smile', hold: 1500, morphs: { mouthSmileLeft: 0.85, mouthSmileRight: 0.85, cheekSquintLeft: 0.4, cheekSquintRight: 0.4 } },
+ '2': { label: 'wink', hold: 280, morphs: { eyeBlinkLeft: 1, mouthSmileLeft: 0.5, mouthSmileRight: 0.3 } },
+ '3': { label: 'surprised', hold: 1400, morphs: { jawOpen: 0.55, eyeWideLeft: 0.8, eyeWideRight: 0.8, browInnerUp: 0.7 } },
+ '4': { label: 'sad', hold: 1800, morphs: { mouthFrownLeft: 0.7, mouthFrownRight: 0.7, browInnerUp: 0.55 } },
+ '5': { label: 'angry', hold: 1600, morphs: { browDownLeft: 0.8, browDownRight: 0.8, mouthPressLeft: 0.6, mouthPressRight: 0.6, noseSneerLeft: 0.4, noseSneerRight: 0.4 } },
+ '6': { label: 'disgust', hold: 1600, morphs: { noseSneerLeft: 0.8, noseSneerRight: 0.8, mouthUpperUpLeft: 0.55, mouthUpperUpRight: 0.55, eyeSquintLeft: 0.45, eyeSquintRight: 0.45 } },
+ '7': { label: 'thinking', hold: 1800, morphs: { eyeLookUpLeft: 0.6, eyeLookUpRight: 0.6, mouthLeft: 0.35, browOuterUpLeft: 0.45 } },
+ '8': { label: 'kiss', hold: 1200, morphs: { mouthPucker: 0.95, eyeBlinkLeft: 0.6, eyeBlinkRight: 0.6 } },
+ '9': { label: 'tongue', hold: 1400, morphs: { tongueOut: 0.9, jawOpen: 0.45, mouthSmileLeft: 0.4, mouthSmileRight: 0.4 } },
+ '0': { label: 'neutral', hold: 80, morphs: {} },
+});
+
main().catch((err) => {
showError(err?.message || 'Could not load avatar');
});
@@ -92,6 +114,12 @@ async function main() {
const params = new URL(location.href).searchParams;
applyBackground(params.get('bg') || 'transparent');
+ // Overlay mode — chrome-free canvas for OBS Browser Source. Hides the
+ // name plate, mocap pill, and error positioning; treats the body as a
+ // pure render surface. Press space to re-show chrome (VSeeFace "※" pattern).
+ const overlayMode = params.get('overlay') === '1' || params.get('chrome') === '0';
+ if (overlayMode) document.body.classList.add('overlay-mode');
+
// ── Resolve which avatar to render ─────────────────────────────────────
const resolved = await resolveAvatar(params);
if (!resolved) {
@@ -99,7 +127,7 @@ async function main() {
return;
}
- const namePlate = params.get('name') !== '0';
+ const namePlate = !overlayMode && params.get('name') !== '0';
if (namePlate && resolved.name) {
document.getElementById('name-plate').textContent = resolved.name;
}
diff --git a/src/create-review-features.js b/src/create-review-features.js
index f618f0a6a..1d7e72926 100644
--- a/src/create-review-features.js
+++ b/src/create-review-features.js
@@ -251,28 +251,75 @@ export function openVoicePreview({ glbUrl, name }) {
// ── Static info modals (identity / paid / embed / reputation) ────────────────
-export function openIdentityModal() {
+export async function openIdentityModal(ctx = {}) {
+ // Render the shell synchronously so the modal opens instantly. The keypair
+ // generation is fast (~ms) but the import is a fat dependency — load it
+ // in the background and patch the address in once it resolves.
+ const body = document.createElement('div');
+ body.innerHTML = `
+ <ul class="fm-bullets">
+ <li>Owned by your wallet, not by three.ws — transfer or sell at any time.</li>
+ <li>Metadata (avatar URL, persona, voice) is mutable by you, signed on-chain.</li>
+ <li>Discoverable in the agent registry by capability, price, and reputation.</li>
+ </ul>
+ <div class="fm-id-card" data-state="loading">
+ <div class="fm-id-head">
+ <span class="fm-id-chain">Solana mainnet</span>
+ <span class="fm-id-pill" data-pill>generating…</span>
+ </div>
+ <div class="fm-id-addr" data-addr>—</div>
+ <div class="fm-id-meta">
+ <div><span class="muted">Name</span><strong data-name>${escapeHtml(ctx.name || 'Your new avatar')}</strong></div>
+ <div><span class="muted">Asset standard</span><strong>Metaplex Core</strong></div>
+ </div>
+ <button class="fm-copy fm-id-copy" type="button" data-copy-addr disabled>Copy address</button>
+ </div>
+ <p class="fm-note">Sample keypair generated locally — your real agent gets a unique address on save. Nothing is broadcast.</p>
+ `;
+
openFeatureModal({
icon: '🪪',
title: 'On-Chain Identity',
lede: 'Your agent becomes a Metaplex Core asset on Solana the moment you save — transferable, composable, browsable in any wallet.',
- body: `
- <ul class="fm-bullets">
- <li>Owned by your wallet, not by three.ws — transfer or sell at any time.</li>
- <li>Metadata (avatar URL, persona, voice) is mutable by you, signed on-chain.</li>
- <li>Discoverable in the registry by capability, price, and reputation.</li>
- </ul>
- <div class="fm-row">
- <div>
- <strong>Agent wallet</strong>
- <div class="muted">Solana address · generated when you save</div>
- </div>
- <code class="fm-placeholder">&lt;your·agent·wallet&gt;</code>
- </div>
- <p class="fm-note">No network calls happen until you save — this preview is local.</p>
- `,
+ body,
actions: [{ label: 'Got it' }],
});
+
+ // Generate a real, throwaway sample keypair in-browser so the preview
+ // shows a *real-shaped* base58 address rather than an obvious placeholder.
+ // Private key is discarded — this is purely a visual proof of "real Solana
+ // addresses, not lorem ipsum".
+ try {
+ const { Keypair } = await import('@solana/web3.js');
+ const kp = Keypair.generate();
+ const addr = kp.publicKey.toBase58();
+ const card = body.querySelector('.fm-id-card');
+ card.dataset.state = 'ready';
+ card.querySelector('[data-pill]').textContent = 'preview';
+ card.querySelector('[data-addr]').textContent = addr;
+ const copy = card.querySelector('[data-copy-addr]');
+ copy.disabled = false;
+ copy.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(addr);
+ copy.textContent = 'Copied';
+ copy.classList.add('copied');
+ setTimeout(() => {
+ copy.textContent = 'Copy address';
+ copy.classList.remove('copied');
+ }, 1600);
+ } catch {
+ copy.textContent = 'Press ⌘C';
+ }
+ });
+ } catch (err) {
+ const card = body.querySelector('.fm-id-card');
+ card.dataset.state = 'error';
+ card.querySelector('[data-pill]').textContent = 'unavailable';
+ card.querySelector('[data-addr]').textContent =
+ 'Couldn\'t load keypair generator — your real address is created on save.';
+ console.warn('[identity-preview] keypair gen failed', err);
+ }
}
export function openPaidSkillsModal() {
@@ -299,29 +346,106 @@ export function openPaidSkillsModal() {
});
}
-export function openEmbedModal() {
- // Template, not a fake value: the placeholder reads as a parameter the user
- // has to fill in after saving. Copy still works — they get the exact tag
- // shape they'll need.
- const snippet = `<script src="https://three.ws/embed.js"
- data-agent="<your-agent-id>"
- data-mode="full"
- async></script>`;
+export function openEmbedModal(ctx = {}) {
+ const handle = slugify(ctx.name) || 'your-agent';
+ const snippets = {
+ script: `<script async src="https://three.ws/embed.js"
+ data-widget="${handle}"
+ data-type="talking-agent"></script>`,
+ webcomponent: `<agent-3d agent="${handle}" mode="full"></agent-3d>
+<script type="module"
+ src="https://three.ws/embed/agent-3d.js"></script>`,
+ react: `import { Agent3D } from '@three.ws/react';
+
+export default function Page() {
+ return <Agent3D agent="${handle}" mode="full" />;
+}`,
+ iframe: `<iframe
+ src="https://three.ws/widget#widget=${handle}&kiosk=true"
+ width="420" height="600"
+ style="border:0;border-radius:14px"
+ allow="microphone; autoplay"
+ loading="lazy"></iframe>`,
+ };
+
+ const body = document.createElement('div');
+ body.innerHTML = `
+ <ul class="fm-bullets">
+ <li>WebGL renders in-browser. No install, no plugin.</li>
+ <li>Modes: floating bubble, fullscreen, inline card, or sidebar.</li>
+ <li>Works in Webflow, Framer, raw HTML, React, Next.js, Squarespace.</li>
+ </ul>
+
+ <div class="fm-tabs" role="tablist" aria-label="Embed format">
+ <button class="fm-tab is-active" role="tab" data-tab="script">Script tag</button>
+ <button class="fm-tab" role="tab" data-tab="webcomponent">Web Component</button>
+ <button class="fm-tab" role="tab" data-tab="react">React</button>
+ <button class="fm-tab" role="tab" data-tab="iframe">iframe</button>
+ </div>
+ <div class="fm-code" data-copy-target>
+ <pre data-snippet></pre>
+ <button class="fm-copy" type="button">Copy</button>
+ </div>
+
+ <div class="fm-browser" aria-label="Live embed preview">
+ <div class="fm-browser-bar">
+ <span class="fm-browser-dot"></span>
+ <span class="fm-browser-dot"></span>
+ <span class="fm-browser-dot"></span>
+ <div class="fm-browser-url">three.ws/@${escapeHtml(handle)}</div>
+ </div>
+ <div class="fm-browser-stage" data-stage>
+ <img class="fm-browser-shot" alt="" data-shot hidden />
+ <div class="fm-browser-skeleton" data-skel>Rendering live preview…</div>
+ </div>
+ </div>
+ <p class="fm-note">Save your avatar to claim the real <code>data-widget</code> ID — copies above keep working with the placeholder.</p>
+ `;
+
openFeatureModal({
icon: '🧩',
title: 'Embed Anywhere',
- lede: 'One tag drops your agent on any site — Webflow, Framer, raw HTML, React, Squarespace, you name it.',
- body: `
- <ul class="fm-bullets">
- <li>WebGL renders in-browser. No install, no plugin.</li>
- <li>Modes: floating bubble, fullscreen, inline card, or sidebar.</li>
- <li>The <code>agent-3d</code> Web Component works in any framework.</li>
- </ul>
- <div class="fm-code" data-copy='${snippet.replace(/'/g, '&apos;')}'>${escapeHtml(snippet)}<button class="fm-copy" type="button">Copy</button></div>
- <p class="fm-note">Save your avatar to get a real <code>data-agent</code> ID and a one-click copy of the live snippet.</p>
- `,
+ lede: 'One tag drops your avatar on any site. Real snippet, real iframe shape, real preview of how it renders.',
+ body,
actions: [{ label: 'Got it' }],
+ dialogClass: 'fm-dialog--wide',
});
+
+ // Wire tabs ↔ snippet swap.
+ const codeEl = body.querySelector('[data-copy-target]');
+ const snippetEl = body.querySelector('[data-snippet]');
+ function setTab(name) {
+ body.querySelectorAll('.fm-tab').forEach((t) => t.classList.toggle('is-active', t.dataset.tab === name));
+ snippetEl.textContent = snippets[name];
+ codeEl.dataset.copy = snippets[name];
+ }
+ body.querySelectorAll('.fm-tab').forEach((t) => {
+ t.addEventListener('click', () => setTab(t.dataset.tab));
+ });
+ setTab('script');
+
+ // Live preview: capture a snapshot from the actual viewer canvas so the
+ // "this is what your embed will look like" frame shows *this avatar*,
+ // not a stock image. Falls back to a styled placeholder if the canvas
+ // isn't ready.
+ const stage = body.querySelector('[data-stage]');
+ const shot = body.querySelector('[data-shot]');
+ const skel = body.querySelector('[data-skel]');
+ const sourceCanvas = document.querySelector('#mv-container canvas');
+ if (sourceCanvas) {
+ try {
+ sourceCanvas.toBlob((b) => {
+ if (!b) return;
+ shot.src = URL.createObjectURL(b);
+ shot.hidden = false;
+ skel.hidden = true;
+ }, 'image/png');
+ } catch (err) {
+ console.warn('[embed-preview] canvas snapshot failed', err);
+ }
+ } else {
+ skel.textContent = 'Preview will render here once your avatar is loaded.';
+ }
}
// ── Download: real GLB / USDZ / VRM export from the staged blob ──────────────
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index c8c2439c9..a40af5a4f 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -53,6 +53,13 @@ export const api = {
`/api/widgets/${encodeURIComponent(id)}/transcripts?thread_id=${encodeURIComponent(threadId)}`,
),
listKnowledge: (id) => j('GET', `/api/widgets/${encodeURIComponent(id)}/knowledge`),
+ testKnowledge: (id, query) =>
+ j(
+ 'GET',
+ `/api/widgets/${encodeURIComponent(id)}/knowledge?test=${encodeURIComponent(query)}`,
+ ),
+ 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),
@@ -4643,6 +4650,17 @@ function renderStatsPanel(w, stats) {
const refList = referers.length
? `<details><summary>Top referrers</summary><ul style="margin:6px 0 0; padding-left:18px; font-size:12px; color:#aaa">${referers.map((r) => `<li>${esc(r.host || '(direct)')} — ${formatNum(r.count)}</li>`).join('')}</ul></details>`
: '';
+
+ const chatSpark =
+ stats.recent_chats_7d && stats.recent_chats_7d.length
+ ? `<div style="margin-top:10px"><div class="muted" style="font-size:11px; margin-bottom:4px">Visitor messages, last 7 days</div>${sparkline(stats.recent_chats_7d)}</div>`
+ : '';
+
+ const topQs = (stats.top_questions || []).slice(0, 5);
+ const topQsBlock = topQs.length
+ ? `<details style="margin-top:10px"><summary>Top questions</summary><ul style="margin:6px 0 0; padding-left:18px; font-size:12px; color:#ccc; display:flex; flex-direction:column; gap:4px">${topQs.map((q) => `<li><span style="opacity:0.7">×${formatNum(q.count)}</span> ${esc((q.question || '').slice(0, 140))}</li>`).join('')}</ul></details>`
+ : '';
+
return `
<div class="stat-grid">
<div class="stat"><div class="n">${formatNum(stats.view_count)}</div><div class="l">Views (lifetime)</div></div>
@@ -4653,7 +4671,9 @@ function renderStatsPanel(w, stats) {
<div style="margin-top:14px">
${sparkline(stats.recent_views_7d || [])}
</div>
+ ${chatSpark}
${refList}
+ ${topQsBlock}
`;
}
diff --git a/src/next-layout.js b/src/next-layout.js
index 3b70e3940..1d726f3d5 100644
--- a/src/next-layout.js
+++ b/src/next-layout.js
@@ -7,17 +7,16 @@
* buttons (Save / Widget / Deploy / Profile) plus Upload + Create. The layout
* is toggled via body[data-layout='next'] (see app.js _applyViewerLayout).
*
- * Wiring is direct: clip selection drives viewer.mixer.clipAction() and
- * playback state is read/written on the same AnimationAction the dock
- * exposes. The Controls drawer physically relocates the existing
- * viewer .gui-wrap DOM into a drawer body so dat.GUI continues to drive
- * camera/lighting/material state through its original onChange handlers —
- * no re-implementation, just a presentational reparent.
+ * Playback is driven through viewer.animationManager — the same path the
+ * existing AnimationPanel uses — so manifest-loaded clips, lazy fetches,
+ * crossfades, and the onChange callback work identically. The Controls
+ * drawer physically relocates the dat.GUI .gui-wrap into a drawer body so
+ * every camera/lighting/material knob keeps working through its original
+ * onChange handlers; no re-implementation.
*
- * Pulls in three concrete patterns from current best-in-class viewers:
+ * Borrows three concrete patterns from current best-in-class viewers:
* - Sketchfab-style single bottom bar with a real scrubbable timeline
- * - Babylon-Sandbox-style invisible full-page drag-drop with a tiny
- * floating gear that opens the controls drawer (Khronos drawer body)
+ * - Babylon-Sandbox-style full-page drop + floating gear → drawer (Khronos)
* - Google model-viewer-style auto-rotate-on-idle + a hand swipe prompt
* that disappears after the first interaction
*/
@@ -28,18 +27,54 @@ const STORAGE_KEY_INTERACTED = '3dagent:viewer-interacted';
const POLL_INTERVAL_MS = 100;
const POLL_MAX_MS = 15000;
+const ICON_FALLBACK = {
+ idle: '🧍',
+ breathing: '🧍',
+ standing: '🧍',
+ walking: '🚶',
+ walk: '🚶',
+ running: '🏃',
+ run: '🏃',
+ waving: '👋',
+ wave: '👋',
+ dancing: '💃',
+ dance: '💃',
+ sitting: '🪑',
+ sit: '🪑',
+ jumping: '🦘',
+ jump: '🦘',
+ talking: '🗣️',
+ talk: '🗣️',
+ clapping: '👏',
+ clap: '👏',
+ punching: '👊',
+ punch: '👊',
+ kicking: '🦵',
+ kick: '🦵',
+ covereyes: '🙈',
+ facepalm: '🤦',
+ 'av-waving': '👋',
+ 'av-superhero-jump': '🦸',
+ 'boxer-dance': '🥊',
+ 'av-brag-and-clap': '👏',
+ 'av-flex-arm': '💪',
+ 'av-walk-crouching': '🚶',
+ 'av-idle-breath': '🧘',
+ 'av-waiting': '🕰️',
+};
+
export class NextLayout {
constructor(app) {
this.app = app;
this.viewer = null;
- this.action = null;
- this.clipIdx = -1;
this.loop = true;
this.rafId = 0;
this.driverAttached = false;
this._guiMoved = false;
this._idleTimer = 0;
this._mounted = false;
+ this._defsRendered = false;
+ this._currentName = null;
}
mount() {
@@ -99,18 +134,20 @@ export class NextLayout {
const viewer = await this._waitForViewer();
if (!viewer) return;
this.viewer = viewer;
- await this._waitForClips(viewer);
+ await this._waitForDefs(viewer);
this._renderClipGrid();
- this._selectClipByIdx(0, { autoplay: false });
+ this._subscribeOnChange();
this._attachDriver();
this._armIdleAutoRotate();
+ // Seed dock state from the manager (it may already be playing 'idle').
+ this._onManagerChange(viewer.animationManager.currentName);
}
_waitForViewer() {
return new Promise((resolve) => {
const start = Date.now();
const poll = () => {
- if (this.app.viewer && this.app.viewer.controls) {
+ if (this.app.viewer && this.app.viewer.controls && this.app.viewer.animationManager) {
resolve(this.app.viewer);
return;
}
@@ -124,16 +161,22 @@ export class NextLayout {
});
}
- _waitForClips(viewer) {
+ _waitForDefs(viewer) {
return new Promise((resolve) => {
const start = Date.now();
const poll = () => {
- if (viewer.clips?.length && viewer.mixer) {
- resolve(viewer.clips.slice());
+ const defs = viewer.animationManager?.getAnimationDefs();
+ if (defs && defs.length > 0) {
+ resolve(defs);
+ return;
+ }
+ // Fall back to the GLB's built-in clips if no manifest exists.
+ if (viewer.clips?.length && viewer.mixer && Date.now() - start > 3000) {
+ resolve(this._defsFromClips(viewer.clips));
return;
}
if (Date.now() - start > POLL_MAX_MS) {
- resolve([]);
+ resolve(this._defsFromClips(viewer.clips || []));
return;
}
setTimeout(poll, POLL_INTERVAL_MS);
@@ -142,73 +185,128 @@ export class NextLayout {
});
}
+ _defsFromClips(clips) {
+ // Synthesize defs from GLB-built-in clips so the dock has something to
+ // show even on avatars without a manifest. Playback for these goes
+ // through viewer.mixer directly (see _playClipDef).
+ return clips.map((clip) => ({
+ name: clip.name,
+ label: _stripIdx(clip.name),
+ __builtin: clip,
+ }));
+ }
+
// ── animation playback ───────────────────────────────────────────────────
_renderClipGrid() {
+ if (this._defsRendered) return;
const grid = this.els.grid;
- if (!grid || !this.viewer?.clips) return;
+ if (!grid || !this.viewer) return;
+ const defs = this._currentDefs();
grid.innerHTML = '';
- const clips = this.viewer.clips;
const frag = document.createDocumentFragment();
- clips.forEach((clip, i) => {
+ defs.forEach((def) => {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'next-grid__item';
- btn.dataset.idx = String(i);
+ btn.dataset.name = def.name;
btn.setAttribute('role', 'option');
btn.setAttribute('aria-selected', 'false');
- btn.title = _stripIdx(clip.name);
+ btn.title = def.label || def.name;
+ const icon = document.createElement('span');
+ icon.className = 'next-grid__icon';
+ icon.textContent = def.icon || ICON_FALLBACK[def.name.toLowerCase()] || '▶';
const label = document.createElement('span');
label.className = 'next-grid__label';
- label.textContent = _stripIdx(clip.name);
+ label.textContent = def.label || def.name;
+ btn.appendChild(icon);
btn.appendChild(label);
btn.addEventListener('click', () => {
- this._selectClipByIdx(i, { autoplay: true });
+ this._playClipDef(def);
this._toggleGrid(false);
});
frag.appendChild(btn);
});
grid.appendChild(frag);
+ this._defsRendered = true;
+ }
+
+ _currentDefs() {
+ const mgr = this.viewer?.animationManager;
+ const manifest = mgr?.getAnimationDefs() || [];
+ if (manifest.length > 0) return manifest;
+ return this._defsFromClips(this.viewer?.clips || []);
+ }
+
+ async _playClipDef(def) {
+ const viewer = this.viewer;
+ if (!viewer) return;
+ if (def.__builtin) {
+ this._playBuiltinClip(def.__builtin);
+ return;
+ }
+ await viewer.animationManager.crossfadeTo(def.name, 0.2);
+ // onChange fires from inside crossfadeTo; UI updates land in _onManagerChange.
}
- _selectClipByIdx(idx, { autoplay }) {
+ _playBuiltinClip(clip) {
const viewer = this.viewer;
- if (!viewer?.mixer || !viewer.clips || idx < 0 || idx >= viewer.clips.length) return;
- this._stopAll();
- const clip = viewer.clips[idx];
+ if (!viewer?.mixer) return;
+ viewer.mixer.stopAllAction();
const action = viewer.mixer.clipAction(clip);
action.reset();
action.enabled = true;
action.setEffectiveTimeScale(1);
action.setEffectiveWeight(1);
this._applyLoop(action);
- if (autoplay) action.play();
- else action.paused = true;
- this.action = action;
- this.clipIdx = idx;
- if (viewer.state?.actionStates) {
- for (const k of Object.keys(viewer.state.actionStates)) {
- viewer.state.actionStates[k] = false;
- }
- viewer.state.actionStates[clip.name] = autoplay;
- }
- this._updateClipName();
+ action.play();
+ this._currentName = clip.name;
+ this._updateClipName(_stripIdx(clip.name));
this._updatePlayBtn();
- this._updateScrubAndTime();
this._updateGridHighlight();
viewer.invalidate();
}
- _stopAll() {
+ _subscribeOnChange() {
+ const mgr = this.viewer?.animationManager;
+ if (!mgr) return;
+ const prev = mgr.onChange;
+ mgr.onChange = (name) => {
+ try {
+ prev?.(name);
+ } catch {
+ /* keep our handler running even if a downstream listener throws */
+ }
+ this._onManagerChange(name);
+ };
+ }
+
+ _onManagerChange(name) {
+ this._currentName = name;
+ const def = this._currentDefs().find((d) => d.name === name);
+ this._updateClipName(def?.label || (name ? _stripIdx(name) : '—'));
+ this._updatePlayBtn();
+ this._updateGridHighlight();
+ // Re-apply loop preference on the new action.
+ const action = this._currentAction();
+ if (action) this._applyLoop(action);
+ }
+
+ _currentAction() {
const viewer = this.viewer;
- if (!viewer?.mixer) return;
- viewer.mixer.stopAllAction();
- if (viewer.state?.actionStates) {
- for (const k of Object.keys(viewer.state.actionStates)) viewer.state.actionStates[k] = false;
+ if (!viewer) return null;
+ const mgr = viewer.animationManager;
+ if (mgr?.currentAction) return mgr.currentAction;
+ // Fallback: built-in clip path uses viewer.mixer directly.
+ if (this._currentName && viewer.mixer && viewer.clips) {
+ const clip = viewer.clips.find((c) => c.name === this._currentName);
+ if (clip) return viewer.mixer.clipAction(clip);
}
+ return null;
}
_applyLoop(action) {
+ if (!action) return;
action.setLoop(this.loop ? LoopRepeat : LoopOnce, this.loop ? Infinity : 1);
action.clampWhenFinished = !this.loop;
}
@@ -223,28 +321,28 @@ export class NextLayout {
this.rafId = requestAnimationFrame(tick);
}
- _updateClipName() {
+ _updateClipName(text) {
if (!this.els.clipName) return;
- const clip = this.viewer?.clips?.[this.clipIdx];
- this.els.clipName.textContent = clip ? _stripIdx(clip.name) : '—';
+ this.els.clipName.textContent = text || '—';
}
_updatePlayBtn() {
const btn = this.els.playBtn;
if (!btn) return;
- const playing = Boolean(this.action && !this.action.paused);
+ const a = this._currentAction();
+ const playing = Boolean(a && !a.paused && a.isRunning());
btn.setAttribute('aria-pressed', String(playing));
btn.setAttribute('aria-label', playing ? 'Pause' : 'Play');
btn.classList.toggle('next-dock__play--playing', playing);
}
_updateScrubAndTime() {
- const a = this.action;
+ const a = this._currentAction();
const scrubInput = this.els.scrubInput;
const scrubFill = this.els.scrubFill;
const time = this.els.time;
if (!a) {
- if (scrubInput) scrubInput.value = '0';
+ if (scrubInput && document.activeElement !== scrubInput) scrubInput.value = '0';
if (scrubFill) scrubFill.style.width = '0%';
if (time) time.textContent = '0:00 / 0:00';
return;
@@ -263,7 +361,7 @@ export class NextLayout {
const grid = this.els.grid;
if (!grid) return;
grid.querySelectorAll('.next-grid__item').forEach((btn) => {
- const active = Number(btn.dataset.idx) === this.clipIdx;
+ const active = btn.dataset.name === this._currentName;
btn.classList.toggle('next-grid__item--active', active);
btn.setAttribute('aria-selected', String(active));
});
@@ -277,18 +375,23 @@ export class NextLayout {
});
this.els.playBtn?.addEventListener('click', () => {
- if (!this.action) return;
- if (this.action.paused) {
- const duration = this.action.getClip().duration || 0;
- // If we're at the end of a one-shot clip, rewind before playing.
- if (!this.loop && duration && this.action.time >= duration - 0.01) {
- this.action.reset();
- this._applyLoop(this.action);
+ const a = this._currentAction();
+ if (!a) {
+ // Nothing playing yet — auto-play the first available def.
+ const defs = this._currentDefs();
+ if (defs[0]) this._playClipDef(defs[0]);
+ return;
+ }
+ if (a.paused || !a.isRunning()) {
+ const duration = a.getClip().duration || 0;
+ if (!this.loop && duration && a.time >= duration - 0.01) {
+ a.reset();
+ this._applyLoop(a);
}
- this.action.paused = false;
- if (!this.action.isRunning()) this.action.play();
+ a.paused = false;
+ if (!a.isRunning()) a.play();
} else {
- this.action.paused = true;
+ a.paused = true;
}
this._updatePlayBtn();
this.viewer?.invalidate();
@@ -297,15 +400,14 @@ export class NextLayout {
const scrub = this.els.scrubInput;
if (scrub) {
const onScrub = () => {
- if (!this.action) return;
- const duration = this.action.getClip().duration || 0;
+ const a = this._currentAction();
+ if (!a) return;
+ const duration = a.getClip().duration || 0;
const pct = Number(scrub.value) / 1000;
- this.action.time = Math.max(0, Math.min(duration, pct * duration));
- if (this.action.paused) {
- // Manually advance so the mixer applies the new time even
- // while paused. dt=0 still triggers a pose update.
- this.viewer?.mixer?.update(0);
- }
+ a.time = Math.max(0, Math.min(duration, pct * duration));
+ // Tick the mixer with dt=0 so the new pose lands even while paused.
+ this.viewer?.mixer?.update(0);
+ this.viewer?.animationManager?.mixer?.update(0);
this._updateScrubAndTime();
this.viewer?.invalidate();
};
@@ -317,12 +419,12 @@ export class NextLayout {
this.loop = !this.loop;
this.els.loopBtn.setAttribute('aria-pressed', String(this.loop));
this.els.loopBtn.classList.toggle('next-dock__loop--off', !this.loop);
- if (this.action) this._applyLoop(this.action);
+ const a = this._currentAction();
+ if (a) this._applyLoop(a);
});
}
_wireGrid() {
- // Close grid on outside click.
document.addEventListener('click', (e) => {
const grid = this.els.grid;
const btn = this.els.clipBtn;
@@ -393,13 +495,11 @@ export class NextLayout {
this._toggleShare(false);
});
- // Wire Save → fire the original button's click handler.
this.els.shareSave?.addEventListener('click', () => {
document.getElementById('save-to-account-btn')?.click();
this._toggleShare(false);
});
- // Upload → trigger the existing #file-input picker (SimpleDropzone listens to it).
this.els.shareUpload?.addEventListener('click', () => {
document.getElementById('file-input')?.click();
this._toggleShare(false);
@@ -407,9 +507,6 @@ export class NextLayout {
}
_wireShareItemMirroring() {
- // The original action buttons toggle hidden + update href dynamically
- // based on auth/state. Mirror those changes onto the Share popover's
- // items so they reflect the same set of available actions.
const map = [
{ src: 'save-to-account-btn', dst: this.els.shareSave, type: 'btn' },
{ src: 'make-widget-btn', dst: this.els.shareWidget, type: 'link' },
@@ -434,6 +531,7 @@ export class NextLayout {
}
const isDeployed = srcEl.classList.contains('is-deployed');
dst.classList.toggle('next-share-menu__item--success', isDeployed);
+ this._updateShareDot();
};
sync();
const mo = new MutationObserver(sync);
@@ -445,7 +543,6 @@ export class NextLayout {
characterData: true,
});
}
- // Reflect available actions count on the corner button (subtle dot).
this._updateShareDot();
}
@@ -546,9 +643,10 @@ export class NextLayout {
this.root?.setAttribute('aria-hidden', String(!next));
if (next) {
this._mountGuiIntoDrawer();
+ // If clips loaded after first mount, ensure grid reflects the latest defs.
+ this._defsRendered = false;
+ this._renderClipGrid();
} else if (this._guiMoved) {
- // Return the dat.GUI panel back to the viewer container so the
- // Classic .gui-toggle keeps working when the user flips back.
const wrap = document.querySelector('.gui-wrap');
const viewerEl = document.getElementById('viewer-container');
if (wrap && viewerEl) {