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.

dashboard-next/library + agents/:id/voice: voice picker + friendlier errors

nirholasc58ee9d95e91
diff --git a/api/agents/_id/voice.js b/api/agents/_id/voice.js
index b516a8a78..c9b28fa1d 100644
--- a/api/agents/_id/voice.js
+++ b/api/agents/_id/voice.js
@@ -1,12 +1,14 @@
// Voice clone management for an agent.
//
// GET /api/agents/:id/voice — current voice status
+// PUT /api/agents/:id/voice — assign a voice_id from the server's
+// ElevenLabs library (body { voice_id })
// POST /api/agents/:id/voice/clone — clone voice from uploaded audio
-// DELETE /api/agents/:id/voice — remove cloned voice
+// DELETE /api/agents/:id/voice — remove cloned voice / clear selection
import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
@@ -41,8 +43,8 @@ function readRawBody(req) {
}
export const handleVoice = wrap(async (req, res, id, action) => {
- if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+ if (cors(req, res, { methods: 'GET,PUT,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT', 'POST', 'DELETE'])) return;
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
@@ -64,6 +66,81 @@ export const handleVoice = wrap(async (req, res, id, action) => {
});
}
+ // ── PUT — assign a voice from the ElevenLabs library ────────────────────
+ //
+ // Body: { voice_id: string | null }
+ // - null/empty: equivalent to DELETE (clear selection, free clone slot)
+ // - non-null: must be a voice_id present in /v1/voices for this account
+ //
+ // If the agent currently holds a *cloned* voice and the new pick is
+ // different, the old clone is freed in ElevenLabs to recover the quota
+ // slot. voice_cloned_at is cleared (the new pick is a library voice,
+ // not a clone owned by this user).
+
+ if (req.method === 'PUT') {
+ const apiKey = env.ELEVENLABS_API_KEY;
+ if (!apiKey)
+ return error(res, 503, 'not_configured', 'voice library is not configured on this server');
+
+ let body;
+ try { body = await readJson(req); }
+ catch { return error(res, 400, 'validation_error', 'invalid JSON body'); }
+
+ const nextVoiceId = body?.voice_id == null ? null : String(body.voice_id).trim() || null;
+
+ const [current] =
+ await sql`SELECT voice_id, voice_cloned_at FROM agent_identities WHERE id = ${id}`;
+ const wasCloned = !!current?.voice_cloned_at;
+ const oldVoiceId = current?.voice_id || null;
+
+ // Validate library membership for non-null picks.
+ if (nextVoiceId) {
+ let voices;
+ try {
+ const resp = await fetch(`${ELEVEN_BASE}/voices`, {
+ headers: { 'xi-api-key': apiKey },
+ });
+ if (!resp.ok) {
+ console.error('[voice/put] elevenlabs voices fetch failed', resp.status);
+ return error(res, 502, 'upstream_error', 'voice library is unavailable');
+ }
+ const data = await resp.json();
+ voices = data?.voices || [];
+ } catch (err) {
+ console.error('[voice/put] elevenlabs fetch threw', err);
+ return error(res, 502, 'upstream_error', 'voice library is unavailable');
+ }
+ if (!voices.some((v) => v.voice_id === nextVoiceId)) {
+ return error(res, 400, 'validation_error', 'voice_id is not in the available library');
+ }
+ }
+
+ // Free the prior cloned voice on ElevenLabs (best-effort) only when
+ // we're actually replacing a clone with something else.
+ if (wasCloned && oldVoiceId && oldVoiceId !== nextVoiceId) {
+ fetch(`${ELEVEN_BASE}/voices/${encodeURIComponent(oldVoiceId)}`, {
+ method: 'DELETE',
+ headers: { 'xi-api-key': apiKey },
+ }).catch(() => {});
+ }
+
+ if (nextVoiceId) {
+ await sql`
+ UPDATE agent_identities
+ SET voice_provider = 'elevenlabs', voice_id = ${nextVoiceId}, voice_cloned_at = NULL
+ WHERE id = ${id}
+ `;
+ return json(res, 200, { voice_provider: 'elevenlabs', voice_id: nextVoiceId, voice_cloned_at: null });
+ }
+
+ await sql`
+ UPDATE agent_identities
+ SET voice_provider = 'browser', voice_id = NULL, voice_cloned_at = NULL
+ WHERE id = ${id}
+ `;
+ return json(res, 200, { voice_provider: 'browser', voice_id: null, voice_cloned_at: null });
+ }
+
// ── DELETE — remove cloned voice ─────────────────────────────────────────
if (req.method === 'DELETE') {
diff --git a/src/dashboard-next/pages/library.js b/src/dashboard-next/pages/library.js
index a2080db1c..925728978 100644
--- a/src/dashboard-next/pages/library.js
+++ b/src/dashboard-next/pages/library.js
@@ -2,7 +2,7 @@
// Hash-driven tab switcher (#tab=animations|memory|strategy|voice).
import { mountShell } from '../shell.js';
-import { requireUser, get, esc } from '../api.js';
+import { requireUser, esc } from '../api.js';
import { renderAnimations } from './library/animations.js';
import { renderMemory } from './library/memory.js';
import { renderStrategy } from './library/strategy.js';
@@ -114,12 +114,23 @@ function writeTab(tab) {
Promise.resolve()
.then(() => render(body, { me }))
.catch((err) => {
+ const raw = err?.message || String(err);
+ const status = err?.status || 0;
+ const friendly = (status === 401 || /unauthorized|sign in|bearer/i.test(raw))
+ ? 'Your session expired. Refresh the page to sign back in.'
+ : (status === 403 || /forbidden/i.test(raw))
+ ? "You don't have permission to view this."
+ : (status === 429 || /rate.?limit/i.test(raw))
+ ? 'Slow down — try again in a moment.'
+ : raw.replace(/^HTTP\s+\d+\s*/i, '') || 'Unknown error.';
body.innerHTML = `
<div class="dn-empty">
- <h3>Couldn’t load this tab</h3>
- <p>${esc(err.message || String(err))}</p>
+ <h3>Couldn't load this tab</h3>
+ <p>${esc(friendly)}</p>
+ <div style="margin-top:12px"><button class="dn-btn" type="button" id="lib-retry">Retry</button></div>
</div>
`;
+ body.querySelector('#lib-retry')?.addEventListener('click', () => activate(tab));
});
}
diff --git a/src/dashboard-next/pages/library/animations.js b/src/dashboard-next/pages/library/animations.js
index a7382f290..4b5d5b5ab 100644
--- a/src/dashboard-next/pages/library/animations.js
+++ b/src/dashboard-next/pages/library/animations.js
@@ -5,6 +5,17 @@
import { get, put, post, esc, relTime } from '../../api.js';
+function friendly(err) {
+ if (!err) return 'Something went wrong.';
+ const status = err.status || 0;
+ const msg = err.message || String(err);
+ if (status === 401 || /unauthorized|sign in|bearer/i.test(msg)) return 'Your session expired — refresh the page.';
+ if (status === 403 || /forbidden/i.test(msg)) return "You don't have permission for that.";
+ if (status === 429 || /rate.?limit/i.test(msg)) return 'Slow down — try again in a moment.';
+ if (status === 413 || /too large/i.test(msg)) return 'File is too large.';
+ return msg.replace(/^HTTP\s+\d+\s*/i, '') || 'Upload failed.';
+}
+
export async function renderAnimations(host) {
host.innerHTML = `
<div class="anim-head">
@@ -86,7 +97,7 @@ export async function renderAnimations(host) {
const res = await get('/api/agents');
agents = res?.agents || [];
} catch (err) {
- grid.innerHTML = `<div class="dn-empty"><h3>Couldn’t load agents</h3><p>${esc(err.message || 'Failed')}</p></div>`;
+ grid.innerHTML = `<div class="dn-empty"><h3>Couldn't load agents</h3><p>${esc(friendly(err))}</p></div>`;
return;
}
@@ -199,7 +210,7 @@ function openUploadDialog(host, agents, onDone) {
onDone?.();
} catch (err) {
statusEl.textContent = '';
- errorEl.textContent = err.message || 'Upload failed.';
+ errorEl.textContent = friendly(err);
}
};
diff --git a/src/dashboard-next/pages/library/memory.js b/src/dashboard-next/pages/library/memory.js
index 6f693e087..960b0495e 100644
--- a/src/dashboard-next/pages/library/memory.js
+++ b/src/dashboard-next/pages/library/memory.js
@@ -4,6 +4,16 @@
import { get, post, esc, relTime } from '../../api.js';
+function friendly(err) {
+ if (!err) return 'Something went wrong.';
+ const status = err.status || 0;
+ const msg = err.message || String(err);
+ if (status === 401 || /unauthorized|sign in|bearer/i.test(msg)) return 'Your session expired — refresh the page.';
+ if (status === 403 || /forbidden/i.test(msg)) return "You don't have permission for that.";
+ if (status === 429 || /rate.?limit/i.test(msg)) return 'Slow down — try again in a moment.';
+ return msg.replace(/^HTTP\s+\d+\s*/i, '') || 'Unknown error.';
+}
+
export async function renderMemory(host) {
host.innerHTML = `
<div class="mem-head">
@@ -76,7 +86,7 @@ export async function renderMemory(host) {
const res = await get('/api/agents');
agents = res?.agents || [];
} catch (err) {
- listEl.innerHTML = `<div class="dn-empty"><h3>Couldn’t load agents</h3><p>${esc(err.message || 'Failed')}</p></div>`;
+ listEl.innerHTML = `<div class="dn-empty"><h3>Couldn't load agents</h3><p>${esc(friendly(err))}</p></div>`;
return;
}
@@ -119,7 +129,7 @@ export async function renderMemory(host) {
function renderList() {
const html = [];
if (errors.length) {
- html.push(`<div class="dn-empty" style="margin-bottom:12px"><h3>Some agents’ memories couldn’t be loaded</h3><p>${errors.map((e) => `${esc(e.agent)}: ${esc(e.message)}`).join(' · ')}</p></div>`);
+ html.push(`<div class="dn-empty" style="margin-bottom:12px"><h3>Some agents' memories couldn't be loaded</h3><p>${errors.map((e) => `${esc(e.agent)}: ${esc(friendly({ message: e.message }))}`).join(' · ')}</p></div>`);
}
if (!all.length) {
html.push(`
@@ -187,7 +197,7 @@ export async function renderMemory(host) {
host.querySelector('#mem-add-content').value = '';
setTimeout(() => { statusEl.textContent = ''; addPanel.hidden = true; }, 600);
} catch (err) {
- statusEl.textContent = err.message || 'Save failed.';
+ statusEl.textContent = friendly(err);
} finally {
submitBtn.disabled = false;
}
diff --git a/src/dashboard-next/pages/library/strategy.js b/src/dashboard-next/pages/library/strategy.js
index 9550afc6e..2f3f2fb8a 100644
--- a/src/dashboard-next/pages/library/strategy.js
+++ b/src/dashboard-next/pages/library/strategy.js
@@ -4,6 +4,16 @@
import { get, post, esc, relTime, ApiError } from '../../api.js';
+function friendly(err) {
+ if (!err) return 'Something went wrong.';
+ const status = err.status || 0;
+ const msg = err.message || String(err);
+ if (status === 401 || /unauthorized|sign in|bearer/i.test(msg)) return 'Your session expired — refresh the page.';
+ if (status === 403 || /forbidden/i.test(msg)) return "You don't have permission for that.";
+ if (status === 429 || /rate.?limit/i.test(msg)) return 'Slow down — try again in a moment.';
+ return msg.replace(/^HTTP\s+\d+\s*/i, '') || 'Save failed.';
+}
+
export async function renderStrategy(host) {
host.innerHTML = `
<div class="strat-head">
@@ -52,7 +62,7 @@ export async function renderStrategy(host) {
const res = await get('/api/agents');
agents = res?.agents || [];
} catch (err) {
- body.innerHTML = `<div class="dn-empty"><h3>Couldn’t load agents</h3><p>${esc(err.message || 'Failed')}</p></div>`;
+ body.innerHTML = `<div class="dn-empty"><h3>Couldn't load agents</h3><p>${esc(friendly(err))}</p></div>`;
return;
}
@@ -99,11 +109,11 @@ export async function renderStrategy(host) {
}
if (loadErr) {
- body.innerHTML = `<div class="dn-empty"><h3>Couldn’t load strategy</h3><p>${esc(loadErr.message || 'Failed')}</p></div>`;
+ body.innerHTML = `<div class="dn-empty"><h3>Couldn't load strategy</h3><p>${esc(friendly(loadErr))}</p></div>`;
return;
}
- const placeholder = '{\n "objective": "trade memes profitably",\n "max_position_sol": 0.5,\n "stop_loss_pct": 20\n}';
+ const placeholder = '{\n "objective": "describe what this agent is optimizing for",\n "constraints": []\n}';
body.innerHTML = `
<div class="strat-panel">
<textarea class="strat-textarea" id="strat-text" spellcheck="false" placeholder=${JSON.stringify(placeholder)}>${esc(initial)}</textarea>
@@ -154,7 +164,7 @@ export async function renderStrategy(host) {
} catch (err) {
if (seq !== inflight) return;
setChip('error', 'save failed');
- msg.textContent = err.message || String(err);
+ msg.textContent = friendly(err);
}
}
diff --git a/src/dashboard-next/pages/library/voice.js b/src/dashboard-next/pages/library/voice.js
index ad0f2a0ff..ebfb9b96a 100644
--- a/src/dashboard-next/pages/library/voice.js
+++ b/src/dashboard-next/pages/library/voice.js
@@ -1,20 +1,24 @@
// Library → Voice tab.
-// Per-agent voice status (cloned ElevenLabs voice or browser fallback)
-// with a TTS preview backed by /api/tts/eleven. The actual voice clone
-// flow lives on /dashboard/voice — we link there from each row.
+// Per-agent voice picker. Lists voices from the server's ElevenLabs
+// library (/api/tts/eleven/voices), shows the currently assigned voice
+// for each agent, lets the user swap voices (PUT /api/agents/:id/voice)
+// and previews any voice with custom text via POST /api/tts/eleven.
+// Cloning a fresh voice from a recording lives on /dashboard/voice.
-import { get, esc } from '../../api.js';
+import { get, put, esc } from '../../api.js';
-const ELEVEN_PREVIEW_MAX = 240;
+const PREVIEW_MAX = 240;
const DEFAULT_PREVIEW = 'Hi, this is your agent speaking. Ready when you are.';
+const BROWSER_OPTION_VALUE = '__browser__';
export async function renderVoice(host) {
host.innerHTML = `
<div class="voice-head">
<div>
<h2 class="dn-panel-title" style="font-size:17px;margin:0 0 4px">Agent voices</h2>
- <div class="dn-panel-sub" style="margin:0">Each agent has a voice clone (ElevenLabs) or browser TTS fallback. Preview below; clone or replace on the voice page.</div>
+ <div class="dn-panel-sub" style="margin:0">Pick from the ElevenLabs library, preview against your own text, or clone a fresh voice from a recording.</div>
</div>
+ <a class="dn-btn ghost" href="/dashboard/voice">Clone a new voice →</a>
</div>
<div id="voice-list"></div>
@@ -28,15 +32,20 @@ export async function renderVoice(host) {
padding:16px;
margin-bottom:10px;
display:grid;
- grid-template-columns: 1fr auto;
- gap:14px 18px;
- align-items:flex-start;
+ grid-template-columns:1fr;
+ gap:12px;
}
- .voice-row1 { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
+ .voice-row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
.voice-name { font-size:15px; font-weight:600; color:var(--nxt-ink); }
.voice-meta { font-size:11px; color:var(--nxt-ink-fade); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
- .voice-actions { display:flex; gap:8px; flex-wrap:wrap; align-self:center; }
- .voice-preview { grid-column:1/-1; display:flex; gap:10px; flex-wrap:wrap; align-items:center; }
+ .voice-picker { display:flex; gap:8px; flex-wrap:wrap; align-items:center; }
+ .voice-picker label { font-size:12px; color:var(--nxt-ink-dim); }
+ .voice-picker select {
+ min-width:240px;
+ background:#0a0a14; border:1px solid rgba(255,255,255,0.1); color:var(--nxt-ink);
+ border-radius:8px; padding:8px 10px; font:inherit;
+ }
+ .voice-preview { display:flex; gap:10px; flex-wrap:wrap; align-items:center; }
.voice-preview input {
flex:1; min-width:220px;
background:#0a0a14; border:1px solid rgba(255,255,255,0.1); color:var(--nxt-ink);
@@ -45,24 +54,35 @@ export async function renderVoice(host) {
.voice-preview audio { height:32px; max-width:280px; }
.voice-status { font-size:12px; color:var(--nxt-ink-fade); min-height:16px; flex-basis:100%; }
.voice-status.err { color:#ff9ab1; }
+ .voice-status.ok { color:#86efac; }
</style>
`;
const list = host.querySelector('#voice-list');
let agents = [];
- try {
- const res = await get('/api/agents');
- agents = res?.agents || [];
- } catch (err) {
- list.innerHTML = `<div class="dn-empty"><h3>Couldn’t load agents</h3><p>${esc(err.message || 'Failed')}</p></div>`;
+ let library = null;
+ const [agentsRes, voicesRes] = await Promise.allSettled([
+ get('/api/agents'),
+ get('/api/tts/eleven/voices'),
+ ]);
+
+ if (agentsRes.status === 'rejected') {
+ list.innerHTML = `<div class="dn-empty"><h3>Couldn't load agents</h3><p>${esc(friendly(agentsRes.reason))}</p></div>`;
return;
}
+ agents = agentsRes.value?.agents || [];
+
+ if (voicesRes.status === 'fulfilled') {
+ library = voicesRes.value || { enabled: false, voices: [] };
+ } else {
+ library = { enabled: false, voices: [] };
+ }
if (!agents.length) {
list.innerHTML = `
<div class="dn-empty">
- <h3>You don’t have any agents yet</h3>
+ <h3>You don't have any agents yet</h3>
<p>Voices are scoped to an agent. Create one to start.</p>
<div style="margin-top:12px"><a class="dn-btn primary" href="/create">Create an agent</a></div>
</div>
@@ -70,62 +90,140 @@ export async function renderVoice(host) {
return;
}
- let elevenEnabled = false;
- try {
- const v = await get('/api/tts/eleven/voices');
- elevenEnabled = !!v?.enabled;
- } catch {
- elevenEnabled = false;
+ if (!library.enabled) {
+ const banner = document.createElement('div');
+ banner.className = 'dn-empty';
+ banner.style.cssText = 'margin-bottom:14px;padding:14px 16px;text-align:left';
+ banner.innerHTML = `
+ <h3 style="margin:0 0 4px;font-size:14px">ElevenLabs is not configured</h3>
+ <p style="margin:0;font-size:12px">Voice picking and previews are disabled until <code>ELEVENLABS_API_KEY</code> is set on the server. Agents will fall back to browser TTS.</p>
+ `;
+ list.appendChild(banner);
}
- for (const agent of agents) {
- list.appendChild(voiceCard(agent, { elevenEnabled }));
- }
+ for (const agent of agents) list.appendChild(voiceCard(agent, library));
}
-function voiceCard(agent, { elevenEnabled }) {
+function voiceCard(agent, library) {
const wrap = document.createElement('div');
wrap.className = 'voice-card';
- const voiceId = agent.voice_id || null;
- const provider = agent.voice_provider || 'browser';
- const providerLabel = voiceId ? `${esc(provider)} · cloned` : `${esc(provider)} · default`;
+ const selectId = `voice-sel-${agent.id}`;
+ const currentVoiceId = agent.voice_id || null;
+ const currentVoiceName = currentVoiceId
+ ? (library.voices.find((v) => v.voice_id === currentVoiceId)?.name || 'Custom clone')
+ : 'Browser TTS';
+
+ const options = [
+ `<option value="${BROWSER_OPTION_VALUE}"${!currentVoiceId ? ' selected' : ''}>— Browser TTS (no clone) —</option>`,
+ ...(library.voices || []).map((v) => {
+ const sel = v.voice_id === currentVoiceId ? ' selected' : '';
+ const cat = v.category ? ` · ${esc(v.category)}` : '';
+ return `<option value="${esc(v.voice_id)}"${sel}>${esc(v.name)}${cat}</option>`;
+ }),
+ ];
+
+ // Edge case: agent holds a cloned voice that isn't in the library list
+ // (e.g., a personal clone that doesn't show up in the shared /voices
+ // listing). Surface it so the user doesn't accidentally lose it.
+ if (currentVoiceId && !library.voices.some((v) => v.voice_id === currentVoiceId)) {
+ options.splice(1, 0,
+ `<option value="${esc(currentVoiceId)}" selected>Current clone (${esc(currentVoiceId).slice(0, 8)}…)</option>`,
+ );
+ }
wrap.innerHTML = `
- <div>
- <div class="voice-row1">
- <span class="voice-name">${esc(agent.name || agent.id)}</span>
- <span class="dn-tag ${voiceId ? 'success' : ''}">${providerLabel}</span>
- ${voiceId ? `<span class="voice-meta">${esc(voiceId)}</span>` : ''}
- </div>
+ <div class="voice-row">
+ <span class="voice-name">${esc(agent.name || agent.id)}</span>
+ <span class="dn-tag ${currentVoiceId ? 'success' : ''}">${esc(currentVoiceName)}</span>
+ ${currentVoiceId ? `<span class="voice-meta">${esc(currentVoiceId)}</span>` : ''}
</div>
- <div class="voice-actions">
- <a class="dn-btn ghost" href="/dashboard/voice">${voiceId ? 'Manage' : 'Clone a voice'}</a>
+
+ <div class="voice-picker">
+ <label for="${selectId}">Voice</label>
+ <select id="${selectId}" data-role="picker" ${library.enabled ? '' : 'disabled'}>
+ ${options.join('')}
+ </select>
+ <button class="dn-btn primary" data-role="save" type="button" ${library.enabled ? '' : 'disabled'}>Save</button>
</div>
+
<div class="voice-preview">
- <input type="text" maxlength="${ELEVEN_PREVIEW_MAX}" placeholder="Type sample text…" value="${esc(DEFAULT_PREVIEW)}" />
- <button class="dn-btn primary" data-action="preview" type="button" ${voiceId && elevenEnabled ? '' : 'disabled'}>Preview</button>
- <audio controls preload="none" hidden></audio>
- <span class="voice-status">${voiceId && elevenEnabled ? 'Click Preview to synthesize a sample.' : (elevenEnabled ? 'No cloned voice — clone one first to preview.' : 'ElevenLabs not configured on this server.')}</span>
+ <input type="text" maxlength="${PREVIEW_MAX}" placeholder="Type sample text…" value="${esc(DEFAULT_PREVIEW)}" data-role="preview-text" />
+ <button class="dn-btn" data-role="preview-btn" type="button" ${library.enabled ? '' : 'disabled'}>Preview</button>
+ <audio controls preload="none" hidden data-role="audio"></audio>
+ <span class="voice-status" data-role="status">${library.enabled
+ ? (currentVoiceId ? 'Click Preview to synthesize a sample.' : 'Pick a voice above, then Preview to hear it.')
+ : 'ElevenLabs not configured — previews unavailable.'}</span>
</div>
`;
- const input = wrap.querySelector('input');
- const btn = wrap.querySelector('button[data-action="preview"]');
- const audioEl = wrap.querySelector('audio');
- const status = wrap.querySelector('.voice-status');
-
- btn?.addEventListener('click', async () => {
- const text = input.value.trim();
- if (!text) { status.textContent = 'Type some text first.'; status.classList.add('err'); return; }
- btn.disabled = true;
- status.classList.remove('err');
- status.textContent = 'Synthesizing…';
+ const sel = wrap.querySelector('[data-role="picker"]');
+ const saveBtn = wrap.querySelector('[data-role="save"]');
+ const previewBtn= wrap.querySelector('[data-role="preview-btn"]');
+ const textInput = wrap.querySelector('[data-role="preview-text"]');
+ const audioEl = wrap.querySelector('[data-role="audio"]');
+ const status = wrap.querySelector('[data-role="status"]');
+ const tagEl = wrap.querySelector('.dn-tag');
+ const metaEl = wrap.querySelector('.voice-meta');
+ const headRow = wrap.querySelector('.voice-row');
+
+ function readPick() {
+ const v = sel.value;
+ return v === BROWSER_OPTION_VALUE ? null : v;
+ }
+
+ function setStatus(text, kind) {
+ status.textContent = text;
+ status.classList.remove('err', 'ok');
+ if (kind) status.classList.add(kind);
+ }
+
+ saveBtn.addEventListener('click', async () => {
+ const pick = readPick();
+ saveBtn.disabled = true;
+ setStatus(pick ? 'Saving voice…' : 'Removing voice…');
+ try {
+ const result = await put(
+ `/api/agents/${encodeURIComponent(agent.id)}/voice`,
+ { voice_id: pick },
+ );
+ const newId = result?.voice_id || null;
+ agent.voice_id = newId;
+ agent.voice_provider = result?.voice_provider || (newId ? 'elevenlabs' : 'browser');
+ const newName = newId
+ ? (library.voices.find((v) => v.voice_id === newId)?.name || 'Custom clone')
+ : 'Browser TTS';
+ tagEl.textContent = newName;
+ tagEl.classList.toggle('success', !!newId);
+ if (metaEl) {
+ metaEl.textContent = newId || '';
+ metaEl.style.display = newId ? '' : 'none';
+ } else if (newId) {
+ const span = document.createElement('span');
+ span.className = 'voice-meta';
+ span.textContent = newId;
+ headRow.appendChild(span);
+ }
+ setStatus('Saved.', 'ok');
+ } catch (err) {
+ setStatus(friendly(err), 'err');
+ } finally {
+ saveBtn.disabled = false;
+ }
+ });
+
+ previewBtn.addEventListener('click', async () => {
+ const text = textInput.value.trim();
+ if (!text) { setStatus('Type some text first.', 'err'); return; }
+ const pick = readPick();
+ if (!pick) { setStatus('Pick a voice above first.', 'err'); return; }
+ previewBtn.disabled = true;
+ setStatus('Synthesizing…');
try {
const res = await fetch('/api/tts/eleven', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ voiceId, text }),
+ body: JSON.stringify({ voiceId: pick, text }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
@@ -135,14 +233,24 @@ function voiceCard(agent, { elevenEnabled }) {
audioEl.src = URL.createObjectURL(blob);
audioEl.hidden = false;
audioEl.play().catch(() => {});
- status.textContent = 'Ready.';
+ setStatus('Ready.', 'ok');
} catch (err) {
- status.classList.add('err');
- status.textContent = err.message || 'Preview failed.';
+ setStatus(friendly(err), 'err');
} finally {
- btn.disabled = false;
+ previewBtn.disabled = false;
}
});
return wrap;
}
+
+function friendly(err) {
+ if (!err) return 'Something went wrong.';
+ const status = err.status || 0;
+ const msg = err.message || String(err);
+ if (status === 401 || /unauthorized|sign in|bearer/i.test(msg)) return 'Your session expired — refresh the page.';
+ if (status === 403 || /forbidden/i.test(msg)) return "You don't have permission for that.";
+ if (status === 429 || /rate.?limit/i.test(msg)) return 'Slow down — try again in a moment.';
+ if (status === 503 || /not.?configured/i.test(msg)) return 'ElevenLabs is not configured on this server.';
+ return msg.replace(/^HTTP\s+\d+\s*/i, '') || 'Unknown error.';
+}