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.

embed pages, dashboard, create-review tweaks; widget module

nirholas95f3b0585713
diff --git a/pages/agent-embed.html b/pages/agent-embed.html
index 8367f140c..21f803c63 100644
--- a/pages/agent-embed.html
+++ b/pages/agent-embed.html
@@ -450,12 +450,36 @@
const avatarCtl = new AgentAvatar(viewer, protocol, identity);
avatarCtl.attach();
- // Echo every protocol action onto the bridge so hosts can mirror state
- // (chat UIs, telemetry, host-side animation triggers).
+ // Echo every protocol action onto the legacy bridge so hosts can mirror
+ // state (chat UIs, telemetry, host-side animation triggers).
protocol.on('*', (action) => {
postToParent({ type: 'agent:action', agentId, action });
});
+ // Modern bridge — accepts the v1 EmbedHostBridge envelope used by
+ // `<threews-avatar driveable>` and by the embed-host-bridge npm
+ // surface. Listens on the same window in parallel with the legacy
+ // `agent:action` handler above. Both fan into the same protocol bus,
+ // so AgentAvatar handles speak/gesture/look/emote identically no
+ // matter which envelope the host chose.
+ const modernBridge = new EmbedActionBridge({
+ protocol,
+ avatar: { id: identity.avatarId, name: identity.name },
+ manifest: { id: { agentId }, agentId, policy: null },
+ window,
+ getClips: () => {
+ const defs = viewer?.animationManager?.getAnimationDefs?.() || [];
+ return defs.map((d) => ({
+ name: d.name,
+ label: d.label || d.name,
+ icon: d.icon || null,
+ loop: !!d.loop,
+ source: d.source || null,
+ }));
+ },
+ });
+ modernBridge.start();
+
// Report content height to host so embed-sdk can auto-fit the iframe.
// Coalesce into rAF so a runaway resize observer can't flood the host.
let pendingPost = false;
diff --git a/pages/avatar-embed.html b/pages/avatar-embed.html
index 2b16cc2ab..0438b430a 100644
--- a/pages/avatar-embed.html
+++ b/pages/avatar-embed.html
@@ -96,14 +96,100 @@
color: #111;
border-color: rgba(0, 0, 0, 0.12);
}
+
+ /* Overlay mode — OBS Browser Source target. Strips all chrome so
+ * the canvas is the only renderable surface. Space-bar toggles
+ * the panel for in-stream emote control while keeping the canvas
+ * clean. */
+ body.overlay-mode #name-plate,
+ body.overlay-mode #mocap-pill,
+ body.overlay-mode #error {
+ display: none !important;
+ }
+ body.overlay-mode.panel-open #emote-panel {
+ display: grid;
+ }
+
+ #emote-panel {
+ position: absolute;
+ left: 50%;
+ bottom: 16px;
+ transform: translateX(-50%);
+ z-index: 5;
+ display: none;
+ grid-template-columns: repeat(10, auto);
+ gap: 6px;
+ padding: 8px;
+ border-radius: 12px;
+ background: rgba(0, 0, 0, 0.55);
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ backdrop-filter: blur(6px);
+ font-family: ui-monospace, SFMono-Regular, monospace;
+ font-size: 11px;
+ color: #fff;
+ user-select: none;
+ }
+ body.panel-open #emote-panel {
+ display: grid;
+ }
+ #emote-panel .slot {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ min-width: 48px;
+ padding: 6px 8px;
+ border-radius: 8px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(255, 255, 255, 0.04);
+ cursor: pointer;
+ line-height: 1;
+ }
+ #emote-panel .slot:hover,
+ #emote-panel .slot.active {
+ background: rgba(255, 255, 255, 0.12);
+ border-color: rgba(255, 255, 255, 0.3);
+ }
+ #emote-panel .slot .k {
+ font-weight: 600;
+ font-size: 12px;
+ color: #fff;
+ }
+ #emote-panel .slot .l {
+ font-size: 9px;
+ margin-top: 3px;
+ color: rgba(255, 255, 255, 0.7);
+ letter-spacing: 0.04em;
+ }
+
+ #state-pill {
+ position: absolute;
+ left: 12px;
+ top: 10px;
+ z-index: 4;
+ display: none;
+ padding: 4px 10px;
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.55);
+ color: #fff;
+ font-size: 10px;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ pointer-events: none;
+ }
+ body.show-state #state-pill {
+ display: inline-block;
+ }
</style>
</head>
<body>
<div id="stage"></div>
<div id="name-plate"></div>
+ <div id="state-pill" aria-live="polite">idle</div>
<div id="mocap-pill" role="button" tabindex="0" aria-label="Toggle webcam mocap">
<span class="dot"></span><span class="label">webcam mocap</span>
</div>
+ <div id="emote-panel" role="toolbar" aria-label="Emote hotkeys"></div>
<div id="error"></div>
<script type="module" src="/src/avatar-embed.js"></script>
diff --git a/src/avatar-face-capture.js b/src/avatar-face-capture.js
index a28d29149..fa0eab719 100644
--- a/src/avatar-face-capture.js
+++ b/src/avatar-face-capture.js
@@ -1,21 +1,28 @@
/**
- * Browser-side selfie → ARKit-52 blendshapes via MediaPipe Face Landmarker.
+ * Browser-side selfie → avatar shape transfer via MediaPipe Face Landmarker.
*
- * No bundling: the tasks-vision package + WASM model (~5 MB total) load on
- * demand from a CDN. The first call pays a one-time cost; subsequent
- * captures reuse the cached FaceLandmarker instance.
+ * Two outputs:
*
- * import { detectFaceBlendshapes } from './avatar-face-capture.js';
- * const lm = await detectFaceBlendshapes.loadLandmarker();
- * const map = await detectFaceBlendshapes(canvasOrImage, lm);
- * // map: { jawOpen: 0.12, mouthSmileLeft: 0.04, ... } (52 keys)
+ * 1. detectFaceBlendshapes() — raw 52 ARKit blendshape weights from the
+ * photo. These describe the *expression* the user was making, not their
+ * face *shape*. If the user smiled, mouthSmileLeft/Right will be high.
+ * Useful only for live-track or "freeze my current expression" flows.
*
- * The 52 returned keys are exactly the ARKit blendshape names so they bind
- * 1:1 to RPM / Avaturn / three.ws avatar morphs without any rename pass.
+ * 2. detectFaceIdentity() — identity-only morph weights derived from the
+ * 478-point landmark mesh via geometric ratios (face width, jaw width,
+ * lip thickness, eye spacing, etc.). This is what you want for
+ * "personalize from selfie": it captures who they are, not what they
+ * were doing with their face when the shutter fired.
*
- * License-trap reminder: MediaPipe and the face-landmarker model are both
- * Apache-2.0 — safe to ship. We do *not* bundle FLAME / DECA / SMPL-X weights
- * because those are research-only / non-commercial. See the survey notes.
+ * Why this split: RPM, Avaturn, and in3D all do the equivalent server-side
+ * via proprietary regressions. We can't bundle FLAME / SMPL / DECA weights
+ * (research-only licenses), and shipping the raw ARKit expression scores
+ * burns a smile into the avatar forever. The ratio heuristics are crude,
+ * but they ship, they respect licensing, and the user fine-tunes from the
+ * Sculpt panel anyway.
+ *
+ * No bundling: tasks-vision + WASM model (~5 MB) load on demand from a CDN.
+ * License: MediaPipe + face_landmarker.task are both Apache-2.0 — safe.
*/
// We load tasks-vision via dynamic ESM import. Pinning to a specific version
diff --git a/src/create-review-features.js b/src/create-review-features.js
index 1d7e72926..1f6a61787 100644
--- a/src/create-review-features.js
+++ b/src/create-review-features.js
@@ -322,28 +322,119 @@ export async function openIdentityModal(ctx = {}) {
}
}
-export function openPaidSkillsModal() {
+export function openPaidSkillsModal(ctx = {}) {
+ const handle = slugify(ctx.name) || 'your-agent';
+ const endpoint = `https://three.ws/api/agent/${handle}/ask`;
+ const snippets = {
+ curl: `# 1. Make the request — server replies 402 with payment terms
+curl -sS -X POST ${endpoint} \\
+ -H 'content-type: application/json' \\
+ -d '{"message":"hello"}'
+
+# → HTTP/1.1 402 Payment Required
+# → {"accepts":[{"network":"solana","asset":"USDC",
+# → "amount":"0.05","payTo":"<agent·wallet>"}]}
+
+# 2. Sign a USDC transfer for the quoted amount, retry with X-PAYMENT
+curl -sS -X POST ${endpoint} \\
+ -H 'content-type: application/json' \\
+ -H 'x-payment: <base64-signed-payload>' \\
+ -d '{"message":"hello"}'
+
+# → HTTP/1.1 200 OK
+# → {"reply":"Hi! How can I help?","tx":"<solana·tx·sig>"}`,
+ fetch: `import { withX402 } from '@three.ws/x402-fetch';
+
+// withX402 wraps fetch — intercepts 402, signs USDC, retries.
+const fetchPaid = withX402(fetch, { wallet, network: 'solana' });
+
+const res = await fetchPaid('${endpoint}', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ message: 'hello' }),
+});
+
+console.log(await res.json()); // { reply, tx }`,
+ python: `from three_ws import X402Client
+
+client = X402Client(wallet=wallet, network="solana")
+
+reply = client.post(
+ "${endpoint}",
+ json={"message": "hello"},
+)
+print(reply.json()) # {"reply": "...", "tx": "<sig>"}`,
+ };
+
+ const body = document.createElement('div');
+ body.innerHTML = `
+ <ul class="fm-bullets">
+ <li>Quoted in USDC on Solana — payments settle in seconds, signed end-to-end.</li>
+ <li>Set a price per skill (chat, render, custom endpoint) after saving.</li>
+ <li>Earnings stream into your agent's wallet, withdrawable any time.</li>
+ </ul>
+
+ <div class="fm-handshake" aria-label="x402 handshake">
+ <div class="fm-handshake-step">
+ <span class="fm-handshake-num">1</span>
+ <div>
+ <strong>Client calls</strong>
+ <div class="muted">No auth, just hits the endpoint.</div>
+ </div>
+ <span class="fm-handshake-code">POST</span>
+ </div>
+ <div class="fm-handshake-arrow">→</div>
+ <div class="fm-handshake-step">
+ <span class="fm-handshake-num">2</span>
+ <div>
+ <strong>Server replies <code>402</code></strong>
+ <div class="muted">Quotes <code>$0.05</code> USDC on Solana.</div>
+ </div>
+ <span class="fm-handshake-code">402</span>
+ </div>
+ <div class="fm-handshake-arrow">→</div>
+ <div class="fm-handshake-step">
+ <span class="fm-handshake-num">3</span>
+ <div>
+ <strong>Client signs &amp; retries</strong>
+ <div class="muted"><code>X-PAYMENT</code> header carries the signed transfer.</div>
+ </div>
+ <span class="fm-handshake-code">200</span>
+ </div>
+ </div>
+
+ <div class="fm-tabs" role="tablist" aria-label="Client language">
+ <button class="fm-tab is-active" role="tab" data-tab="curl">cURL</button>
+ <button class="fm-tab" role="tab" data-tab="fetch">JavaScript</button>
+ <button class="fm-tab" role="tab" data-tab="python">Python</button>
+ </div>
+ <div class="fm-code" data-copy-target>
+ <pre data-snippet></pre>
+ <button class="fm-copy" type="button">Copy</button>
+ </div>
+ <p class="fm-note">Endpoint shape is real — your handle is filled in as you name your avatar. Pricing &amp; gating is configured after save.</p>
+ `;
+
openFeatureModal({
icon: '💸',
title: 'Paid Skills (x402)',
lede: 'Charge per call in USDC over the x402 protocol. Other agents (and apps) pay yours automatically — no API keys, no invoicing.',
- body: `
- <ul class="fm-bullets">
- <li>Set a price per skill — chat, render, custom endpoint, anything.</li>
- <li>Payments settle on Base in USDC, signed and verifiable.</li>
- <li>Your earnings stream into your agent's wallet, withdrawable any time.</li>
- </ul>
- <div class="fm-row">
- <div>
- <strong>Example pricing</strong>
- <div class="muted">You set this after saving</div>
- </div>
- <code style="color: var(--accent); font-weight: 600;">$0.05 / chat call</code>
- </div>
- <p class="fm-note">Listing your agent is free — you only pay if/when it earns.</p>
- `,
+ body,
actions: [{ label: 'Got it' }],
+ dialogClass: 'fm-dialog--wide',
+ });
+
+ 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('curl');
}
export function openEmbedModal(ctx = {}) {
@@ -544,27 +635,66 @@ function prettyBytes(n) {
return `${(n / 1024 / 1024).toFixed(2)} MB`;
}
-export function openReputationModal() {
+export function openReputationModal(ctx = {}) {
+ const handle = slugify(ctx.name) || 'your-agent';
+ // Sample reviews — clearly labelled as such ("EXAMPLE" pill on the card).
+ // Structure mirrors src/reputation-ui.js so the user sees the actual
+ // production shape (truncated reviewer address, stars, comment, tx link).
+ const sample = [
+ { author: '7xK…aN4q', stars: 5, comment: 'Sharp at SQL — saved me an hour on a gnarly join.', when: '2d ago' },
+ { author: '9mR…vT8p', stars: 5, comment: 'Voice felt natural over a 30-min call. Recommend.', when: '5d ago' },
+ { author: 'Bcj…F2zL', stars: 4, comment: 'Solid embed, easy to drop on our docs site.', when: '1w ago' },
+ ];
+
+ const reviewsHtml = sample
+ .map(
+ (r) => `
+ <div class="rep-review-item">
+ <div class="rep-review-header">
+ <span class="rep-review-author">${escapeHtml(r.author)}</span>
+ <span class="rep-stars" aria-label="${r.stars} stars">${'★'.repeat(r.stars)}${'☆'.repeat(5 - r.stars)}</span>
+ </div>
+ <p class="rep-comment">${escapeHtml(r.comment)}</p>
+ <div class="rep-review-footer">
+ <span class="muted">${escapeHtml(r.when)}</span>
+ <span class="rep-link">↗ tx</span>
+ </div>
+ </div>
+ `,
+ )
+ .join('');
+
openFeatureModal({
icon: '⭐',
title: 'Reputation',
- lede: 'Signed feedback, call history, and validation events accrue to your agent — visible to anyone deciding whether to trust it.',
+ lede: 'Signed feedback, call history, and validation events accrue to your agent — public, verifiable, portable.',
body: `
<ul class="fm-bullets">
<li>Every paid call is logged with a signed receipt — verifiable, non-repudiable.</li>
- <li>Users can leave reviews; reviews carry the reviewer's own reputation weight.</li>
- <li>Validators can attest to capability (e.g. "this agent reliably ships valid SQL").</li>
+ <li>Reviews carry the reviewer's own reputation weight — Sybil-resistant.</li>
+ <li>Validators can attest to capability (e.g. "ships valid SQL 9.6/10 of the time").</li>
</ul>
- <div class="fm-row">
- <div>
- <strong>Your starting rep</strong>
- <div class="muted">Reviews accrue as your agent is used</div>
+
+ <div class="rep-card">
+ <div class="rep-card-head">
+ <div>
+ <strong>${escapeHtml(handle)}</strong>
+ <div class="muted">three.ws/@${escapeHtml(handle)}</div>
+ </div>
+ <span class="rep-sample-pill">EXAMPLE</span>
+ </div>
+ <div class="rep-stats">
+ <div><strong class="rep-stat-big">4.8</strong><span class="rep-stars">★★★★★</span><span class="muted">37 reviews</span></div>
+ <div><strong>1,204</strong><span class="muted">paid calls</span></div>
+ <div><strong>0.41 SOL</strong><span class="muted">staked on rep</span></div>
</div>
- <code style="color: var(--muted);">★★★★★ · 0 reviews</code>
+ <div class="rep-reviews">${reviewsHtml}</div>
</div>
- <p class="fm-note">Your reputation lives on-chain alongside your agent — it travels with the asset.</p>
+
+ <p class="fm-note">Your starting rep is empty — every paid call and review accrues to your asset, on-chain, and travels with it if you ever transfer.</p>
`,
actions: [{ label: 'Got it' }],
+ dialogClass: 'fm-dialog--wide',
});
}
@@ -575,3 +705,16 @@ function escapeHtml(s) {
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
+
+/** URL-safe slug derived from the user's typed avatar name. */
+export function slugify(s) {
+ if (!s) return '';
+ return String(s)
+ .toLowerCase()
+ .trim()
+ .normalize('NFKD')
+ .replace(/[̀-ͯ]/g, '')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 32);
+}
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index a40af5a4f..755068f25 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -4423,13 +4423,27 @@ async function openWidgetDrawer(w, ctx) {
w.type === 'talking-agent'
? `
<section id="transcripts-region" aria-label="Chat transcripts">
- <h3 style="margin:18px 0 6px; font-size:13px; text-transform:uppercase; letter-spacing:0.06em; color:#aaa">Chat transcripts</h3>
+ <div style="display:flex; justify-content:space-between; align-items:baseline; margin:18px 0 6px">
+ <h3 style="margin:0; font-size:13px; text-transform:uppercase; letter-spacing:0.06em; color:#aaa">Chat transcripts</h3>
+ <a href="${attr(api.transcriptsCsvUrl(w.id))}" download class="btn sec" style="font-size:11px; padding:2px 8px">Download CSV</a>
+ </div>
<div id="transcripts-totals" class="muted" style="font-size:12px"></div>
<div id="transcripts-list" style="display:flex; flex-direction:column; gap:6px; margin-top:8px"></div>
<div id="transcripts-detail" hidden></div>
<div id="knowledge-region" style="margin-top:14px">
<h3 style="margin:0 0 6px; font-size:13px; text-transform:uppercase; letter-spacing:0.06em; color:#aaa">Knowledge</h3>
<div id="knowledge-summary" class="muted" style="font-size:12px">Loading…</div>
+ <details style="margin-top:8px">
+ <summary style="font-size:12px; cursor:pointer">Test a retrieval query</summary>
+ <div style="margin-top:8px; display:flex; flex-direction:column; gap:6px">
+ <div style="display:flex; gap:6px">
+ <input id="knowledge-test-q" type="text" placeholder='e.g. "what is your refund policy?"'
+ style="flex:1; background:#0f0f17; border:1px solid var(--border); border-radius:6px; padding:6px 8px; font-size:13px; color:#eee">
+ <button id="knowledge-test-go" type="button" class="btn sec" style="font-size:12px">Run</button>
+ </div>
+ <div id="knowledge-test-results" class="muted" style="font-size:12px"></div>
+ </div>
+ </details>
</div>
</section>
`
diff --git a/src/widget/rpc-server.js b/src/widget/rpc-server.js
new file mode 100644
index 000000000..29d042b31
--- /dev/null
+++ b/src/widget/rpc-server.js
@@ -0,0 +1,296 @@
+// JSON-RPC 2.0 server for the in-iframe widget surface.
+//
+// Parents that load /widget#... or /app#widget=... in an iframe can drive the
+// viewer programmatically by posting JSON-RPC messages:
+//
+// iframe.contentWindow.postMessage({
+// jsonrpc: '2.0', id: 1,
+// method: 'camera.setLookAt',
+// params: { eye: [0, 1.6, 3], target: [0, 1, 0], duration: 1.2 },
+// }, '*');
+//
+// The server replies with `{ jsonrpc: '2.0', id, result }` or
+// `{ jsonrpc: '2.0', id, error: { code, message } }`. It also pushes events
+// (notifications, no id) for viewer.ready, model.loaded, animation.ended, etc.
+//
+// The legacy `{ id, action, input }` bridge in app.js still works in parallel —
+// this module is additive, not a replacement.
+
+import { Vector3 } from 'three';
+import { protocol, ACTION_TYPES } from '../agent-protocol.js';
+
+const PROTOCOL = 'jsonrpc';
+const VERSION = '2.0';
+
+const ERR = {
+ PARSE: { code: -32700, message: 'Parse error' },
+ INVALID_REQUEST: { code: -32600, message: 'Invalid Request' },
+ METHOD_NOT_FOUND: { code: -32601, message: 'Method not found' },
+ INVALID_PARAMS: { code: -32602, message: 'Invalid params' },
+ INTERNAL: { code: -32603, message: 'Internal error' },
+ VIEWER_NOT_READY: { code: -32000, message: 'Viewer not ready' },
+};
+
+function arr3(v, fallback) {
+ if (Array.isArray(v) && v.length === 3 && v.every((n) => Number.isFinite(n))) return v;
+ return fallback;
+}
+
+/**
+ * Wire JSON-RPC handlers onto the App instance and start listening.
+ * @param {App} app — the running App
+ * @returns {() => void} teardown
+ */
+export function startWidgetRpcServer(app) {
+ const methods = buildMethods(app);
+ const onMessage = (event) => {
+ const msg = event.data;
+ if (!msg || typeof msg !== 'object' || msg.jsonrpc !== VERSION) return;
+ // Ignore replies from clients (responses to events we sent).
+ if (!msg.method) return;
+ // Require a string method; reject malformed.
+ if (typeof msg.method !== 'string') {
+ if (msg.id != null) reply(event, msg.id, null, ERR.INVALID_REQUEST);
+ return;
+ }
+ const handler = methods[msg.method];
+ if (!handler) {
+ if (msg.id != null) reply(event, msg.id, null, ERR.METHOD_NOT_FOUND);
+ return;
+ }
+ Promise.resolve()
+ .then(() => handler(msg.params || {}, event))
+ .then(
+ (result) => {
+ if (msg.id != null) reply(event, msg.id, result ?? {}, null);
+ },
+ (err) => {
+ if (msg.id != null) {
+ reply(event, msg.id, null, {
+ code: ERR.INTERNAL.code,
+ message: String(err?.message || err || 'error'),
+ });
+ }
+ },
+ );
+ };
+
+ window.addEventListener('message', onMessage);
+
+ // Push protocol-level lifecycle events to the parent. These mirror the
+ // internal protocol bus so any subscriber can know when the model is live.
+ const unsubLoad = protocol.on(ACTION_TYPES.LOAD_END, (action) => {
+ const success = action?.payload?.success === true;
+ if (success) {
+ emit('model.loaded', {
+ url: app._currentModelUrl || null,
+ success: true,
+ });
+ if (!app._rpcReadyFired) {
+ app._rpcReadyFired = true;
+ emit('viewer.ready', {});
+ }
+ } else {
+ emit('model.loaded', {
+ url: app._currentModelUrl || null,
+ success: false,
+ error: action?.payload?.error || 'load failed',
+ });
+ }
+ });
+
+ // Cleanup helper exposed for tests; production never tears this down.
+ return () => {
+ window.removeEventListener('message', onMessage);
+ unsubLoad();
+ };
+}
+
+/**
+ * Send a notification event to every plausible parent. We don't track a
+ * specific origin because widgets are embedded in unknown third-party pages;
+ * `*` is the standard for outbound notifications. Parents validate by
+ * checking `event.source === iframe.contentWindow` on their side.
+ */
+function emit(method, params) {
+ if (window.parent === window) return; // not in an iframe
+ try {
+ window.parent.postMessage({ jsonrpc: VERSION, method, params }, '*');
+ } catch {
+ /* parent gone — ignore */
+ }
+}
+
+function reply(event, id, result, error) {
+ const msg = error
+ ? { jsonrpc: VERSION, id, error }
+ : { jsonrpc: VERSION, id, result };
+ const replyTo = event.source || window.parent;
+ if (!replyTo) return;
+ // Reply to the exact origin we received from when we have one — otherwise
+ // fall back to '*'. The wildcard is safe because the reply is keyed to
+ // the request id, which the client generated.
+ const origin = event.origin && event.origin !== 'null' ? event.origin : '*';
+ try {
+ replyTo.postMessage(msg, origin);
+ } catch {
+ /* dead window — ignore */
+ }
+}
+
+function buildMethods(app) {
+ const requireViewer = () => {
+ const v = app.viewer || window.VIEWER?.app?.viewer;
+ if (!v) throw Object.assign(new Error(ERR.VIEWER_NOT_READY.message), {
+ code: ERR.VIEWER_NOT_READY.code,
+ });
+ return v;
+ };
+
+ return {
+ // ── Camera ────────────────────────────────────────────────────────────
+ 'camera.getLookAt': () => {
+ const v = requireViewer();
+ const cam = v.activeCamera || v.defaultCamera;
+ return {
+ eye: cam.position.toArray(),
+ target: v.controls.target.toArray(),
+ fov: cam.fov,
+ };
+ },
+ 'camera.setLookAt': (params) => {
+ const v = requireViewer();
+ const cam = v.activeCamera || v.defaultCamera;
+ const eye = arr3(params.eye, null);
+ const target = arr3(params.target, null);
+ const duration = Number(params.duration);
+ if (!eye && !target) throw new Error('eye or target required');
+ if (duration > 0) {
+ // Tween via the viewer's own helper.
+ const targetVec = target ? new Vector3().fromArray(target) : v.controls.target.clone();
+ const eyeVec = eye ? new Vector3().fromArray(eye) : cam.position.clone();
+ v._tweenCamera?.(eyeVec, targetVec, duration * 1000);
+ } else {
+ if (eye) cam.position.fromArray(eye);
+ if (target) v.controls.target.fromArray(target);
+ v.controls.update();
+ v.invalidate();
+ }
+ return {
+ eye: cam.position.toArray(),
+ target: v.controls.target.toArray(),
+ };
+ },
+ 'camera.recenter': (params) => {
+ const v = requireViewer();
+ v.frameContent({
+ animate: true,
+ durationMs: Number(params.duration) > 0 ? Number(params.duration) * 1000 : 600,
+ });
+ return {};
+ },
+
+ // ── Animation ─────────────────────────────────────────────────────────
+ 'animation.list': () => {
+ const v = requireViewer();
+ const defs = v.animationManager?.getAnimationDefs?.() || [];
+ const baked = (v.clips || []).map((c) => ({ name: c.name, duration: c.duration }));
+ return {
+ clips: [
+ ...defs.map((d) => ({ name: d.name, duration: d.duration ?? null })),
+ ...baked,
+ ],
+ };
+ },
+ 'animation.play': async (params) => {
+ const v = requireViewer();
+ const name = String(params.name || '').trim();
+ if (!name) throw new Error('name required');
+ const loop = params.loop !== false;
+ if (v.animationManager?.ensureLoaded) {
+ await v.animationManager.ensureLoaded(name).catch(() => {});
+ }
+ if (app.sceneCtrl?.playClipByName) {
+ app.sceneCtrl.playClipByName(name, { loop });
+ } else {
+ v.animationManager?.play?.(name, { loop });
+ }
+ return { name };
+ },
+ 'animation.stop': () => {
+ const v = requireViewer();
+ v.animationManager?.stop?.();
+ return {};
+ },
+
+ // ── Screenshot ────────────────────────────────────────────────────────
+ 'screenshot.capture': async (params) => {
+ const v = requireViewer();
+ // Render once into the offscreen buffer at the requested size, then
+ // snapshot. Falls back to canvas.toDataURL() if no resize requested.
+ const w = Math.round(Number(params.width) || 0);
+ const h = Math.round(Number(params.height) || 0);
+ if (w > 0 && h > 0) {
+ const blob = await v.captureScreenshot({ width: w, height: h }).catch(() => null);
+ if (blob) {
+ const reader = new FileReader();
+ return await new Promise((resolve, reject) => {
+ reader.onload = () => resolve({ dataUrl: reader.result });
+ reader.onerror = () => reject(new Error('blob read failed'));
+ reader.readAsDataURL(blob);
+ });
+ }
+ }
+ v.renderer.render(v.scene, v.activeCamera || v.defaultCamera);
+ const mime = String(params.mime || 'image/png');
+ return { dataUrl: v.renderer.domElement.toDataURL(mime) };
+ },
+
+ // ── Model swap ────────────────────────────────────────────────────────
+ 'model.load': async (params) => {
+ const url = String(params.url || '').trim();
+ if (!url) throw new Error('url required');
+ await app.view(url, '', new Map());
+ return { url };
+ },
+
+ // ── Display config ────────────────────────────────────────────────────
+ 'viewer.setBackground': (params) => {
+ const v = requireViewer();
+ if (!params.color) throw new Error('color required');
+ v.setBackgroundColor(params.color);
+ return {};
+ },
+ 'viewer.setAutoRotate': (params) => {
+ const v = requireViewer();
+ if (typeof params.enabled === 'boolean') v.controls.autoRotate = params.enabled;
+ if (typeof params.speed === 'number') v.controls.autoRotateSpeed = params.speed;
+ v.invalidate();
+ return {};
+ },
+ 'viewer.setEnvironment': (params) => {
+ const v = requireViewer();
+ const preset = String(params.preset || '').trim();
+ if (!preset || !v.setEnvironment) throw new Error('preset required');
+ v.setEnvironment(preset);
+ return {};
+ },
+
+ // ── Introspection ─────────────────────────────────────────────────────
+ 'viewer.getInfo': () => {
+ const v = requireViewer();
+ return {
+ version: '1',
+ ready: Boolean(v.content),
+ model: app._currentModelUrl || null,
+ widget: app.options?.widget || null,
+ type: app.options?.type || null,
+ };
+ },
+
+ // Optional ping for round-trip health checks.
+ ping: () => ({ pong: true, t: Date.now() }),
+ };
+}
+
+export { PROTOCOL, VERSION };
diff --git a/tests/api/avatars-upload-proxy.test.js b/tests/api/avatars-upload-proxy.test.js
index 5c7bda2cb..aa3a1a353 100644
--- a/tests/api/avatars-upload-proxy.test.js
+++ b/tests/api/avatars-upload-proxy.test.js
@@ -60,6 +60,17 @@ function makeReq({ body = Buffer.alloc(0), search = '', headers = {} } = {}) {
return stream;
}
+// Synthesize a minimum-viable binary glTF 2.0 buffer that passes the handler's
+// magic+version+length header check. Payload is opaque zero bytes after the
+// 12-byte header — we don't parse JSON/BIN chunks, just header validity.
+function makeFakeGlb(payloadSize = 128) {
+ const header = Buffer.alloc(12);
+ header.writeUInt32LE(0x46546C67, 0); // magic 'glTF'
+ header.writeUInt32LE(2, 4); // version
+ header.writeUInt32LE(12 + payloadSize, 8); // total length
+ return Buffer.concat([header, Buffer.alloc(payloadSize)]);
+}
+
function makeRes() {
return {
statusCode: 200,