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
fix(chat): give voice output one working speaker and a voice you can pick
nirholas343d415be78f
diff --git a/chat/src/App.svelte b/chat/src/App.svelteindex ea9652b9e..3376c2922 100644--- a/chat/src/App.svelte+++ b/chat/src/App.svelte@@ -23,7 +23,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, currentUser, notify, localProvidersEnabled, generating as generatingStore } from './stores.js';+ import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, ttsVoiceURI, localAgentId, activeAgent, talkingHeadAvatarUrl, route, mode, websiteCategory, loadCurrentUser, currentUser, notify, localProvidersEnabled, generating as generatingStore } from './stores.js';import { t } from './i18n.js';import Notifications from './Notifications.svelte';import TxApprovalModal from './TxApprovalModal.svelte';@@ -76,7 +76,6 @@import { deleteSingleItem, initEncryption, sendSingleItem, syncPull, syncPush } from './sync.js';import AgentPicker from './AgentPicker.svelte';import AgentSettingsModal from './AgentSettingsModal.svelte';- import TalkingHead from './TalkingHead.svelte';import EmptyState from './three-ui/EmptyState.svelte';import SuggestionChips from './three-ui/SuggestionChips.svelte';import TopNav from './three-ui/TopNav.svelte';@@ -510,7 +509,6 @@convo.messages[i].thinking = false;stopThinkingTimer(i);}- talkingHead?.think(false);}// Built-in scene/avatar tools. These are declared server-side in api/chat.js@@ -925,6 +923,10 @@submitCompletion();} else {generateTitle();+ // The turn is finished: animate the avatar and read the reply+ // aloud. A tool-call turn keeps streaming, so it speaks on the+ // follow-up completion that actually ends the turn.+ speakLastMessage();}return;@@ -1823,9 +1825,6 @@// Floating 3D agentlet agentEl;- let talkingHead;- let talkingHeadReady = false;- let pendingSpeak = null;let agentReady = false;let agentPendingSpeak = null;let agentVisible = true;@@ -2120,9 +2119,16 @@$: if ($mode !== 'website') websiteCategory.set(null);+ // Providers differ on how a stream ends: some send a single chunk carrying+ // finish_reason, others repeat it on a trailing usage chunk. Speaking is+ // keyed to the message so a repeated end-of-stream can't read a reply twice.+ let lastSpokenMessageId = null;+function speakLastMessage() {const last = [...convo.messages].reverse().find((m) => m.role === 'assistant' && m.content);if (!last?.content) return;+ if (last.id === lastSpokenMessageId) return;+ lastSpokenMessageId = last.id;if (agentEl && effectiveAgentId) {if (agentReady) {@@ -2132,36 +2138,21 @@} else {agentPendingSpeak = last.content;}- } else if ($talkingHeadEnabled && agentVisible) {- if (talkingHeadReady) {- const mood = detectEmotion(last.content);- if (mood) talkingHead.setMood(mood);- talkingHead.speak({ text: last.content, mood: mood || 'neutral' });- } else {- pendingSpeak = last.content;- }}- if ($ttsEnabled && window.speechSynthesis && !$talkingHeadEnabled) {+ // agentEl.speak() only drives the mouth/gesture animation, it carries no+ // audio, so the browser voice is the single speaker for every reply.+ if ($ttsEnabled && window.speechSynthesis) {window.speechSynthesis.cancel();const utt = new SpeechSynthesisUtterance(last.content);+ const picked = $ttsVoiceURI+ ? window.speechSynthesis.getVoices().find((v) => v.voiceURI === $ttsVoiceURI)+ : null;+ if (picked) utt.voice = picked;window.speechSynthesis.speak(utt);}}- $: if ($talkingHeadAvatarUrl) {- talkingHeadReady = false;- pendingSpeak = null;- }-- function onTalkingHeadReady() {- talkingHeadReady = true;- if (pendingSpeak) {- talkingHead.speak({ text: pendingSpeak });- pendingSpeak = null;- }- }-async function generateTitle() {if (convo.title) return;const msgs = convo.messages.filter((m) => m.role === 'user' || m.role === 'assistant');@@ -2742,7 +2733,7 @@</div><div class="pointer-events-none absolute bottom-[72px] inset-x-0 h-8 z-[98] bg-gradient-to-t from-paper to-transparent" />- {#if $toolSchema.length > 0 || (effectiveAgentId || $talkingHeadEnabled)}+ {#if $toolSchema.length > 0 || effectiveAgentId}<div class="flex flex-wrap gap-1.5 px-4 pt-2 pb-0">{#each $toolSchema as group}<span class="inline-flex items-center gap-1 rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-0.5 text-[11px] font-medium text-indigo-700">@@ -2762,7 +2753,7 @@>+ Add skill</button>- {#if effectiveAgentId || $talkingHeadEnabled}+ {#if effectiveAgentId}<buttonclass="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 hover:bg-emerald-100"on:click={agentVisible ? killAvatar : reviveAvatar}diff --git a/chat/src/SettingsModal.svelte b/chat/src/SettingsModal.svelteindex 8fca65665..2ce6bcdcf 100644--- a/chat/src/SettingsModal.svelte+++ b/chat/src/SettingsModal.svelte@@ -1,5 +1,5 @@<script>- import { createEventDispatcher, tick } from 'svelte';+ import { createEventDispatcher, onDestroy, tick } from 'svelte';import { v4 as uuidv4 } from 'uuid';import {anthropicAPIKey,@@ -14,6 +14,8 @@syncServer,toolSchema,talkingHeadAvatarUrl,+ ttsEnabled,+ ttsVoiceURI,locale,localProvidersEnabled,currentUser,@@ -144,6 +146,30 @@talkingHeadAvatarUrl.set('');}+ // Browser speech synthesis. Chrome populates getVoices() asynchronously, so+ // the list starts empty and fills in on the voiceschanged event.+ const speech = typeof window !== 'undefined' ? window.speechSynthesis : null;+ let voices = [];++ function loadVoices() {+ voices = speech ? speech.getVoices() : [];+ }++ if (speech) {+ loadVoices();+ speech.addEventListener('voiceschanged', loadVoices);+ onDestroy(() => speech.removeEventListener('voiceschanged', loadVoices));+ }++ function previewVoice() {+ if (!speech) return;+ speech.cancel();+ const utt = new SpeechSynthesisUtterance('This is how replies will sound.');+ const picked = voices.find((v) => v.voiceURI === $ttsVoiceURI);+ if (picked) utt.voice = picked;+ speech.speak(utt);+ }+let addClientToolOpen = false;let loadClientTool = null;@@ -687,6 +713,50 @@</div>{:else if activeTab === 'avatar'}<div class="flex flex-col gap-4">+ <div class="flex flex-col gap-2 rounded-lg border border-slate-200 p-3">+ <label class="flex items-start gap-2 text-[13px] text-slate-700">+ <input type="checkbox" bind:checked={$ttsEnabled} class="mt-0.5" disabled={!speech} />+ <span class="flex flex-col">+ <span>Speak replies aloud</span>+ <span class="text-[11px] text-slate-500">+ {#if speech}+ Your browser reads each finished reply out loud. The avatar mouths along+ with it.+ {:else}+ This browser has no speech synthesis, so replies stay text-only.+ {/if}+ </span>+ </span>+ </label>++ {#if speech && $ttsEnabled}+ <div class="flex items-end gap-2 pl-6">+ <label class="flex flex-1 flex-col text-[11px] text-slate-500">+ <span class="mb-1">Voice</span>+ <select+ bind:value={$ttsVoiceURI}+ class="rounded-md border border-slate-200 px-2 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400"+ >+ <option value="">Browser default</option>+ {#each voices as v (v.voiceURI)}+ <option value={v.voiceURI}>{v.name} ({v.lang})</option>+ {/each}+ </select>+ </label>+ <button+ type="button"+ on:click={previewVoice}+ class="rounded-md border border-slate-200 px-3 py-1.5 text-[12px] font-medium text-slate-700 transition-colors hover:border-indigo-300 hover:bg-indigo-50 focus:outline-none focus:ring-2 focus:ring-indigo-300"+ >Preview</button>+ </div>+ {#if voices.length === 0}+ <p class="pl-6 text-[11px] text-slate-400">+ No installed voices reported yet. The browser default still speaks.+ </p>+ {/if}+ {/if}+ </div>+{#if avatarsLoading}<p class="text-xs text-slate-400">Loading avatars…</p>{/if}@@ -747,7 +817,7 @@<div class="flex flex-col gap-1"><div class="flex items-center justify-between">- <label class="text-sm font-medium text-slate-700">Custom 3D Avatar URL (.glb)</label>+ <label for="avatar-url" class="text-sm font-medium text-slate-700">Custom 3D Avatar URL (.glb)</label>{#if $talkingHeadAvatarUrl}<buttontype="button"@@ -757,6 +827,7 @@{/if}</div><input+ id="avatar-url"type="url"placeholder="https://three.ws/api/avatars/<id> or any .glb URL"bind:value={$talkingHeadAvatarUrl}diff --git a/chat/src/TalkingHead.svelte b/chat/src/TalkingHead.sveltedeleted file mode 100644index 24dc623a5..000000000--- a/chat/src/TalkingHead.svelte+++ /dev/null@@ -1,174 +0,0 @@-<!--- TalkingHead.svelte — embed met4citizen/TalkingHead in the chat sidebar.-- Usage:- <TalkingHead bind:this={head} avatarUrl={...} ttsEndpoint={...} />- head.speak({ text: 'hi', mood: 'neutral' });-- TalkingHead is loaded from a CDN as ES modules, mirroring the upstream- README. Avoids vendoring three.js + RPM loaders — they already use- importmaps. We bridge the chat reply pipeline → head.speakText() so a new- assistant message produces lipsynced speech.-- Repo: https://github.com/met4citizen/TalkingHead (MIT)--->-<script>- import { onMount, onDestroy, createEventDispatcher } from 'svelte';-- export let avatarUrl = '';- export let avatarBody = 'F';- export let ttsEndpoint = '/api/tts/google';- export let ttsApikey = '';- export let lipsyncModules = ['en'];-- const CDN_URL =- 'https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs';-- const dispatch = createEventDispatcher();-- let container;- let head = null;- let loadError = null;-- function importWithTimeout(url, ms) {- return Promise.race([- import(/* @vite-ignore */ url),- new Promise((_, reject) =>- setTimeout(() => reject(new Error('CDN load timed out')), ms)- ),- ]);- }-- const FALLBACK_AVATAR_URL = '/avatars/default.glb';-- async function loadAvatar() {- loadError = null;- if (head?.stop) head.stop();- head = null;-- try {- const url = avatarUrl || FALLBACK_AVATAR_URL;-- let mod;- try {- mod = await importWithTimeout(CDN_URL, 15000);- } catch {- await new Promise((r) => setTimeout(r, 2000));- mod = await importWithTimeout(CDN_URL, 15000);- }-- const { TalkingHead } = mod;- head = new TalkingHead(container, {- ttsEndpoint,- ttsApikey,- lipsyncModules,- cameraView: 'idle',- });-- await Promise.race([- head.showAvatar({- url,- body: avatarBody,- avatarMood: 'neutral',- lipsyncLang: 'en',- }),- new Promise((_, reject) =>- setTimeout(() => reject(new Error('Avatar model load timed out')), 20000)- ),- ]);-- dispatch('ready');- } catch (err) {- loadError = err?.message || String(err);- console.warn('[TalkingHead] failed to load', err);- }- }-- export function retry() {- loadAvatar();- }-- onMount(() => {- loadAvatar();- });-- onDestroy(() => {- if (head?.stop) head.stop();- head = null;- });-- export function speak({ text, mood = 'neutral', lang = 'en' }) {- if (!head) return Promise.resolve();- return head.speakText(text, { avatarMood: mood, lipsyncLang: lang });- }-- export function setMood(mood) {- head?.setMood?.(mood);- }-- export function playGesture(name, duration = 3) {- if (name === 'walk') {- head?.playAnimation?.('walk');- } else {- head?.playGesture?.(name, duration);- }- }-- export function think(isThinking) {- if (isThinking) {- head?.playAnimation?.('thinking');- } else {- head?.setMood?.('neutral');- }- }-</script>--<div class="talking-head" bind:this={container}>- {#if loadError}- <div class="error">- <p>Avatar failed to load</p>- <p class="detail">{loadError}</p>- <button on:click={retry}>Retry</button>- </div>- {/if}-</div>--<style>- .talking-head {- position: relative;- width: 100%;- aspect-ratio: 3 / 4;- background: #000;- border-radius: 12px;- overflow: hidden;- }- .error {- position: absolute;- inset: 0;- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- gap: 8px;- padding: 16px;- }- .error p {- color: #f88;- font-size: 12px;- text-align: center;- margin: 0;- }- .error .detail {- color: #aaa;- font-size: 11px;- }- .error button {- background: #333;- color: #fff;- border: none;- border-radius: 6px;- padding: 4px 12px;- font-size: 12px;- cursor: pointer;- }-</style>diff --git a/chat/src/stores.js b/chat/src/stores.jsindex abef73557..d2ba320ac 100644--- a/chat/src/stores.js+++ b/chat/src/stores.js@@ -69,11 +69,15 @@ export const toolSchema = persisted('toolSchemaGroups', []);export const knowledgeSkills = persisted('knowledgeSkills', []);export const ttsEnabled = persisted('ttsEnabled', false);+// voiceURI of the browser SpeechSynthesisVoice to read replies with. Empty+// means "whatever the browser picks for the page language".+export const ttsVoiceURI = persisted('ttsVoiceURI', '');export const localAgentId = persisted('localAgentId', '');export const activeAgent = persisted('activeAgentDetail', null);export const agentLibraryUrl = persisted('agentLibraryUrl', 'https://agents-ai-library.vercel.app');export const pluginLibraryUrl = persisted('pluginLibraryUrl', 'https://ai-agent-plugins.vercel.app');-export const talkingHeadEnabled = persisted('talkingHeadEnabled', false);+// The avatar GLB the chat shows for the assistant: the <agent-3d> viewer in a+// reply, the sidebar logo, and the Settings avatar picker all read this one.export const talkingHeadAvatarUrl = persisted('talkingHeadAvatarUrl', '');// True while the assistant is generating a response — drives the chat avatardiff --git a/docs/ux-flows/10-chat-brain-labs.md b/docs/ux-flows/10-chat-brain-labs.mdindex d4ead3759..cc879ef7f 100644--- a/docs/ux-flows/10-chat-brain-labs.md+++ b/docs/ux-flows/10-chat-brain-labs.md@@ -7,7 +7,7 @@ modules. Routes resolved via `vercel.json` rewrites.---### Conversational AI Chat (3D talking agent) — `/chat`-- **Source:** `/workspaces/three.ws/chat/` (a standalone Svelte app, separate Vite build). Entry `/workspaces/three.ws/chat/index.html` → `/workspaces/three.ws/chat/src/main.js` → `/workspaces/three.ws/chat/src/App.svelte`. Key modules: `chat/src/providers.js` (LLM providers), `chat/src/convo.js` (streaming completion pipeline), `chat/src/TalkingHead.svelte` (3D avatar + TTS lip-sync), `chat/src/AgentPicker.svelte`, `chat/src/ModelSelector.svelte`, `chat/src/stores.js`, `chat/src/walletAuth.js` (SIWE/SIWS), `chat/src/tools.js`, `chat/src/sync.js`, `chat/src/SkillsMarketplaceModal.svelte`, `chat/src/TxApprovalModal.svelte`.+- **Source:** `/workspaces/three.ws/chat/` (a standalone Svelte app, separate Vite build). Entry `/workspaces/three.ws/chat/index.html` → `/workspaces/three.ws/chat/src/main.js` → `/workspaces/three.ws/chat/src/App.svelte`. Key modules: `chat/src/providers.js` (LLM providers), `chat/src/convo.js` (streaming completion pipeline), `chat/src/AgentPicker.svelte`, `chat/src/ModelSelector.svelte`, `chat/src/stores.js`, `chat/src/walletAuth.js` (SIWE/SIWS), `chat/src/tools.js`, `chat/src/sync.js`, `chat/src/SkillsMarketplaceModal.svelte`, `chat/src/TxApprovalModal.svelte`.- **Entry point:** `/chat` → `chat/index.html` (`<div id="app">` mounted by `main.js`).- **Prerequisites / gates:** None to start chatting: free built-in models stream through the server proxy with no key. Optional gates: user-supplied API key (Anthropic/OpenAI/Groq/Mistral/Ollama/OpenRouter) stored locally for non-built-in models; wallet sign-in (SIWE/SIWS via `/api/auth/*`) only for cross-device sync + on-chain tool calls; `TxApprovalModal` requires a connected wallet for wallet/pump tool transactions. No $THREE gate. Voice output is opt-in (off by default).- **Steps (6):**@@ -16,13 +16,13 @@ modules. Routes resolved via `vercel.json` rewrites.3. (optional) Toggle voice output in settings.4. Type a message in the composer and submit (or attach an image / file for multimodal).5. `convo.complete()` POSTs to the provider's completion URL (built-in → `/api/chat/proxy`; Anthropic → `/v1/messages`; others → `/v1/chat/completions`) and streams tokens back into the assistant bubble (markdown + KaTeX rendered live).- 6. On reply completion with voice enabled: if an agent is loaded, its `<agent-3d>` avatar speaks the reply (`agentEl.speak(...)`) and expresses the classified emotion (`agentEl.expressEmotion(...)`); with no agent loaded, browser `speechSynthesis` reads it. Payoff: a 3D agent that answers in voice with mood animation. (A legacy `TalkingHead.svelte` component is still imported but never mounted; see the note below.)+ 6. On reply completion: if an agent is loaded, its `<agent-3d>` avatar plays the talk animation (`agentEl.speak(...)`) and expresses the classified emotion (`agentEl.expressEmotion(...)`); those two calls are animation only and carry no audio. With voice output enabled, browser `speechSynthesis` reads the reply aloud, agent or not. Payoff: a 3D agent that answers in voice with mood animation.- **Decision points / branches:** model/provider choice (free built-in vs keyed provider vs OpenRouter "all models" vs local Ollama); text vs voice output (agent-3d speech vs browser speechSynthesis vs silent); persona/agent loaded vs raw model; tool-calling on/off (16 curated tool packs in `tools.js` `curatedToolPacks`, surfaced via `ToolPackModal`: wallet-transactions, x402-pay, tradingview, price-chart-3d, token-price, token-ticker-3d, web-search, date-time, pump-launch, tx-explain, mint-scene-nft, nft-3d-import, forge-text-to-3d, forge-avatar, wallet-balances, token-gate-scene; the built-in wallet/agent/pump/payments tool schemas back them); every generated 3D model card carries "View in AR ↗" (`/ar?src=<glb>`), "Download GLB", and "Viewer ↗" actions; regenerate / edit / branch a message; share conversation (compressed link via `share.js`).- **External calls / dependencies:** `/api/chat/models` (free model list, OpenRouter-proxied), `/api/chat/proxy` (built-in completions), `/api/chat/config`, `/api/mcp` + `/api/pump-fun-mcp` (skills marketplace / pump tools), `/api/agents` + `/api/marketplace/agents` (agent picker), `/api/auth/{me,logout,siwe/nonce,siwe/verify,siws/nonce,siws/verify}` (wallet auth), agent-library `index.en-US.json`. Direct provider APIs (api.anthropic.com, api.openai.com, api.groq.com, api.mistral.ai, openrouter.ai, local Ollama) when a user key is set.- **Success state:** Streamed assistant message rendered; if voice is enabled and an agent is loaded, the 3D avatar speaks with mood animation; conversation persisted to IndexedDB / optional E2E-encrypted sync.- **Empty / error states:** Empty state with brand tagline + suggestion chips when no messages. Provider/network errors surface as inline notices; abortable generation via `controller`. Missing API key → model marked unavailable in selector. Avatar GLB load failure falls back to default avatar; speech failure degrades silently to text.- **Step count:** 6 required (+4 optional)-- **Known issue (verified 2026-08-05):** the standalone 3D Talking Head is dead code. `TalkingHead.svelte` is imported in `App.svelte` but never rendered, so its bind never fires; with the settings "Talking Head" toggle on, replies queue in `pendingSpeak` and are never spoken (and `speechSynthesis` is suppressed while the toggle is on). Its default TTS endpoint `/api/tts/google` also no longer exists (live TTS endpoints are `/api/tts/speak`, `/api/tts/eleven`, `/api/tts/edge`). The working voice path is the agent-3d avatar described in step 6.+- **Voice path (resolved 2026-08-06):** there is exactly one speaker, browser `speechSynthesis`, gated on the voice-output toggle. The legacy standalone Talking Head component (a CDN build of met4citizen/TalkingHead pointed at the long-retired `/api/tts/google`) was imported but never rendered, and its dead `talkingHeadEnabled` flag suppressed `speechSynthesis` for anyone whose browser still carried the flag from an older build. Component, flag, and both dead branches are removed. `talkingHeadAvatarUrl` survives on purpose: it is the live store behind the Settings avatar picker, the sidebar logo, and the in-reply `<agent-3d>` viewer.---@@ -40,7 +40,7 @@ modules. Routes resolved via `vercel.json` rewrites.- **Success state:** Agent profile with interactive 3D avatar, live token data, and working navigation to world/embed/edit.- **Empty / error states:** Avatar mount failure → flat-image fallback; enrich failure logged non-fatally; save errors surface inline in the edit flow.- **Step count:** 4 required (+2 optional)-- **Note:** This route is a profile/directory surface, **not** a chat interface. The "talk to a 3D agent" experience lives at `/chat` (Talking Head). `/agents/:id` links *out* to `/play` ("See in world"), not to an inline chat.+- **Note:** This route is a profile/directory surface, **not** a chat interface. The "talk to a 3D agent" experience lives at `/chat`. `/agents/:id` links *out* to `/play` ("See in world"), not to an inline chat.---