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.

refine: agent voice settings + ElevenLabs lib, speech runtime, agent resolver

nirholasf34daebfabfe
diff --git a/api/_lib/elevenlabs.js b/api/_lib/elevenlabs.js
index 50f1a0e9c..8e3083b04 100644
--- a/api/_lib/elevenlabs.js
+++ b/api/_lib/elevenlabs.js
@@ -15,6 +15,41 @@ export const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';
// still override per request with `modelId`.
export const DEFAULT_TTS_MODEL = 'eleven_flash_v2_5';
+// Selectable synthesis models surfaced in the voice editor. Keep ids in sync
+// with ElevenLabs' model catalog; the agent voice API validates against this.
+export const TTS_MODELS = [
+ { id: 'eleven_flash_v2_5', label: 'Flash v2.5', note: 'Lowest latency · real-time' },
+ { id: 'eleven_turbo_v2_5', label: 'Turbo v2.5', note: 'Balanced latency & quality' },
+ { id: 'eleven_multilingual_v2', label: 'Multilingual v2', note: 'Highest quality · 29 languages' },
+];
+const TTS_MODEL_IDS = new Set(TTS_MODELS.map((m) => m.id));
+
+export function isValidModel(id) {
+ return typeof id === 'string' && TTS_MODEL_IDS.has(id);
+}
+
+/**
+ * Normalize a client-supplied voice_settings object to the canonical ElevenLabs
+ * shape with every numeric field clamped to 0..1.
+ * @returns the normalized object, or null for null input ("use defaults").
+ * @throws {Error & { status:400 }} for a non-object, non-null input.
+ */
+export function normalizeVoiceSettings(input) {
+ if (input == null) return null;
+ if (typeof input !== 'object' || Array.isArray(input))
+ throw upstreamError('voice_settings must be an object', 400);
+ const clamp01 = (v, d) => {
+ const n = Number(v);
+ return Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : d;
+ };
+ return {
+ stability: clamp01(input.stability, 0.5),
+ similarity_boost: clamp01(input.similarity_boost, 0.75),
+ style: clamp01(input.style, 0.5),
+ use_speaker_boost: input.use_speaker_boost !== undefined ? !!input.use_speaker_boost : true,
+ };
+}
+
export function elevenApiKey() {
return env.ELEVENLABS_API_KEY || null;
}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 05ce11c41..271850331 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -403,6 +403,8 @@ alter table agent_identities add column if not exists embed_policy jsonb;
alter table agent_identities add column if not exists voice_provider text default 'browser';
alter table agent_identities add column if not exists voice_id text;
alter table agent_identities add column if not exists voice_cloned_at timestamptz;
+alter table agent_identities add column if not exists voice_model text;
+alter table agent_identities add column if not exists voice_settings jsonb;
alter table agent_identities add column if not exists farcaster_fid integer;
alter table agent_identities add column if not exists farcaster_fname text;
alter table agent_identities add column if not exists farcaster_seeded_at timestamptz;
diff --git a/api/agents.js b/api/agents.js
index 2d723255b..374fe3643 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -495,9 +495,11 @@ function decorate(row, isOwner = true) {
is_owner: !!isOwner,
created_at: row.created_at,
};
- // Voice clone fields are public (voice_id is needed by the runtime to select TTS).
+ // Voice fields are public (the runtime reads them to configure TTS).
base.voice_provider = row.voice_provider || 'browser';
base.voice_id = row.voice_id || null;
+ base.voice_model = row.voice_model || null;
+ base.voice_settings = row.voice_settings || null;
if (isOwner) {
base.wallet_address = row.wallet_address;
diff --git a/api/agents/_id/voice.js b/api/agents/_id/voice.js
index b21792597..c9d1c33e1 100644
--- a/api/agents/_id/voice.js
+++ b/api/agents/_id/voice.js
@@ -10,11 +10,29 @@ import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
-import { isConfigured, listVoices, createClonedVoice, deleteVoice } from '../../_lib/elevenlabs.js';
+import {
+ isConfigured,
+ listVoices,
+ createClonedVoice,
+ deleteVoice,
+ isValidModel,
+ normalizeVoiceSettings,
+} from '../../_lib/elevenlabs.js';
const MAX_AUDIO_BYTES = 10 * 1024 * 1024; // 10 MB
const MIN_DURATION_SEC = 30;
+// Canonical voice-status response shape, shared by GET and the PUT branches.
+function voiceStatus(row) {
+ return {
+ voice_provider: row?.voice_provider || 'browser',
+ voice_id: row?.voice_id || null,
+ voice_cloned_at: row?.voice_cloned_at || null,
+ voice_model: row?.voice_model || null,
+ voice_settings: row?.voice_settings || null,
+ };
+}
+
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
@@ -57,24 +75,22 @@ export const handleVoice = wrap(async (req, res, id, action) => {
if (req.method === 'GET') {
const [row] =
- await sql`SELECT voice_provider, voice_id, voice_cloned_at FROM agent_identities WHERE id = ${id}`;
- return json(res, 200, {
- voice_provider: row.voice_provider || 'browser',
- voice_id: row.voice_id || null,
- voice_cloned_at: row.voice_cloned_at || null,
- });
+ await sql`SELECT voice_provider, voice_id, voice_cloned_at, voice_model, voice_settings FROM agent_identities WHERE id = ${id}`;
+ return json(res, 200, voiceStatus(row));
}
- // ── PUT — assign a voice from the ElevenLabs library ────────────────────
+ // ── PUT — assign a voice and/or tune its settings ───────────────────────
//
- // 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
+ // Body (every field optional; only keys that are present are applied):
+ // voice_id: string | null — library voice id (null/'' clears to browser)
+ // voice_model: string | null — synthesis model id (null = platform default)
+ // voice_settings: object | null — { stability, similarity_boost, style,
+ // use_speaker_boost }; null = defaults
//
- // 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).
+ // A settings/model-only PUT (no voice_id key) updates just those columns and
+ // leaves voice_id / voice_cloned_at untouched, so tuning a cloned voice never
+ // drops the clone marker. Assigning a new voice_id over an existing *clone*
+ // frees the old clone in ElevenLabs to recover the quota slot.
if (req.method === 'PUT') {
if (!isConfigured())
@@ -92,57 +108,85 @@ export const handleVoice = wrap(async (req, res, id, action) => {
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;
+ const has = (k) => Object.prototype.hasOwnProperty.call(body, k);
+ const hasVoiceId = has('voice_id');
+ const hasModel = has('voice_model');
+ const hasSettings = has('voice_settings');
+ if (!hasVoiceId && !hasModel && !hasSettings)
+ return error(res, 400, 'validation_error', 'nothing to update');
+
+ // Validate model + settings up front.
+ let model;
+ if (hasModel) {
+ model = body.voice_model == null ? null : String(body.voice_model);
+ if (model !== null && !isValidModel(model))
+ return error(res, 400, 'validation_error', 'unsupported voice_model');
+ }
+ let settings;
+ if (hasSettings) {
try {
- ({ voices } = await listVoices());
- } catch (err) {
- console.error('[voice/put] listVoices failed', 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',
- );
+ settings = normalizeVoiceSettings(body.voice_settings);
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.message);
}
}
- // 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) {
- deleteVoice(oldVoiceId);
- }
+ const [current] =
+ await sql`SELECT voice_id, voice_cloned_at, voice_model, voice_settings FROM agent_identities WHERE id = ${id}`;
+
+ // Carry forward whatever wasn't explicitly provided.
+ const finalModel = hasModel ? model : (current?.voice_model ?? null);
+ const finalSettings = hasSettings ? settings : (current?.voice_settings ?? null);
+ const settingsParam = finalSettings == null ? null : JSON.stringify(finalSettings);
+
+ if (hasVoiceId) {
+ const nextVoiceId = body.voice_id == null ? null : String(body.voice_id).trim() || null;
+ const wasCloned = !!current?.voice_cloned_at;
+ const oldVoiceId = current?.voice_id || null;
+
+ if (nextVoiceId) {
+ let voices;
+ try {
+ ({ voices } = await listVoices());
+ } catch (err) {
+ console.error('[voice/put] listVoices failed', 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');
+
+ if (wasCloned && oldVoiceId && oldVoiceId !== nextVoiceId) deleteVoice(oldVoiceId);
+
+ const [row] = await sql`
+ UPDATE agent_identities
+ SET voice_provider = 'elevenlabs', voice_id = ${nextVoiceId}, voice_cloned_at = NULL,
+ voice_model = ${finalModel}, voice_settings = ${settingsParam}::jsonb
+ WHERE id = ${id}
+ RETURNING voice_provider, voice_id, voice_cloned_at, voice_model, voice_settings
+ `;
+ return json(res, 200, voiceStatus(row));
+ }
- if (nextVoiceId) {
- await sql`
+ // Clear to browser — resets every voice column.
+ if (wasCloned && oldVoiceId) deleteVoice(oldVoiceId);
+ const [row] = await sql`
UPDATE agent_identities
- SET voice_provider = 'elevenlabs', voice_id = ${nextVoiceId}, voice_cloned_at = NULL
+ SET voice_provider = 'browser', voice_id = NULL, voice_cloned_at = NULL,
+ voice_model = NULL, voice_settings = NULL
WHERE id = ${id}
+ RETURNING voice_provider, voice_id, voice_cloned_at, voice_model, voice_settings
`;
- return json(res, 200, {
- voice_provider: 'elevenlabs',
- voice_id: nextVoiceId,
- voice_cloned_at: null,
- });
+ return json(res, 200, voiceStatus(row));
}
- await sql`
+ // Settings/model-only update — leave the voice assignment untouched.
+ const [row] = await sql`
UPDATE agent_identities
- SET voice_provider = 'browser', voice_id = NULL, voice_cloned_at = NULL
+ SET voice_model = ${finalModel}, voice_settings = ${settingsParam}::jsonb
WHERE id = ${id}
+ RETURNING voice_provider, voice_id, voice_cloned_at, voice_model, voice_settings
`;
- return json(res, 200, { voice_provider: 'browser', voice_id: null, voice_cloned_at: null });
+ return json(res, 200, voiceStatus(row));
}
// ── DELETE — remove cloned voice ─────────────────────────────────────────
diff --git a/api/tts/eleven.js b/api/tts/eleven.js
index 0ccc0d339..5db2fbe14 100644
--- a/api/tts/eleven.js
+++ b/api/tts/eleven.js
@@ -23,7 +23,12 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { cors, method, wrap, error, readJson } from '../_lib/http.js';
import { sha256 } from '../_lib/crypto.js';
import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';
-import { ELEVEN_BASE, DEFAULT_TTS_MODEL, elevenApiKey } from '../_lib/elevenlabs.js';
+import {
+ ELEVEN_BASE,
+ DEFAULT_TTS_MODEL,
+ elevenApiKey,
+ normalizeVoiceSettings,
+} from '../_lib/elevenlabs.js';
const CHARS_PER_HOUR = 1000;
@@ -72,18 +77,11 @@ export default wrap(async (req, res) => {
// Honor the canonical ElevenLabs `voice_settings` object the client sends
// (the ElevenLabsTTS client maps `rate` → `style` and forwards it here);
- // fall back to ElevenLabs' recommended defaults. Clamped to 0..1 and folded
- // into the cache key so distinct settings never collide on a shared clip.
- const clamp01 = (v, fallback) => {
- const n = Number(v);
- return Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : fallback;
- };
- const vs =
- body.voice_settings && typeof body.voice_settings === 'object' ? body.voice_settings : {};
- const stability = clamp01(vs.stability, 0.5);
- const similarityBoost = clamp01(vs.similarity_boost, 0.75);
- const style = clamp01(vs.style, 0.5);
- const useSpeakerBoost = vs.use_speaker_boost !== undefined ? !!vs.use_speaker_boost : true;
+ // fall back to ElevenLabs' recommended defaults. Folded into the cache key so
+ // distinct settings never collide on a shared clip.
+ const settings = normalizeVoiceSettings(
+ body.voice_settings && typeof body.voice_settings === 'object' ? body.voice_settings : {},
+ );
// ── Char-based rate limit ─────────────────────────────────────────────────
// rKey is lifted to function scope so a failed synthesis can refund the
@@ -123,7 +121,7 @@ export default wrap(async (req, res) => {
// ── R2 cache lookup ───────────────────────────────────────────────────────
const cacheHash = await sha256(
- `${voiceId}\x00${text}\x00${modelId}\x00${stability}\x00${similarityBoost}\x00${style}\x00${useSpeakerBoost}`,
+ `${voiceId}\x00${text}\x00${modelId}\x00${settings.stability}\x00${settings.similarity_boost}\x00${settings.style}\x00${settings.use_speaker_boost}`,
);
const cacheKey = `tts/cache/${cacheHash}.mp3`;
@@ -156,12 +154,7 @@ export default wrap(async (req, res) => {
body: JSON.stringify({
text,
model_id: modelId,
- voice_settings: {
- stability,
- similarity_boost: similarityBoost,
- style,
- use_speaker_boost: useSpeakerBoost,
- },
+ voice_settings: settings,
}),
},
);
diff --git a/chat-plugin/README.md b/chat-plugin/README.md
index 83f84f9c3..1da488261 100644
--- a/chat-plugin/README.md
+++ b/chat-plugin/README.md
@@ -132,12 +132,19 @@ Two harnesses live in `chat-plugin/dev/`:
one to use when verifying the SperaxOS / LobeChat integration.
- **`index.html`** — drives the lower-level v1 bridge directly.
+The harness files live outside `public/` (so they never ship), which means the Vite
+dev server can't serve them — run a plain static server for the harness and point its
+iframe at the dev server:
+
```bash
-# From repo root, run the dev server (serves /lobehub/iframe/ + /api proxy):
-npm run dev # http://localhost:3000
+# Terminal 1 — the dev server (serves /lobehub/iframe/, /src/lib.js, /api proxy):
+npm run dev # http://localhost:3000
+
+# Terminal 2 — a static server for the harness:
+python3 -m http.server 8080
-# Open the protocol harness against it:
-open http://localhost:3000/chat-plugin/dev/sperax.html?origin=http://localhost:3000&agent=<your-agent-id>
+# Open the protocol harness; ?origin points the iframe at the dev server:
+open "http://localhost:8080/chat-plugin/dev/sperax.html?origin=http://localhost:3000&agent=<your-agent-id>"
```
Click **Load iframe**, wait for the green **plugin-ready ✓** dot, then **Inject
diff --git a/pages/agent-edit.html b/pages/agent-edit.html
index eb253013b..a60a02dfe 100644
--- a/pages/agent-edit.html
+++ b/pages/agent-edit.html
@@ -857,6 +857,12 @@
.voice-tile-meta { font-size: 0.618rem; color: rgba(255, 255, 255, 0.4); }
.voice-tile-play { background: transparent; border: 0; color: rgba(255, 255, 255, 0.6); font-size: 1rem; cursor: pointer; padding: 0 0.25rem; }
.voice-tile-play:hover { color: #fff; }
+ .voice-tune-grid { display: grid; grid-template-columns: max-content 1fr; gap: 0.5rem 0.85rem; align-items: center; margin-bottom: 0.85rem; }
+ .voice-tune-grid .form-label { margin: 0; display: flex; justify-content: space-between; gap: 0.5rem; }
+ .voice-tune-grid input[type="range"] { width: 100%; accent-color: #3b82f6; cursor: pointer; }
+ .voice-range-val { font-variant-numeric: tabular-nums; color: rgba(255, 255, 255, 0.55); font-weight: 400; }
+ .voice-check { grid-column: 1 / -1; display: flex; align-items: center; gap: 0.5rem; font-size: 0.82rem; color: rgba(255, 255, 255, 0.75); cursor: pointer; }
+ .voice-check input { accent-color: #3b82f6; }
/* Memories */
.mem-list { display: flex; flex-direction: column; gap: 0.5rem; }
@@ -1245,6 +1251,40 @@
<div id="voice-list" class="voice-list"><div class="muted">Loading voices…</div></div>
</div>
+ <div class="form-group" id="voice-tune" hidden>
+ <label class="form-label">Fine-tune delivery</label>
+ <p class="hint">Applied whenever this agent speaks with its ElevenLabs voice.</p>
+
+ <div class="voice-tune-grid">
+ <label class="form-label" for="voice-model">Model</label>
+ <select class="form-input" id="voice-model"></select>
+
+ <label class="form-label" for="voice-stability">Stability
+ <span class="voice-range-val" id="voice-stability-val">0.50</span></label>
+ <input type="range" id="voice-stability" min="0" max="1" step="0.05" value="0.5" />
+
+ <label class="form-label" for="voice-similarity">Similarity
+ <span class="voice-range-val" id="voice-similarity-val">0.75</span></label>
+ <input type="range" id="voice-similarity" min="0" max="1" step="0.05" value="0.75" />
+
+ <label class="form-label" for="voice-style">Style
+ <span class="voice-range-val" id="voice-style-val">0.50</span></label>
+ <input type="range" id="voice-style" min="0" max="1" step="0.05" value="0.5" />
+
+ <label class="voice-check" for="voice-speaker-boost">
+ <input type="checkbox" id="voice-speaker-boost" checked /> Speaker boost
+ </label>
+ </div>
+
+ <div class="form-actions">
+ <input class="form-input" id="voice-test-text" type="text" maxlength="200"
+ placeholder="Type a line to test…" value="Hi! This is how I sound." style="max-width:280px" />
+ <button class="btn-ghost" id="voice-test-btn">Test voice</button>
+ <button class="btn-primary" id="voice-save-settings-btn">Save settings</button>
+ <span class="form-status" id="voice-settings-status" role="status" aria-live="polite"></span>
+ </div>
+ </div>
+
<div class="form-group">
<label class="form-label">Or clone your own voice</label>
<p class="hint">Upload at least 30 seconds of clean speech (mp3/wav/m4a, max 10 MB). 3 clones per day.</p>
diff --git a/public/sperax/README.md b/public/sperax/README.md
index 55f1a5a21..3379c5833 100644
--- a/public/sperax/README.md
+++ b/public/sperax/README.md
@@ -85,12 +85,15 @@ The manifest is hosted and ready. To list it on `plugin.delivery`:
## Local testing
-Run the dev server and drive the iframe with the protocol harness — it posts the
-exact `speraxos:` / `lobe-chat:` messages a real host sends:
+Drive the iframe with the protocol harness in `chat-plugin/dev/sperax.html` — it
+posts the exact `speraxos:` / `lobe-chat:` messages a real host sends. Run the dev
+server for the iframe, and a static server for the harness (it lives outside
+`public/`, so Vite won't serve it):
```bash
-npm run dev # http://localhost:3000
-open "http://localhost:3000/chat-plugin/dev/sperax.html?origin=http://localhost:3000&agent=<agentId>"
+npm run dev # http://localhost:3000 (iframe + /api)
+python3 -m http.server 8080 # serves the harness
+open "http://localhost:8080/chat-plugin/dev/sperax.html?origin=http://localhost:3000&agent=<agentId>"
```
---
diff --git a/src/agent-resolver.js b/src/agent-resolver.js
index c33ce6129..78a8e17e6 100644
--- a/src/agent-resolver.js
+++ b/src/agent-resolver.js
@@ -109,6 +109,19 @@ export async function resolveByAgentId(agentId, signal) {
return resolved;
}
+// Map a stored ElevenLabs voice_settings object (snake_case, as persisted by
+// PUT /api/agents/:id/voice) to the camelCase options ElevenLabsTTS accepts.
+// Omits absent fields so the TTS client falls back to its own defaults.
+function voiceSettingsToConfig(vs) {
+ if (!vs || typeof vs !== 'object') return {};
+ const out = {};
+ if (vs.stability != null) out.stability = vs.stability;
+ if (vs.similarity_boost != null) out.similarityBoost = vs.similarity_boost;
+ if (vs.style != null) out.style = vs.style;
+ if (vs.use_speaker_boost != null) out.useSpeakerBoost = vs.use_speaker_boost;
+ return out;
+}
+
export async function resolveAgentById(
agentId,
{ origin = typeof location !== 'undefined' ? location.origin : '', fetchFn = fetch } = {},
@@ -159,6 +172,8 @@ export async function resolveAgentById(
provider: 'elevenlabs',
voiceId: agent.voice_id,
proxyURL: `${origin}/api/tts/eleven`,
+ ...(agent.voice_model ? { modelId: agent.voice_model } : {}),
+ ...voiceSettingsToConfig(agent.voice_settings),
}
: { provider: 'browser' },
stt: { provider: 'browser' },
diff --git a/src/runtime/speech.js b/src/runtime/speech.js
index 4a538fcc1..b240c1004 100644
--- a/src/runtime/speech.js
+++ b/src/runtime/speech.js
@@ -182,6 +182,7 @@ export class ElevenLabsTTS {
lang = 'en-US',
stability = 0.5,
similarityBoost = 0.75,
+ style = null,
useSpeakerBoost = true,
} = {}) {
if (!voiceId) throw new Error('ElevenLabsTTS requires voiceId');
@@ -194,6 +195,8 @@ export class ElevenLabsTTS {
this.lang = lang;
this.stability = stability;
this.similarityBoost = similarityBoost;
+ // Explicit style override (0..1). When null, style is derived from `rate`.
+ this.style = style;
this.useSpeakerBoost = useSpeakerBoost;
this._speaking = false;
@@ -237,9 +240,12 @@ export class ElevenLabsTTS {
// apiKey is only sent when there's no proxy. Proxies must keep keys server-side.
if (!this.proxyURL && this.apiKey) headers['xi-api-key'] = this.apiKey;
- // Map rate (0.5..1.5) → style (0..1). Clamped to keep delivery natural.
+ // Explicit style wins; otherwise map rate (0.5..1.5) → style (0..1).
const rateNorm = Math.min(1.5, Math.max(0.5, this.rate));
- const styleVal = Math.min(1, Math.max(0, (rateNorm - 0.5) / 1.0));
+ const styleVal =
+ this.style != null
+ ? Math.min(1, Math.max(0, Number(this.style)))
+ : Math.min(1, Math.max(0, (rateNorm - 0.5) / 1.0));
const body = JSON.stringify({
text,
diff --git a/tests/api-tts-elevenlabs.test.js b/tests/api-tts-elevenlabs.test.js
index 8e3f0f5dc..4eef9bb56 100644
--- a/tests/api-tts-elevenlabs.test.js
+++ b/tests/api-tts-elevenlabs.test.js
@@ -17,6 +17,9 @@ vi.mock('@elevenlabs/elevenlabs-js', () => ({
import {
DEFAULT_TTS_MODEL,
+ TTS_MODELS,
+ isValidModel,
+ normalizeVoiceSettings,
elevenApiKey,
isConfigured,
listVoices,
@@ -56,6 +59,61 @@ describe('config gate', () => {
});
});
+describe('isValidModel / TTS_MODELS', () => {
+ it('accepts catalog models and rejects everything else', () => {
+ expect(isValidModel('eleven_flash_v2_5')).toBe(true);
+ expect(isValidModel('eleven_turbo_v2_5')).toBe(true);
+ expect(isValidModel('gpt-4o-tts')).toBe(false);
+ expect(isValidModel(null)).toBe(false);
+ expect(isValidModel(undefined)).toBe(false);
+ });
+
+ it('exposes the default model in the catalog', () => {
+ expect(TTS_MODELS.some((m) => m.id === DEFAULT_TTS_MODEL)).toBe(true);
+ for (const m of TTS_MODELS) expect(m).toMatchObject({ id: expect.any(String), label: expect.any(String) });
+ });
+});
+
+describe('normalizeVoiceSettings', () => {
+ it('returns null for null input (use defaults)', () => {
+ expect(normalizeVoiceSettings(null)).toBeNull();
+ expect(normalizeVoiceSettings(undefined)).toBeNull();
+ });
+
+ it('fills recommended defaults for an empty object', () => {
+ expect(normalizeVoiceSettings({})).toEqual({
+ stability: 0.5,
+ similarity_boost: 0.75,
+ style: 0.5,
+ use_speaker_boost: true,
+ });
+ });
+
+ it('clamps numeric fields to 0..1 and falls back on non-numbers', () => {
+ expect(normalizeVoiceSettings({ stability: 2, similarity_boost: -1, style: 'nope' })).toEqual({
+ stability: 1,
+ similarity_boost: 0,
+ style: 0.5,
+ use_speaker_boost: true,
+ });
+ });
+
+ it('coerces use_speaker_boost to a boolean', () => {
+ expect(normalizeVoiceSettings({ use_speaker_boost: false }).use_speaker_boost).toBe(false);
+ expect(normalizeVoiceSettings({ use_speaker_boost: 0 }).use_speaker_boost).toBe(false);
+ });
+
+ it('rejects non-object input with a 400', () => {
+ expect(() => normalizeVoiceSettings('x')).toThrowError(/must be an object/);
+ expect(() => normalizeVoiceSettings([])).toThrow();
+ try {
+ normalizeVoiceSettings(5);
+ } catch (e) {
+ expect(e.status).toBe(400);
+ }
+ });
+});
+
describe('listVoices', () => {
it('throws a 503 when unconfigured, without hitting the network', async () => {
delete process.env.ELEVENLABS_API_KEY;