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.

fix(render): report unapplied expression morphs instead of silently dropping them

nirholas2ed968386b10
diff --git a/api/_lib/avatar-render.js b/api/_lib/avatar-render.js
index 321ad852c..b98db2198 100644
--- a/api/_lib/avatar-render.js
+++ b/api/_lib/avatar-render.js
@@ -92,6 +92,32 @@ export function computeCameraFraming(box, preset, aspect, fovDeg, orbit) {
};
}
+// Applies a requested morph map to a loaded model and reports which names
+// actually landed. Shared verbatim between Node (unit tests) and the headless
+// render page (injected via toString(), so keep it self-contained: plain
+// objects only, no three.js, no outer-scope references). A model with no
+// morph targets (or differently-named ones) used to make this a silent no-op:
+// the caller got a clean 200 with none of the requested expression applied
+// and no way to tell. Returns { requested, missing } or null when nothing
+// was requested.
+export function applyExpression(root, expression) {
+ if (!expression || typeof expression !== 'object') return null;
+ const requested = Object.keys(expression);
+ if (!requested.length) return null;
+ const matched = new Set();
+ root.traverse((o) => {
+ if (!o.isMesh || !o.morphTargetDictionary || !o.morphTargetInfluences) return;
+ for (const [name, value] of Object.entries(expression)) {
+ const idx = o.morphTargetDictionary[name] ?? o.morphTargetDictionary[name.toLowerCase()];
+ if (typeof idx === 'number') {
+ o.morphTargetInfluences[idx] = Number(value) || 0;
+ matched.add(name);
+ }
+ }
+ });
+ return { requested, missing: requested.filter((n) => !matched.has(n)) };
+}
+
export const FORMAT_TYPES = {
png: 'image/png',
jpeg: 'image/jpeg',
@@ -205,7 +231,12 @@ function renderFingerprint(updatedAt, params) {
// (MCP callers that only get a URL back)
// false → fire the write in the background and hand back the
// buffer the caller already holds (the HTTP endpoint)
-// Returns { cached, key, imageUrl, buffer, contentType }. buffer is null on a hit.
+// Returns { cached, key, imageUrl, buffer, contentType, expressionReport }.
+// buffer is null on a hit. expressionReport is { requested, missing } when an
+// expression was requested on a fresh render (missing = morph names the model
+// does not carry, i.e. the part of the request that could not be honored),
+// null when no expression was requested, and undefined on a cache hit (the
+// stored image predates the check).
export async function renderAvatarImage({ avatar, glbUrl, params, awaitUpload = false }) {
const contentType = FORMAT_TYPES[params.format];
const fingerprint = renderFingerprint(avatar.updated_at, params);
@@ -221,7 +252,7 @@ export async function renderAvatarImage({ avatar, glbUrl, params, awaitUpload =
}
const cameraOrbit = { theta: params.scenePreset.theta, phi: params.scenePreset.phi, radius: null };
- const { png } = await renderAvatarScene({
+ const { png, expressionReport } = await renderAvatarScene({
glbUrl,
width: params.width,
height: params.height,
@@ -244,7 +275,7 @@ export async function renderAvatarImage({ avatar, glbUrl, params, awaitUpload =
put.catch((err) => console.warn('[avatar-render] cache write failed:', err?.message));
}
- return { cached: false, key, imageUrl: publicUrl(key), buffer: png, contentType };
+ return { cached: false, key, imageUrl: publicUrl(key), buffer: png, contentType, expressionReport };
}
const DEFAULT_CHROMIUM_PACK =
@@ -340,6 +371,7 @@ import { makeGltfRig, poseFromMannequinPreset } from 'pose-rig';
window.__renderDone = false;
window.__renderError = null;
+window.__expressionReport = null;
const canvas = document.getElementById('c');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });
@@ -389,16 +421,7 @@ function applyPose(root, poseMap) {
rig.applyPose(poseFromMannequinPreset(poseMap));
}
-function applyExpression(root, expression) {
- if (!expression || typeof expression !== 'object') return;
- root.traverse((o) => {
- if (!o.isMesh || !o.morphTargetDictionary || !o.morphTargetInfluences) return;
- for (const [name, value] of Object.entries(expression)) {
- const idx = o.morphTargetDictionary[name] ?? o.morphTargetDictionary[name.toLowerCase()];
- if (typeof idx === 'number') o.morphTargetInfluences[idx] = Number(value) || 0;
- }
- });
-}
+${applyExpression.toString()}
${computeCameraFraming.toString()}
@@ -447,7 +470,7 @@ loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
const root = gltf.scene;
scene.add(root);
applyPose(root, poseMap);
- applyExpression(root, expression);
+ window.__expressionReport = applyExpression(root, expression);
frameCameraForScene(root, orbit, preset);
renderer.render(scene, camera);
requestAnimationFrame(() => {
@@ -500,12 +523,13 @@ export async function renderAvatarScene({
if (err) {
throw Object.assign(new Error(`render failed: ${err}`), { status: 502, code: 'render_failed' });
}
+ const expressionReport = await page.evaluate(() => window.__expressionReport);
const png = await page.screenshot({
type: 'png',
omitBackground: background === 'transparent',
clip: { x: 0, y: 0, width: W, height: H },
});
- return { png };
+ return { png, expressionReport };
} finally {
await page.close().catch(() => {});
}
diff --git a/api/_mcp/tools/avatars.js b/api/_mcp/tools/avatars.js
index 97198a3c9..22a08b82d 100644
--- a/api/_mcp/tools/avatars.js
+++ b/api/_mcp/tools/avatars.js
@@ -333,17 +333,25 @@ export const toolDefs = [
};
}
+ // A requested expression the model cannot express used to vanish
+ // silently (a morph-less avatar rendered fine with none of it applied).
+ // Tell the caller which morphs did not land.
+ const missingMorphs = out.expressionReport?.missing?.length ? out.expressionReport.missing : null;
+ const morphNote = missingMorphs
+ ? `\nNote: this model has no morph target(s) named ${missingMorphs.join(', ')}; that part of the expression was not applied.`
+ : '';
return {
content: [
{
type: 'text',
- text: `Rendered "${avatar.name}" (${resolved.params.scene}).\n${out.imageUrl}`,
+ text: `Rendered "${avatar.name}" (${resolved.params.scene}).\n${out.imageUrl}${morphNote}`,
},
],
structuredContent: {
image_url: out.imageUrl,
scene: resolved.params.scene,
cached: out.cached,
+ ...(missingMorphs ? { expression_missing: missingMorphs } : {}),
},
};
},
diff --git a/api/avatar/render.js b/api/avatar/render.js
index 8229209c8..28dafb3b4 100644
--- a/api/avatar/render.js
+++ b/api/avatar/render.js
@@ -15,6 +15,12 @@
// format — png | jpeg | webp (default: png)
// quality — 1-100 for lossy formats (default: 90)
//
+// When an expression is requested, fresh (non-cached) responses carry
+// `x-render-expression: applied | partial | none`; `partial`/`none` add
+// `x-render-expression-missing` listing the morph names the model does not
+// have. A model with zero morph targets renders fine but reports `none`
+// instead of silently ignoring the expression.
+//
// Caching:
// First request per parameter combo renders via headless chromium + three.js
// and caches the result in R2. Subsequent requests 302 to the CDN URL.
@@ -154,6 +160,17 @@ export default wrap(async function handler(req, res) {
res.setHeader('x-render-cache', 'miss');
res.setHeader('x-render-scene', params.scene);
res.setHeader('x-render-size', `${params.width}x${params.height}`);
- res.setHeader('access-control-expose-headers', 'x-render-cache, x-render-scene, x-render-size');
+ // An expression request against a model that lacks the morph targets used to
+ // be indistinguishable from success. Report what actually landed so callers
+ // can tell "applied" from "the model cannot express this".
+ if (out.expressionReport) {
+ const { requested, missing } = out.expressionReport;
+ const state = missing.length === 0 ? 'applied' : missing.length === requested.length ? 'none' : 'partial';
+ res.setHeader('x-render-expression', state);
+ if (missing.length) {
+ res.setHeader('x-render-expression-missing', missing.slice(0, 32).join(','));
+ }
+ }
+ res.setHeader('access-control-expose-headers', 'x-render-cache, x-render-scene, x-render-size, x-render-expression, x-render-expression-missing');
res.end(imageBuffer);
});
diff --git a/scripts/set-r2-cors.mjs b/scripts/set-r2-cors.mjs
index 91cc03055..276149cfd 100644
--- a/scripts/set-r2-cors.mjs
+++ b/scripts/set-r2-cors.mjs
@@ -117,7 +117,13 @@ const s3 = new S3Client({
const Bucket = process.env.S3_BUCKET;
if (flag('--get')) {
- const current = await getCors();
+ let current;
+ try {
+ current = await getCors();
+ } catch (err) {
+ if (!explainAccessDenied(err, 'reading')) throw err;
+ process.exit(1);
+ }
console.log(JSON.stringify(current, null, 2));
process.exit(0);
}
diff --git a/tests/api/avatar-render-expression-report.test.js b/tests/api/avatar-render-expression-report.test.js
new file mode 100644
index 000000000..23827c516
--- /dev/null
+++ b/tests/api/avatar-render-expression-report.test.js
@@ -0,0 +1,90 @@
+// Regression lock for the silent-expression defect on /api/avatar/render
+// (ISSUES.md item 9, second defect): a model with zero morph targets, or with
+// morphs named differently from the request, rendered a clean 200 with none of
+// the requested expression applied and gave the caller no way to tell.
+// applyExpression now returns { requested, missing }, the page publishes it as
+// window.__expressionReport, and the HTTP layer maps it to
+// x-render-expression / x-render-expression-missing headers.
+
+import { describe, it, expect } from 'vitest';
+import { applyExpression, sceneViewerHtml, SCENE_PRESETS } from '../../api/_lib/avatar-render.js';
+
+// Minimal stand-in for a loaded glTF scene graph: traverse() visits every node.
+function fakeRoot(nodes) {
+ return { traverse(fn) { nodes.forEach(fn); } };
+}
+
+function morphMesh(dictionary) {
+ return {
+ isMesh: true,
+ morphTargetDictionary: dictionary,
+ morphTargetInfluences: new Array(Object.keys(dictionary).length).fill(0),
+ };
+}
+
+describe('applyExpression report', () => {
+ it('returns null when no expression is requested', () => {
+ expect(applyExpression(fakeRoot([morphMesh({ mouthSmile: 0 })]), null)).toBeNull();
+ expect(applyExpression(fakeRoot([morphMesh({ mouthSmile: 0 })]), {})).toBeNull();
+ });
+
+ it('applies matching morphs and reports zero missing', () => {
+ const mesh = morphMesh({ mouthSmile: 0, eyeBlinkLeft: 1 });
+ const report = applyExpression(fakeRoot([mesh]), { mouthSmile: 0.6 });
+ expect(mesh.morphTargetInfluences[0]).toBe(0.6);
+ expect(report).toEqual({ requested: ['mouthSmile'], missing: [] });
+ });
+
+ it('reports every requested name missing on a morph-less model', () => {
+ // The live defect: avatar 13f259c7-… has no morph targets at all.
+ const bareMesh = { isMesh: true };
+ const report = applyExpression(fakeRoot([bareMesh]), { mouthSmile: 0.6, jawOpen: 0.3 });
+ expect(report).toEqual({ requested: ['mouthSmile', 'jawOpen'], missing: ['mouthSmile', 'jawOpen'] });
+ });
+
+ it('reports a partial match when only some morphs exist', () => {
+ const mesh = morphMesh({ mouthSmile: 0 });
+ const report = applyExpression(fakeRoot([mesh]), { mouthSmile: 1, browInnerUp: 0.4 });
+ expect(mesh.morphTargetInfluences[0]).toBe(1);
+ expect(report.missing).toEqual(['browInnerUp']);
+ });
+
+ it('matches case-insensitively via the lowercase fallback', () => {
+ const mesh = morphMesh({ mouthsmile: 0 });
+ const report = applyExpression(fakeRoot([mesh]), { mouthSmile: 0.5 });
+ expect(mesh.morphTargetInfluences[0]).toBe(0.5);
+ expect(report.missing).toEqual([]);
+ });
+
+ it('a name matched on ANY mesh counts as applied', () => {
+ const bare = { isMesh: true };
+ const face = morphMesh({ jawOpen: 0 });
+ const report = applyExpression(fakeRoot([bare, face]), { jawOpen: 0.2 });
+ expect(report.missing).toEqual([]);
+ });
+});
+
+describe('render page wiring', () => {
+ it('injects applyExpression verbatim and publishes __expressionReport', () => {
+ const html = sceneViewerHtml({
+ glbUrl: 'https://cdn.three.ws/a.glb',
+ width: 64,
+ height: 64,
+ background: 'transparent',
+ pose: null,
+ cameraOrbit: null,
+ expression: { mouthSmile: 0.6 },
+ scenePreset: SCENE_PRESETS.portrait,
+ });
+ expect(html).toContain('function applyExpression');
+ expect(html).toContain('window.__expressionReport = null');
+ expect(html).toContain('window.__expressionReport = applyExpression(root, expression)');
+ });
+
+ it('keeps the injected function self-contained (no outer-scope references)', () => {
+ // The page evals this source standalone; a captured import or module
+ // variable would throw only at render time in headless chromium.
+ const src = applyExpression.toString();
+ expect(src).not.toMatch(/\brequire\b|\bimport\b|\bTHREE\b/);
+ });
+});