Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(Avatar): implement live animation for avatar during response generation
nirholasc7ba31ab8f1b
diff --git a/chat/src/App.svelte b/chat/src/App.svelteindex 1f2699efa..58231e3d2 100644--- a/chat/src/App.svelte+++ b/chat/src/App.svelte@@ -22,7 +22,7 @@} from './providers.js';import ModelSelector from './ModelSelector.svelte';import CompanyLogo from './CompanyLogo.svelte';- import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, localAgentId, activeAgent, talkingHeadEnabled, talkingHeadAvatarUrl, route, mode, websiteCategory, loadCurrentUser, notify, localProvidersEnabled } from './stores.js';+ import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, localAgentId, activeAgent, talkingHeadEnabled, talkingHeadAvatarUrl, route, mode, websiteCategory, loadCurrentUser, notify, localProvidersEnabled, generating as generatingStore } from './stores.js';import { t } from './i18n.js';import Notifications from './Notifications.svelte';import AuthPage from './manus/pages/AuthPage.svelte';@@ -443,6 +443,7 @@: null;let generating = false;+ $: $generatingStore = generating;let editingTitleId = null;let historyOpen = false;diff --git a/chat/src/AvatarIcon.svelte b/chat/src/AvatarIcon.svelteindex aae841079..1dd7d6c4d 100644--- a/chat/src/AvatarIcon.svelte+++ b/chat/src/AvatarIcon.svelte@@ -1,11 +1,4 @@<script context="module">- // Shared across all instances — render each avatar URL once per session- const cache = new Map();- const inflight = new Map();-</script>--<script>- import { onMount } from 'svelte';import {Scene,PerspectiveCamera,@@ -16,113 +9,203 @@Vector3,SRGBColorSpace,ACESFilmicToneMapping,+ AnimationMixer,+ AnimationClip,+ LoopRepeat,+ Clock,} from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+ import { SkeletonUtils } from 'three/addons/utils/SkeletonUtils.js';++ const gltfCache = new Map(); // url -> Promise<gltf>+ let walkClipPromise = null;+ let idleClipPromise = null;++ function loadGLTF(url) {+ if (!gltfCache.has(url)) {+ const p = fetch(url, { mode: 'cors' })+ .then((r) => {+ if (!r.ok) throw new Error(r.status);+ return r.arrayBuffer();+ })+ .then(+ (buf) =>+ new Promise((resolve, reject) =>+ new GLTFLoader().parse(buf, '', resolve, reject),+ ),+ );+ gltfCache.set(url, p);+ }+ return gltfCache.get(url);+ }- export let avatarUrl = '';+ async function loadClip(url) {+ const r = await fetch(url);+ if (!r.ok) throw new Error(r.status);+ const json = await r.json();+ const clip = AnimationClip.parse(json);+ // Strip root translation so the avatar walks in place (camera stays framed).+ clip.tracks = clip.tracks.filter((t) => !/Hips\.position/i.test(t.name));+ return clip;+ }- let dataUrl = cache.get(avatarUrl) ?? null;- let state = dataUrl ? 'done' : avatarUrl ? 'loading' : 'error';+ function getWalkClip() {+ if (!walkClipPromise) walkClipPromise = loadClip('/animations/clips/walk.json');+ return walkClipPromise;+ }+ function getIdleClip() {+ if (!idleClipPromise) idleClipPromise = loadClip('/animations/clips/idle.json');+ return idleClipPromise;+ }+</script>- onMount(() => {- if (state !== 'loading') return;- renderAvatar();- });+<script>+ import { onMount, onDestroy } from 'svelte';+ import { generating } from './stores.js';- async function renderAvatar() {- if (cache.has(avatarUrl)) {- dataUrl = cache.get(avatarUrl);- state = 'done';- return;- }+ export let avatarUrl = '';+ /** When true (default), avatar plays walking while $generating, idle otherwise.+ * When false, renders a single still frame (cheap for dense lists). */+ export let live = true;++ let canvas;+ let state = avatarUrl ? 'loading' : 'error';+ let mixer = null;+ let walkAction = null;+ let idleAction = null;+ let renderer = null;+ let scene = null;+ let camera = null;+ let clock = null;+ let rafId = 0;+ let visible = false;+ let observer;+ let docVisible = typeof document === 'undefined' || !document.hidden;++ function onDocVis() {+ docVisible = !document.hidden;+ tickPlayState();+ }- // Deduplicate concurrent renders of the same URL- if (inflight.has(avatarUrl)) {- try {- dataUrl = await inflight.get(avatarUrl);- state = 'done';- } catch {- state = 'error';+ onMount(async () => {+ if (!avatarUrl) return;+ try {+ const gltf = await loadGLTF(avatarUrl);+ const root = SkeletonUtils.clone(gltf.scene);+ scene = new Scene();+ scene.add(root);+ scene.add(new HemisphereLight(0xffffff, 0x444444, 2.0));+ const dir = new DirectionalLight(0xffffff, 2.5);+ dir.position.set(3, 10, 7);+ scene.add(dir);++ const box = new Box3().setFromObject(root);+ const center = box.getCenter(new Vector3());+ const sz = box.getSize(new Vector3());+ const faceY = center.y + sz.y * 0.32;+ const faceHeight = sz.y * 0.32;+ const fov = 24;+ const dist = faceHeight / (2 * Math.tan(((Math.PI / 180) * fov) / 2));+ camera = new PerspectiveCamera(fov, 1, 0.01, 1000);+ camera.position.set(center.x, faceY, center.z + dist * 1.25);+ camera.lookAt(center.x, faceY, center.z);++ renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.setSize(128, 128, false);+ renderer.outputColorSpace = SRGBColorSpace;+ renderer.toneMapping = ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.0;++ if (live) {+ clock = new Clock();+ mixer = new AnimationMixer(root);+ const [walkClip, idleClip] = await Promise.all([getWalkClip(), getIdleClip()]).catch(+ () => [null, null],+ );+ if (walkClip) {+ walkAction = mixer.clipAction(walkClip);+ walkAction.setLoop(LoopRepeat).play();+ walkAction.weight = 0;+ }+ if (idleClip) {+ idleAction = mixer.clipAction(idleClip);+ idleAction.setLoop(LoopRepeat).play();+ idleAction.weight = 1;+ }++ observer = new IntersectionObserver(+ (entries) => {+ visible = entries[0].isIntersecting;+ tickPlayState();+ },+ { rootMargin: '50px' },+ );+ observer.observe(canvas);+ document.addEventListener('visibilitychange', onDocVis);}- return;- }-- const promise = doRender(avatarUrl);- inflight.set(avatarUrl, promise);- try {- dataUrl = await promise;+ renderer.render(scene, camera);state = 'done';} catch {state = 'error';- } finally {- inflight.delete(avatarUrl);}+ });++ function tickPlayState() {+ const shouldRun = live && visible && docVisible;+ if (shouldRun && !rafId) loop();+ if (!shouldRun && rafId) {+ cancelAnimationFrame(rafId);+ rafId = 0;+ }+ }++ function loop() {+ rafId = requestAnimationFrame(loop);+ const dt = clock?.getDelta() || 0;+ if (mixer) {+ // Crossfade between idle and walk based on $generating+ const targetWalk = $generating ? 1 : 0;+ if (walkAction) walkAction.weight += (targetWalk - walkAction.weight) * Math.min(1, dt * 6);+ if (idleAction)+ idleAction.weight += (1 - targetWalk - idleAction.weight) * Math.min(1, dt * 6);+ mixer.update(dt);+ }+ renderer?.render(scene, camera);}- async function doRender(url) {- const resp = await fetch(url, { mode: 'cors' });- if (!resp.ok) throw new Error(resp.status);- const buffer = await resp.arrayBuffer();-- const loader = new GLTFLoader();- const gltf = await new Promise((resolve, reject) =>- loader.parse(buffer, '', resolve, reject),- );-- const scene = new Scene();- scene.add(gltf.scene);-- const box = new Box3().setFromObject(gltf.scene);- const center = box.getCenter(new Vector3());- const boxSize = box.getSize(new Vector3());-- // Frame the face — upper ~35% of the avatar's bounding box- const faceY = center.y + boxSize.y * 0.32;- const faceHeight = boxSize.y * 0.28;- const fov = 22;- const dist = faceHeight / (2 * Math.tan(((Math.PI / 180) * fov) / 2));-- const camera = new PerspectiveCamera(fov, 1, 0.01, 1000);- camera.position.set(center.x, faceY, center.z + dist * 1.2);- camera.lookAt(center.x, faceY, center.z);-- scene.add(new HemisphereLight(0xffffff, 0x444444, 2.0));- const dir = new DirectionalLight(0xffffff, 2.5);- dir.position.set(3, 10, 7);- scene.add(dir);-- const offscreen = document.createElement('canvas');- offscreen.width = 128;- offscreen.height = 128;- const renderer = new WebGLRenderer({ canvas: offscreen, antialias: true, alpha: true });- renderer.setPixelRatio(1);- renderer.setSize(128, 128, false);- renderer.outputColorSpace = SRGBColorSpace;- renderer.toneMapping = ACESFilmicToneMapping;- renderer.toneMappingExposure = 1.0;- renderer.render(scene, camera);-- const result = offscreen.toDataURL('image/png');- cache.set(url, result);-- renderer.dispose();- scene.traverse((obj) => {+ $: if (live && mixer) tickPlayState();++ onDestroy(() => {+ observer?.disconnect();+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onDocVis);+ if (rafId) cancelAnimationFrame(rafId);+ renderer?.dispose();+ scene?.traverse((obj) => {obj.geometry?.dispose();- const mats = Array.isArray(obj.material)- ? obj.material- : obj.material- ? [obj.material]- : [];+ const mats = Array.isArray(obj.material) ? obj.material : obj.material ? [obj.material] : [];for (const m of mats) m.dispose();});-- return result;- }+ });</script>-{#if state === 'done' && dataUrl}- <img src={dataUrl} alt="" class="h-full w-full object-cover" />-{:else if state === 'loading'}- <div class="h-full w-full animate-pulse bg-teal-100" />-{/if}+<canvas+ bind:this={canvas}+ width="128"+ height="128"+ class="h-full w-full object-cover {state !== 'done' ? 'animate-pulse bg-teal-100' : ''} {$generating && live ? 'avatar-bob' : ''}"+/>++<style>+ @keyframes avatar-bob {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-2px); }+ }+ .avatar-bob {+ animation: avatar-bob 0.7s ease-in-out infinite;+ }+ @media (prefers-reduced-motion: reduce) {+ .avatar-bob { animation: none; }+ }+</style>diff --git a/chat/src/CompanyLogo.svelte b/chat/src/CompanyLogo.svelteindex aa2e7688d..af70ab166 100644--- a/chat/src/CompanyLogo.svelte+++ b/chat/src/CompanyLogo.svelte@@ -3,8 +3,10 @@import AvatarIcon from './AvatarIcon.svelte';export let model;- export let size = 'h-3.5 w-3.5';+ export let size = 'h-7 w-7';export let rounded = null;+ /** Live-animated walking avatar. Set false for dense lists (dropdown rows) — uses still frame. */+ export let live = true;// Remember to update hasCompanyLogo from convo.js when adding new logos.const base = import.meta.env.BASE_URL;@@ -12,7 +14,7 @@{#if $talkingHeadAvatarUrl}<span class="{size} {rounded || 'rounded-sm'} overflow-hidden inline-block shrink-0">- <AvatarIcon avatarUrl={$talkingHeadAvatarUrl} />+ <AvatarIcon avatarUrl={$talkingHeadAvatarUrl} {live} /></span>{:else if model && model.provider}{#if model.provider === 'OpenAI' || model.id.startsWith('openai')}diff --git a/chat/src/ModelSelector.svelte b/chat/src/ModelSelector.svelteindex edee02f8a..0c2003e6f 100644--- a/chat/src/ModelSelector.svelte+++ b/chat/src/ModelSelector.svelte@@ -118,7 +118,7 @@query = '';}}>- <CompanyLogo {model} size="w-7 h-7" rounded="rounded" />+ <CompanyLogo {model} size="w-7 h-7" rounded="rounded" live={false} /><span class="line-clamp-1">{formatModelName(model)}</span>{#if model.modality === 'text->image'}<Icon icon={feImage} class="mt-px h-3 w-3 text-slate-800" />diff --git a/chat/src/stores.js b/chat/src/stores.jsindex a88ac46d4..4456e503c 100644--- a/chat/src/stores.js+++ b/chat/src/stores.js@@ -70,6 +70,10 @@ export const pluginLibraryUrl = persisted('pluginLibraryUrl', 'https://ai-agent-export const talkingHeadEnabled = persisted('talkingHeadEnabled', false);export const talkingHeadAvatarUrl = persisted('talkingHeadAvatarUrl', '');+// True while the assistant is generating a response — drives the chat avatar+// walk animation so the agent visibly "moves with the chat".+export const generating = writable(false);+export const route = writable(typeof window !== 'undefined' ? (window.location.hash.slice(1) || 'chat') : 'chat');diff --git a/create.html b/create.htmlindex ae936407e..a57131a7b 100644--- a/create.html+++ b/create.html@@ -582,9 +582,15 @@if (!data || !data.user) {sessionStorage.setItem('login_redirect', '/create');location.replace('/login');+ } else {+ var el = document.getElementById('page-loading');+ if (el) el.remove();}})- .catch(function () {});+ .catch(function () {+ var el = document.getElementById('page-loading');+ if (el) el.remove();+ });</script></head><body>