Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(tts): keep the audible voice profile stable across every fallback takeover

Ruben Lütkef64e43e30e5c
diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.py
index 7b0589c522..8822013e51 100644
--- a/jarvis/plugins/tts/__init__.py
+++ b/jarvis/plugins/tts/__init__.py
@@ -14,15 +14,21 @@ from __future__ import annotations
import logging
from typing import Any
+from jarvis.plugins.tts.curated_catalog import allowed_voices as _curated_voices
+
log = logging.getLogger("jarvis.tts.factory")
# Voices belonging to each respective provider — prevents e.g. a
# Gemini voice ("Charon") from landing in the Grok plugin and triggering HTTP 400.
-_GEMINI_VOICES = frozenset({
- "Charon", "Orus", "Iapetus", "Rasalgethi", "Algenib",
- "Algieba", "Kore", "Fenrir", "Aoede",
-})
-_GROK_VOICES = frozenset({"leo", "rex", "sal", "ara", "eve"})
+# Derived from the curated catalog (the single source of truth) so a voice the
+# picker legitimately offers (e.g. Gemini "Puck", Grok "luna") is never force-
+# rewritten to the family default by the factory whitelist lagging behind.
+_GEMINI_VOICES = frozenset(
+ v.id for v in _curated_voices("gemini-flash-tts", "gemini-3.1-flash-tts-preview")
+)
+_GROK_VOICES = frozenset(
+ v.id for v in _curated_voices("grok-voice", "grok-voice-tts-1.0")
+)
# Accepted spellings → canonical provider name, mirroring the `if provider in (...)`
# groups in ``_build_provider`` so the credential probe + cross-family order key
@@ -192,6 +198,7 @@ def resolve_keyed_fallback(
*,
allow_sapi5: bool = False,
language_code: str | None = None,
+ reference_voice: str | None = None,
) -> Any | None:
"""Build the first cross-family TTS provider (≠ ``exclude_family``) that has
a usable key on this host — so a plugin's INTERNAL runtime fallback never
@@ -204,17 +211,37 @@ def resolve_keyed_fallback(
premium first, OpenRouter last), skipping the failed family and any keyless
one. Returns a built provider, or ``None`` when NO other family has a key
(the caller then degrades to the opt-in SAPI5 exit or an honest mute).
+
+ ``reference_voice`` is the failing provider's ACTIVE voice: when given and
+ its profile is known, the crossed-to family speaks with its curated voice
+ of the SAME profile (masculine/feminine) instead of its unrelated default,
+ so the mid-session takeover doesn't audibly change who is speaking.
"""
from jarvis.core.config import TTSConfig
+ from jarvis.plugins.tts.curated_catalog import continuity_voice, voice_gender
+ ref_gender = voice_gender(reference_voice)
exclude = _canonical_tts_name(exclude_family)
for cand in _TTS_CROSS_FAMILY_ORDER:
if cand == exclude:
continue
+ voice_kwargs: dict[str, str] = {}
+ if ref_gender:
+ model_id = None
+ if cand == "openrouter":
+ # The candidate view carries no model, so OpenRouterTTS will
+ # use its default model — match the voice against that one.
+ from jarvis.plugins.tts.openrouter_speech_models import DEFAULT_MODEL
+
+ model_id = DEFAULT_MODEL
+ matched = continuity_voice(cand, ref_gender, model_id=model_id)
+ if matched:
+ voice_kwargs = {"voice_de": matched, "voice_en": matched}
cfg_view = TTSConfig(
provider=cand,
language_code=language_code or "auto",
allow_sapi5_fallback=allow_sapi5,
+ **voice_kwargs,
)
if not _tts_has_credential(cand, cfg_view):
continue
@@ -229,6 +256,90 @@ def resolve_keyed_fallback(
return None
+def _effective_primary_voice(family: str, tts_cfg: Any) -> str | None:
+ """Best-effort offline prediction of the voice ``family`` will speak with.
+
+ Mirrors each family's builder/plugin voice resolution (config voice when
+ valid for the family, else the family default) WITHOUT building the
+ provider. Used to derive the active voice PROFILE for fallback continuity.
+ Returns ``None`` for families whose voice cannot be predicted offline
+ (Cartesia ids, unknown third-party providers) — callers then skip the
+ profile matching (today's behavior).
+ """
+ voice_de = (getattr(tts_cfg, "voice_de", None) or "").strip()
+ if family == "grok-voice":
+ try:
+ from jarvis.plugins.tts.grok_voice_tts import DEFAULT_VOICES, GROK_VOICE_LEO
+ except ImportError:
+ return None
+ return voice_de if voice_de in DEFAULT_VOICES else GROK_VOICE_LEO
+ if family == "gemini-flash-tts":
+ return voice_de if voice_de in _GEMINI_VOICES else "Charon"
+ if family == "elevenlabs":
+ try:
+ from jarvis.plugins.tts.elevenlabs_tts import JARVIS_VOICE_DANIEL
+ except ImportError:
+ return None
+ cleaned = _without_foreign_voice(tts_cfg, "elevenlabs")
+ return (getattr(cleaned, "voice_de", None) or "").strip() or JARVIS_VOICE_DANIEL
+ if family == "openrouter":
+ try:
+ from jarvis.plugins.tts.openrouter_speech_models import (
+ MODEL_DEFAULT_VOICE,
+ MODEL_VOICES,
+ coerce_speech_model,
+ )
+ except ImportError:
+ return None
+ mid = coerce_speech_model(getattr(tts_cfg, "model", None))
+ if voice_de and voice_de in MODEL_VOICES.get(mid, ()):
+ return voice_de
+ return MODEL_DEFAULT_VOICE.get(mid)
+ if family == "inworld":
+ extras = getattr(tts_cfg, "model_extra", None) or {}
+ iw = extras.get("inworld") if isinstance(extras, dict) else None
+ iw = iw if isinstance(iw, dict) else {}
+ configured = (iw.get("voice_de") or "").strip()
+ if configured:
+ return configured
+ try:
+ from jarvis.plugins.tts.inworld_tts import DEFAULT_VOICE_DE
+ except ImportError:
+ return None
+ return DEFAULT_VOICE_DE
+ return None
+
+
+def _continuity_fallback_voice(
+ primary_name: str, primary_cfg: Any, fallback_name: str, fallback_cfg: Any
+) -> str | None:
+ """Voice the ``FallbackTTS`` wrapper should pin on the fallback provider so
+ a mid-conversation takeover keeps the ACTIVE voice profile (the audible
+ masculine/feminine character), instead of flipping to the fallback family's
+ unrelated default voice.
+
+ Returns ``None`` when the primary's profile is unknown, or when the
+ fallback's own voice resolution already matches it (an explicitly chosen,
+ profile-consistent fallback voice is respected, never overridden).
+ """
+ from jarvis.plugins.tts.curated_catalog import continuity_voice, voice_gender
+
+ ref_voice = _effective_primary_voice(_canonical_tts_name(primary_name), primary_cfg)
+ ref_gender = voice_gender(ref_voice)
+ if not ref_gender:
+ return None
+ fb_family = _canonical_tts_name(fallback_name)
+ native = _effective_primary_voice(fb_family, fallback_cfg)
+ if native is not None and voice_gender(native) == ref_gender:
+ return None
+ model_id = None
+ if fb_family == "openrouter":
+ from jarvis.plugins.tts.openrouter_speech_models import coerce_speech_model
+
+ model_id = coerce_speech_model(getattr(fallback_cfg, "model", None))
+ return continuity_voice(fb_family, ref_gender, model_id=model_id)
+
+
def _resolve_voice_for_provider(
requested: str, provider: str, default: str, allowed: frozenset[str]
) -> str:
@@ -302,8 +413,18 @@ def build_tts_from_config(tts_cfg: Any) -> Any:
from jarvis.plugins.tts.fallback_tts import FallbackTTS
- log.info("TTS fallback active: primary=%r → fallback=%r", primary_name, fallback_name)
- return FallbackTTS(primary, secondary)
+ # Voice-profile continuity (2026-07-17): pin the fallback family's curated
+ # voice matching the primary's active profile, so a mid-conversation
+ # takeover never audibly flips masculine↔feminine ("Jarvis suddenly has a
+ # different voice"). None → the fallback keeps its own resolution.
+ fallback_voice = _continuity_fallback_voice(
+ primary_name, primary_cfg, fallback_name, tts_cfg
+ )
+ log.info(
+ "TTS fallback active: primary=%r → fallback=%r (continuity voice: %s)",
+ primary_name, fallback_name, fallback_voice or "provider default",
+ )
+ return FallbackTTS(primary, secondary, fallback_voice=fallback_voice)
def _build_provider(tts_cfg: Any, provider: str) -> Any:
diff --git a/jarvis/plugins/tts/cartesia_tts.py b/jarvis/plugins/tts/cartesia_tts.py
index 936a200822..22d7c5c26e 100644
--- a/jarvis/plugins/tts/cartesia_tts.py
+++ b/jarvis/plugins/tts/cartesia_tts.py
@@ -355,6 +355,7 @@ class CartesiaTTS:
self.name,
allow_sapi5=self._allow_sapi5_fallback,
language_code=language_code,
+ reference_voice=self._resolve_voice(text, None, language_code),
)
if fb is not None:
produced = False
diff --git a/jarvis/plugins/tts/curated_catalog.py b/jarvis/plugins/tts/curated_catalog.py
index be9afc3473..0c31d06de1 100644
--- a/jarvis/plugins/tts/curated_catalog.py
+++ b/jarvis/plugins/tts/curated_catalog.py
@@ -26,14 +26,84 @@ from dataclasses import dataclass, field
# personality-named voices (Gemini "Charon", Grok "leo") are all multilingual.
MULTILINGUAL = "multi"
+# Voice-profile genders. Only confidently documented voices are tagged; an
+# unknown voice maps to "" so every consumer degrades to today's behavior
+# (fail-safe: no profile → no cross-provider voice matching).
+MASCULINE = "m"
+FEMININE = "f"
+
+# Curated gender register across ALL families (single flat map — voice ids are
+# unique across the vendors we ship). Sources: Google speech-generation voice
+# docs (30 Gemini voices), xAI TTS guide (the five classic Grok voices — the
+# 21 newer ones stay untagged until documented), Inworld voice roster, the
+# five curated ElevenLabs prebuilt voices (ids), OpenAI gpt-realtime (cedar/
+# marin — realtime-only, referenced for cross-path continuity), and the
+# OpenRouter speech-model default voices we curate.
+_VOICE_GENDERS: dict[str, str] = {
+ # Gemini / google TTS + Live (masculine)
+ "Puck": MASCULINE, "Charon": MASCULINE, "Fenrir": MASCULINE,
+ "Orus": MASCULINE, "Enceladus": MASCULINE, "Iapetus": MASCULINE,
+ "Umbriel": MASCULINE, "Algieba": MASCULINE, "Algenib": MASCULINE,
+ "Rasalgethi": MASCULINE, "Alnilam": MASCULINE, "Schedar": MASCULINE,
+ "Achird": MASCULINE, "Zubenelgenubi": MASCULINE, "Sadachbia": MASCULINE,
+ "Sadaltager": MASCULINE,
+ # Gemini / google TTS + Live (feminine)
+ "Zephyr": FEMININE, "Kore": FEMININE, "Leda": FEMININE, "Aoede": FEMININE,
+ "Callirrhoe": FEMININE, "Autonoe": FEMININE, "Despina": FEMININE,
+ "Erinome": FEMININE, "Laomedeia": FEMININE, "Achernar": FEMININE,
+ "Gacrux": FEMININE, "Pulcherrima": FEMININE, "Vindemiatrix": FEMININE,
+ "Sulafat": FEMININE,
+ # Grok Voice (xAI) — classic roster only
+ "leo": MASCULINE, "rex": MASCULINE, "sal": MASCULINE,
+ "ara": FEMININE, "eve": FEMININE,
+ # Inworld
+ "Josef": MASCULINE, "Dennis": MASCULINE, "Diego": MASCULINE,
+ "Johanna": FEMININE, "Ashley": FEMININE, "Lupita": FEMININE,
+ # ElevenLabs curated prebuilt voices (ids; all masculine)
+ "onwK4e9ZLuTAKqWW03F9": MASCULINE, # Daniel
+ "JBFqnCBsd6RMkjVDRZzb": MASCULINE, # George
+ "IKne3meq5aSn9XLyUdCD": MASCULINE, # Charlie
+ "nPczCjzI2devNBz1zQrb": MASCULINE, # Brian
+ "pNInz6obpgDQGcFmaJgB": MASCULINE, # Adam
+ # OpenAI gpt-realtime (realtime path; for cross-path profile continuity)
+ "cedar": MASCULINE, "marin": FEMININE,
+ # OpenRouter curated speech-model defaults outside the vendor families
+ "af_bella": FEMININE, # Kokoro ("af" = adult female roster)
+ "tara": FEMININE, # Orpheus default
+ "en_paul_neutral": MASCULINE, # Voxtral default
+}
+
+
+def voice_gender(voice_id: str | None) -> str | None:
+ """Gender of a known voice id (:data:`MASCULINE`/:data:`FEMININE`), else
+ ``None``. Case-insensitive fallback covers ad-hoc user spellings."""
+ vid = (voice_id or "").strip()
+ if not vid:
+ return None
+ g = _VOICE_GENDERS.get(vid)
+ if g:
+ return g
+ lowered = vid.lower()
+ for known, gender in _VOICE_GENDERS.items():
+ if known.lower() == lowered:
+ return gender
+ return None
+
@dataclass(frozen=True)
class VoiceEntry:
- """One vetted voice: its id and the ISO-639-1 language it speaks (or
- :data:`MULTILINGUAL` for a language-agnostic voice)."""
+ """One vetted voice: its id, the ISO-639-1 language it speaks (or
+ :data:`MULTILINGUAL` for a language-agnostic voice), and its curated
+ gender ("m"/"f", or "" when not confidently documented)."""
id: str
language: str = MULTILINGUAL
+ gender: str = ""
+
+
+def _v(voice_id: str, language: str = MULTILINGUAL) -> VoiceEntry:
+ """Catalog constructor that auto-attaches the curated gender tag."""
+ return VoiceEntry(voice_id, language, _VOICE_GENDERS.get(voice_id, ""))
@dataclass(frozen=True)
@@ -78,12 +148,12 @@ _CATALOG: tuple[ModelEntry, ...] = (
latency_class="realtime",
streaming=True,
voices=(
- VoiceEntry("Josef", "de"),
- VoiceEntry("Johanna", "de"),
- VoiceEntry("Dennis", "en"),
- VoiceEntry("Ashley", "en"),
- VoiceEntry("Diego", "es"),
- VoiceEntry("Lupita", "es"),
+ _v("Josef", "de"),
+ _v("Johanna", "de"),
+ _v("Dennis", "en"),
+ _v("Ashley", "en"),
+ _v("Diego", "es"),
+ _v("Lupita", "es"),
),
),
ModelEntry(
@@ -102,7 +172,7 @@ _CATALOG: tuple[ModelEntry, ...] = (
latency_class="standard", # ~300-500 ms, chunked (no true WS streaming)
streaming=True,
voices=tuple(
- VoiceEntry(v)
+ _v(v)
for v in (
"Charon", "Kore", "Orus", "Iapetus", "Rasalgethi", "Algenib",
"Algieba", "Fenrir", "Aoede", "Zephyr", "Puck", "Leda",
@@ -121,11 +191,11 @@ _CATALOG: tuple[ModelEntry, ...] = (
latency_class="realtime",
streaming=True,
voices=(
- VoiceEntry("onwK4e9ZLuTAKqWW03F9"), # Daniel
- VoiceEntry("JBFqnCBsd6RMkjVDRZzb"), # George
- VoiceEntry("IKne3meq5aSn9XLyUdCD"), # Charlie
- VoiceEntry("nPczCjzI2devNBz1zQrb"), # Brian
- VoiceEntry("pNInz6obpgDQGcFmaJgB"), # Adam
+ _v("onwK4e9ZLuTAKqWW03F9"), # Daniel
+ _v("JBFqnCBsd6RMkjVDRZzb"), # George
+ _v("IKne3meq5aSn9XLyUdCD"), # Charlie
+ _v("nPczCjzI2devNBz1zQrb"), # Brian
+ _v("pNInz6obpgDQGcFmaJgB"), # Adam
),
),
ModelEntry(
@@ -136,7 +206,7 @@ _CATALOG: tuple[ModelEntry, ...] = (
latency_class="realtime",
streaming=True,
voices=tuple(
- VoiceEntry(v)
+ _v(v)
for v in (
"leo", "rex", "sal", "ara", "eve", "carina", "zagan", "helix",
"orion", "luna", "iris", "altair", "zenith", "perseus",
@@ -241,6 +311,52 @@ def allowed_voices(
return [v for v in m.voices if v.language in (short, MULTILINGUAL)]
+# OpenRouter serves other vendors' speech models; map the vendor prefix to the
+# native catalog family so voice-profile continuity works through the gateway.
+_OPENROUTER_VENDOR_FAMILY: dict[str, str] = {
+ "google/": "gemini-flash-tts",
+ "x-ai/": "grok-voice",
+}
+
+
+def continuity_voice(
+ family: str, gender: str, model_id: str | None = None
+) -> str | None:
+ """The curated voice of ``family`` that continues a given voice profile.
+
+ Used when a DIFFERENT provider has to take over mid-conversation (provider
+ fallback, cross-family key crossing, realtime→surface handover): instead of
+ the taking-over family's arbitrary default voice — which audibly flips e.g.
+ masculine→feminine and reads as "Jarvis suddenly changed voice" — the
+ caller asks for the first curated voice matching the active profile.
+
+ Only language-agnostic (multilingual) voices qualify: a fallback voice is
+ pinned once per wrapper and must be able to speak whatever language the
+ turn resolves to. Returns ``None`` when the family curates no matching
+ voice (caller keeps today's provider-default behavior).
+ """
+ fam = (family or "").strip().lower()
+ if fam == "openrouter":
+ mid = model_id or ""
+ fam = next(
+ (
+ mapped
+ for prefix, mapped in _OPENROUTER_VENDOR_FAMILY.items()
+ if mid.startswith(prefix)
+ ),
+ "",
+ )
+ if not fam:
+ return None
+ for m in _CATALOG:
+ if m.family != fam or m.status != "allowed":
+ continue
+ for v in m.voices:
+ if v.gender == gender and v.language == MULTILINGUAL:
+ return v.id
+ return None
+
+
def allowed_openrouter_model_ids(model_ids: list[str]) -> list[str]:
"""Filter a raw OpenRouter speech-model id list down to the allowed ones,
preserving input order. This is the boundary that drops the slop models
diff --git a/jarvis/plugins/tts/elevenlabs_tts.py b/jarvis/plugins/tts/elevenlabs_tts.py
index 77409d27ef..22b1f2d57a 100644
--- a/jarvis/plugins/tts/elevenlabs_tts.py
+++ b/jarvis/plugins/tts/elevenlabs_tts.py
@@ -310,6 +310,7 @@ class ElevenLabsTTS:
self.name,
allow_sapi5=self._allow_sapi5_fallback,
language_code=language_code,
+ reference_voice=self._default_voice,
)
if fb is not None:
produced = False
diff --git a/jarvis/plugins/tts/fallback_tts.py b/jarvis/plugins/tts/fallback_tts.py
index 0fcf9d20f3..22720136b0 100644
--- a/jarvis/plugins/tts/fallback_tts.py
+++ b/jarvis/plugins/tts/fallback_tts.py
@@ -38,9 +38,16 @@ class FallbackTTS:
the wrapped providers and never imports concrete plugin types.
"""
- def __init__(self, primary: Any, fallback: Any) -> None:
+ def __init__(
+ self, primary: Any, fallback: Any, fallback_voice: str | None = None
+ ) -> None:
self._primary = primary
self._fallback = fallback
+ # Voice-profile continuity (2026-07-17): the curated voice of the
+ # fallback FAMILY that matches the primary's active voice profile
+ # (masculine/feminine), computed by the factory. None → the fallback
+ # resolves its own default, exactly as before.
+ self._fallback_voice = (fallback_voice or "").strip() or None
# Surface the primary's identity so callers/logs see the active voice.
self.name = getattr(primary, "name", "fallback-tts")
self.supports_streaming = bool(getattr(primary, "supports_streaming", True))
@@ -122,14 +129,17 @@ class FallbackTTS:
) -> AsyncIterator[Any]:
"""Stream from the fallback provider.
- ``voice`` is intentionally NOT forwarded: the primary's voice name
- (e.g. Gemini "Charon") is invalid for a different provider (e.g. Grok
- expects "leo") and would trigger an HTTP 400. The fallback resolves its
- own default voice instead.
+ The primary's ``voice`` is never forwarded raw: its name (e.g. Gemini
+ "Charon") is invalid for a different provider (e.g. Grok expects
+ "leo") and would trigger an HTTP 400. Instead the factory pre-computes
+ ``fallback_voice`` — the fallback family's curated voice matching the
+ primary's voice PROFILE — so the takeover doesn't audibly flip e.g.
+ masculine→feminine mid-conversation. Without a match the fallback
+ resolves its own default voice, as before.
"""
try:
async for chunk in self._fallback.synthesize(
- text, voice=None, language_code=language_code
+ text, voice=self._fallback_voice, language_code=language_code
):
yield chunk
except Exception as exc: # noqa: BLE001
diff --git a/jarvis/plugins/tts/grok_voice_tts.py b/jarvis/plugins/tts/grok_voice_tts.py
index ecc851d192..b453a09dd2 100644
--- a/jarvis/plugins/tts/grok_voice_tts.py
+++ b/jarvis/plugins/tts/grok_voice_tts.py
@@ -369,6 +369,7 @@ class GrokVoiceTTS:
self.name,
allow_sapi5=self._allow_sapi5_fallback,
language_code=language_code,
+ reference_voice=self._default_voice,
)
if fb is not None:
produced = False
diff --git a/jarvis/plugins/tts/inworld_tts.py b/jarvis/plugins/tts/inworld_tts.py
index c3b9245f89..b8773e9bad 100644
--- a/jarvis/plugins/tts/inworld_tts.py
+++ b/jarvis/plugins/tts/inworld_tts.py
@@ -345,6 +345,7 @@ class InworldTTS:
self.name,
allow_sapi5=self._allow_sapi5_fallback,
language_code=language_code,
+ reference_voice=self._resolve_voice(text, None, language_code),
)
if fb is not None:
produced = False
diff --git a/tests/unit/plugins/tts/test_fallback_voice_continuity.py b/tests/unit/plugins/tts/test_fallback_voice_continuity.py
new file mode 100644
index 0000000000..42ff471602
--- /dev/null
+++ b/tests/unit/plugins/tts/test_fallback_voice_continuity.py
@@ -0,0 +1,221 @@
+"""Voice-profile continuity across TTS takeovers (2026-07-17).
+
+Bug: "the voice suddenly changes mid-conversation, masculine to feminine".
+Every takeover path — the ``FallbackTTS`` wrapper, the plugins' internal
+key-aware cross-family fallback — picked the taking-over family's arbitrary
+default/config voice with no regard for the voice that was just speaking.
+Live example (maintainer log 2026-07-11..16): primary OpenRouter spoke the
+masculine model default (config voice "eve" is a Grok name, silently
+replaced), then a 402/keyless failure crossed to Grok which spoke the
+feminine "eve" — an audible mid-conversation gender flip.
+
+Fix: curated gender tags in ``curated_catalog`` + ``continuity_voice``; the
+factory pins the fallback family's profile-matching voice on ``FallbackTTS``,
+and ``resolve_keyed_fallback`` accepts the failing provider's active voice as
+``reference_voice``. Unknown profiles keep today's behavior (fail-safe).
+"""
+from __future__ import annotations
+
+import pytest
+
+import jarvis.plugins.tts as factory
+from jarvis.plugins.tts import build_tts_from_config
+from jarvis.plugins.tts.curated_catalog import continuity_voice, voice_gender
+from jarvis.plugins.tts.fallback_tts import FallbackTTS
+
+# --- Curated gender register --------------------------------------------------
+
+def test_voice_gender_known_voices():
+ assert voice_gender("Fenrir") == "m" # Gemini Live (maintainer realtime)
+ assert voice_gender("Charon") == "m"
+ assert voice_gender("Kore") == "f"
+ assert voice_gender("leo") == "m"
+ assert voice_gender("eve") == "f"
+ assert voice_gender("Josef") == "m"
+ assert voice_gender("onwK4e9ZLuTAKqWW03F9") == "m" # ElevenLabs Daniel
+
+
+def test_voice_gender_is_case_insensitive_and_fail_safe():
+ assert voice_gender("fenrir") == "m"
+ assert voice_gender("EVE") == "f"
+ assert voice_gender("some-unknown-voice") is None
+ assert voice_gender("") is None
+ assert voice_gender(None) is None
+
+
+def test_continuity_voice_per_family():
+ assert continuity_voice("grok-voice", "m") == "leo"
+ assert continuity_voice("grok-voice", "f") == "ara"
+ assert continuity_voice("gemini-flash-tts", "m") == "Charon"
+ assert continuity_voice("gemini-flash-tts", "f") == "Kore"
+ # ElevenLabs curates only masculine prebuilt voices — feminine has no match.
+ assert continuity_voice("elevenlabs", "m") == "onwK4e9ZLuTAKqWW03F9"
+ assert continuity_voice("elevenlabs", "f") is None
+
+
+def test_continuity_voice_openrouter_resolves_vendor_prefix():
+ google = "google/gemini-3.1-flash-tts-preview"
+ assert continuity_voice("openrouter", "m", model_id=google) == "Charon"
+ assert continuity_voice("openrouter", "f", model_id=google) == "Kore"
+ assert continuity_voice("openrouter", "f", model_id="x-ai/grok-voice-tts-1.0") == "ara"
+ # No vendor mapping → no guess (caller keeps the model default).
+ assert continuity_voice("openrouter", "m", model_id="hexgrad/kokoro-82m") is None
+ assert continuity_voice("openrouter", "m", model_id=None) is None
+
+
+def test_continuity_voice_unknown_family_or_no_curated_voices():
+ assert continuity_voice("cartesia", "m") is None # ids not curated here
+ assert continuity_voice("sapi5", "m") is None
+ assert continuity_voice("", "m") is None
+
+
+def test_inworld_language_bound_voices_are_never_pinned():
+ # Inworld curates only language-bound voices; a pinned fallback voice must
+ # be able to speak ANY turn language, so no match is returned.
+ assert continuity_voice("inworld", "m") is None
+
+
+# --- Factory whitelists follow the curated catalog ----------------------------
+
+def test_factory_whitelists_cover_the_full_curated_roster():
+ # Regression: the old hand-maintained whitelists (9 Gemini / 5 Grok names)
+ # force-rewrote every OTHER legitimately picked voice to the family default
+ # — itself an unwanted voice change.
+ assert "Puck" in factory._GEMINI_VOICES
+ assert "Sulafat" in factory._GEMINI_VOICES
+ assert "luna" in factory._GROK_VOICES
+ assert "atlas" in factory._GROK_VOICES
+
+
+# --- FallbackTTS forwards the pinned continuity voice --------------------------
+
+class _FakeTTS:
+ supports_streaming = True
+
+ def __init__(self, name, *, chunks=1, raise_before=False):
+ self.name = name
+ self._chunks = chunks
+ self._raise_before = raise_before
+ self.synth_calls: list[tuple] = []
+
+ async def synthesize(self, text, voice=None, language_code=None):
+ self.synth_calls.append((text, voice, language_code))
+ if self._raise_before:
+ raise RuntimeError(f"{self.name} boom")
+ for i in range(self._chunks):
+ yield f"{self.name}-{i}"
+
+
+async def test_wrapper_pins_continuity_voice_on_fallback():
+ primary = _FakeTTS("primary", raise_before=True)
+ fallback = _FakeTTS("fallback", chunks=1)
+ wrapper = FallbackTTS(primary, fallback, fallback_voice="leo")
+ out = [c async for c in wrapper.synthesize("Hallo Welt.", language_code="de-DE")]
+ assert out == ["fallback-0"]
+ assert fallback.synth_calls[0][1] == "leo"
+
+
+async def test_wrapper_without_pin_keeps_provider_default():
+ primary = _FakeTTS("primary", raise_before=True)
+ fallback = _FakeTTS("fallback", chunks=1)
+ wrapper = FallbackTTS(primary, fallback)
+ [c async for c in wrapper.synthesize("Hallo Welt.", language_code="de-DE")]
+ assert fallback.synth_calls[0][1] is None
+
+
+# --- Factory wiring -------------------------------------------------------------
+
+class _Cfg:
+ """Maintainer regression case: OpenRouter primary with a contaminated
+ shared [tts] block — foreign model ("sonic-2" = Cartesia) and foreign
+ voice ("eve" = Grok). The primary coerces to the Google speech model and
+ speaks its masculine default; the Grok fallback would speak feminine
+ "eve"."""
+
+ provider = "openrouter-tts"
+ fallback = "grok-voice"
+ model = "sonic-2"
+ voice_de = "eve"
+ voice_en = "eve"
+ language_code = "auto"
+ style_prompt = ""
+ allow_sapi5_fallback = False
+ chunk_by_sentence = False
+ seed = 7
+ temperature = 0.7
+ use_vertex = False
+ vertex_project = None
+ vertex_location = "us-central1"
+ service_account_path = None
+ speed = 1.0
+ stability = 0.5
+ similarity_boost = 0.75
+ style = 0.0
+
+
+def _all_keys_present(monkeypatch):
+ """Keep the configured provider regardless of this host's real keys."""
+ monkeypatch.setattr(factory, "_tts_has_credential", lambda canonical, cfg: True)
+
+
+def test_factory_pins_masculine_grok_voice_for_masculine_primary(_all_keys_present):
+ tts = build_tts_from_config(_Cfg())
+ assert isinstance(tts, FallbackTTS)
+ # Primary effectively speaks "Charon" (m) → the Grok fallback must not
+ # speak "eve" (f); the factory pins the masculine Grok voice instead.
+ assert tts._fallback_voice == "leo"
+
+
+def test_factory_skips_pin_when_fallback_already_matches(_all_keys_present):
+ class _Coherent(_Cfg):
+ provider = "gemini-flash-tts"
+ model = "gemini-3.1-flash-tts-preview"
+ voice_de = "Charon"
+ voice_en = "Charon"
+
+ tts = build_tts_from_config(_Coherent())
+ assert isinstance(tts, FallbackTTS)
+ # Grok natively resolves Charon→leo (m), same profile → no override.
+ assert tts._fallback_voice is None
+
+
+def test_factory_pins_feminine_gemini_voice_for_feminine_grok_primary(_all_keys_present):
+ class _FemininePrimary(_Cfg):
+ provider = "grok-voice"
+ fallback = "gemini-flash-tts"
+ model = ""
+ voice_de = "eve"
+ voice_en = "eve"
+
+ tts = build_tts_from_config(_FemininePrimary())
+ assert isinstance(tts, FallbackTTS)
+ # Grok speaks "eve" (f); Gemini would default to "Charon" (m) → pin "Kore".
+ assert tts._fallback_voice == "Kore"
+
+
+# --- Key-aware internal fallback carries the reference profile -------------------
+
+def test_resolve_keyed_fallback_matches_reference_profile(monkeypatch):
+ monkeypatch.setattr(
+ factory, "_tts_has_credential",
+ lambda canonical, cfg: canonical == "grok-voice",
+ )
+ fb = factory.resolve_keyed_fallback(
+ "gemini-flash-tts", language_code="auto", reference_voice="Kore",
+ )
+ assert fb is not None and fb.name == "grok-voice"
+ # Feminine reference ("Kore") → the crossed-to Grok speaks "ara", not "leo".
+ assert fb._default_voice == "ara"
+
+
+def test_resolve_keyed_fallback_without_reference_keeps_defaults(monkeypatch):
+ monkeypatch.setattr(
+ factory, "_tts_has_credential",
+ lambda canonical, cfg: canonical == "grok-voice",
+ )
+ fb = factory.resolve_keyed_fallback("gemini-flash-tts", language_code="auto")
+ assert fb is not None and fb.name == "grok-voice"
+ assert fb._default_voice == "leo"