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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-03 08:18)

Ruben Lütke6c688deb54e4
diff --git a/jarvis/plugins/tts/openrouter_speech_models.py b/jarvis/plugins/tts/openrouter_speech_models.py
index 27c19dd30e..c0abf883fb 100644
--- a/jarvis/plugins/tts/openrouter_speech_models.py
+++ b/jarvis/plugins/tts/openrouter_speech_models.py
@@ -234,3 +234,108 @@ def voices_for_model_id(model_id: str | None) -> list[str]:
if not model_id:
return []
return list(MODEL_VOICES.get(model_id.strip(), ()))
+
+
+# ----------------------------------------------------------------------
+# Per-voice language classification (the single source of truth)
+# ----------------------------------------------------------------------
+#
+# The provider (``openrouter_tts.py``) and the voice-picker REST endpoint both
+# need to answer "what language does this voice speak?". Keeping that logic here
+# — in the pure, dependency-light module — means there is exactly ONE classifier
+# both call, so the wake/voice list and the UI language chips can never drift.
+
+# Sentinel language code for a voice that is language-AGNOSTIC (one voice speaks
+# any language). Not an ISO-639-1 code on purpose — the UI maps it to the 🌐
+# "Multilingual" chip.
+MULTILINGUAL = "multi"
+
+# Models whose voice ids carry NO language in them: Gemini + Grok ship
+# personality-named voices (Charon, Kore, leo, rex) and each voice is
+# multilingual. Listed explicitly so a coincidental prefix-looking name can
+# never be mis-tagged; every other model is classified per-voice from its
+# id prefix below.
+LANGUAGE_AGNOSTIC_MODELS: frozenset[str] = frozenset({
+ "google/gemini-3.1-flash-tts-preview",
+ "x-ai/grok-voice-tts-1.0",
+})
+
+# Kokoro's first-character language family (``af_`` a=English female,
+# ``ef_`` e=Spanish, ``ff_`` f=French, ...). Second char is gender (f/m).
+_KOKORO_FAMILY: dict[str, str] = {
+ "a": "en", "b": "en", "e": "es", "f": "fr", "h": "hi",
+ "i": "it", "j": "ja", "p": "pt", "z": "zh",
+}
+
+# Two-letter LOCALE/region prefixes (Voxtral: ``en_``, ``gb_``, ``fr_``) that
+# denote a spoken language rather than an ISO language code. ``gb``/``us``/``au``
+# are all English regions, so they normalise to ``en``; anything else falls
+# through as its own two-letter code.
+_LOCALE_TO_LANG: dict[str, str] = {"gb": "en", "us": "en", "au": "en"}
+
+
+def _voice_language_from_prefix(voice: str) -> str | None:
+ """The ISO-639-1 language a language-prefixed voice id speaks.
+
+ Returns ``None`` when the id carries NO recognisable language prefix (a
+ language-agnostic / multilingual voice such as Gemini "Charon" or Grok
+ "leo"). Handles the three prefix styles in the catalog:
+
+ * BCP-47-ish ``de-DE-Klaus`` / ``en-US-Harper:MAI-Voice-2`` (MAI-Voice),
+ * Kokoro ``af_``/``am_`` (English), ``ef_``/``em_`` (Spanish), ``ff_`` (French),
+ * a plain two-letter locale prefix ``en_``/``gb_``/``fr_`` (Voxtral).
+ """
+ v = (voice or "").lower()
+ # BCP-47-ish: first hyphen-separated token is a 2-letter language code.
+ if "-" in v and len(v.split("-", 1)[0]) == 2:
+ return v.split("-", 1)[0]
+ # Kokoro style: <family><gender>_... — gender char is 'f' or 'm'.
+ if len(v) >= 3 and v[1] in ("f", "m") and v[2] == "_":
+ return _KOKORO_FAMILY.get(v[0])
+ # Two-letter locale prefix like "en_", "gb_", "fr_".
+ if len(v) >= 3 and v[2] == "_" and v[0].isalpha() and v[1].isalpha():
+ code = v[:2]
+ return _LOCALE_TO_LANG.get(code, code)
+ return None
+
+
+def voice_matches_language(voice: str, short_lang: str) -> bool:
+ """Heuristic: does a language-prefixed voice id belong to ``short_lang``?
+
+ ``short_lang`` is a two-letter language code (``"de"``/``"en"``/``"es"``/…).
+ Returns ``True`` for a voice with no recognisable language prefix (it is
+ language-agnostic and fits any requested language), so a filter over a
+ language-agnostic model never narrows to empty. Single source of truth — the
+ provider's ``list_voices`` and the voice-picker endpoint both call it.
+ """
+ lang = _voice_language_from_prefix(voice)
+ if lang is None:
+ return True
+ return lang == (short_lang or "").lower().split("-", 1)[0]
+
+
+def voice_language(model_id: str | None, voice: str) -> str:
+ """The language a single voice speaks, as an ISO-639-1 code or ``"multi"``.
+
+ * A voice of a language-AGNOSTIC model (Gemini, Grok) → :data:`MULTILINGUAL`.
+ * A language-prefixed voice (Kokoro ``af_``→``en`` / ``ef_``→``es``,
+ MAI-Voice ``de-DE-``→``de``, Voxtral ``fr_``→``fr``) → its ISO code.
+ * A voice with no recognisable prefix (a language-agnostic voice on any
+ model) → :data:`MULTILINGUAL`.
+ """
+ if (model_id or "") in LANGUAGE_AGNOSTIC_MODELS:
+ return MULTILINGUAL
+ return _voice_language_from_prefix(voice) or MULTILINGUAL
+
+
+def voice_entries_for_model(model_id: str | None) -> list[dict[str, str]]:
+ """Per-voice ``{"id", "language"}`` entries for a model id (sync, offline).
+
+ ``language`` is an ISO-639-1 code or ``"multi"`` (see :func:`voice_language`).
+ Empty list for an unknown model id. Feeds the voice picker after a TTS model
+ is chosen.
+ """
+ return [
+ {"id": v, "language": voice_language(model_id, v)}
+ for v in voices_for_model_id(model_id)
+ ]
diff --git a/jarvis/plugins/tts/openrouter_tts.py b/jarvis/plugins/tts/openrouter_tts.py
index deb6be43f2..e7f6efc294 100644
--- a/jarvis/plugins/tts/openrouter_tts.py
+++ b/jarvis/plugins/tts/openrouter_tts.py
@@ -36,6 +36,7 @@ from jarvis.plugins.tts.openrouter_speech_models import (
MODEL_DEFAULT_VOICE,
MODEL_VOICES,
coerce_speech_model,
+ voice_matches_language,
)
log = logging.getLogger("jarvis.tts.openrouter")
@@ -201,7 +202,7 @@ class OpenRouterTTS:
return [dv] if dv else []
if language:
short = language.lower().split("-", 1)[0]
- narrowed = [v for v in voices if _voice_matches_language(v, short)]
+ narrowed = [v for v in voices if voice_matches_language(v, short)]
if narrowed:
return narrowed
return voices
@@ -286,27 +287,3 @@ class OpenRouterTTS:
timestamp_ns=0,
channels=1,
)
-
-
-def _voice_matches_language(voice: str, short_lang: str) -> bool:
- """Heuristic: does a language-prefixed voice id belong to ``short_lang``?
-
- Handles the two prefix styles in the catalog: BCP-47-ish (``de-DE-Klaus``)
- and Kokoro's two-letter locale prefix (``de_``, ``af_``/``am_``/``bf_``/
- ``bm_`` = English, ``ef_``/``em_`` = Spanish, ``ff_`` = French, ...). Returns
- True for voices with no recognisable language prefix (language-agnostic).
- """
- v = voice.lower()
- if "-" in v and len(v.split("-", 1)[0]) == 2:
- return v.startswith(short_lang + "-")
- # Kokoro style: first char = language family, second = gender, then "_".
- kokoro_family = {
- "a": "en", "b": "en", "e": "es", "f": "fr", "h": "hi",
- "i": "it", "j": "ja", "p": "pt", "z": "zh",
- }
- if len(v) >= 3 and v[1] in ("f", "m") and v[2] == "_":
- return kokoro_family.get(v[0]) == short_lang
- if len(v) >= 3 and v[2] == "_" and v[0].isalpha() and v[1].isalpha():
- # Two-letter locale prefix like "de_", "en_", "fr_".
- return v[:2] == short_lang
- return True
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index f75b958d0e..521bbd4126 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -20,7 +20,7 @@ import logging
import time
from typing import Any, Literal, get_args
-from fastapi import APIRouter, HTTPException, Request
+from fastapi import APIRouter, HTTPException, Request, Response
from pydantic import BaseModel, Field
from jarvis.brain import provider_test as _provider_test
@@ -1509,6 +1509,207 @@ async def tts_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
}
+# ----------------------------------------------------------------------
+# Per-model VOICE picker + audio preview (OpenRouter TTS)
+# ----------------------------------------------------------------------
+#
+# A TTS model (Gemini Flash TTS, Kokoro, MAI-Voice, ...) ships its OWN set of
+# voices, each speaking a specific language (or multilingual). These two routes
+# feed the desktop voice picker: list the chosen model's voices tagged by
+# language, and synthesise a short spoken sample so the user can HEAR a voice
+# before committing. The provider id is always ``openrouter-tts`` today; the
+# routes 400 for any other id rather than guessing.
+
+# The only TTS provider that exposes a per-model voice list + preview so far.
+_VOICE_PICKER_PROVIDER = "openrouter-tts"
+
+# The short fixed sentence spoken by the preview, per language. Deliberately
+# tiny so a preview is cheap and quick. Every supported runtime-output language
+# has an entry (never a de/en-only table — AP-21 / runtime-language doctrine).
+_TTS_PREVIEW_SAMPLES: dict[str, str] = {
+ "de": "Hallo, ich bin dein Assistent.",
+ "en": "Hi, I am your assistant.",
+ "es": "Hola, soy tu asistente.",
+}
+_TTS_PREVIEW_DEFAULT_LANG = "en"
+
+
+def _pcm_to_wav(pcm: bytes, *, sample_rate: int, channels: int = 1) -> bytes:
+ """Wrap int16 little-endian PCM in a minimal in-memory WAV container.
+
+ Mirrors ``jarvis.plugins.stt.openrouter_stt._wrap_pcm_as_wav`` so an
+ ``<audio>`` element can play the OpenRouter TTS stream (raw 24 kHz mono
+ s16le PCM) directly without a client-side decoder.
+ """
+ import io
+ import wave
+
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as wav:
+ wav.setnchannels(max(1, channels))
+ wav.setsampwidth(2) # int16
+ wav.setframerate(sample_rate)
+ wav.writeframes(pcm)
+ return buf.getvalue()
+
+
+class TtsVoiceEntry(BaseModel):
+ id: str
+ # ISO-639-1 code ("en"/"de"/"es"/"fr"/…) or "multi" for a multilingual /
+ # voice-agnostic model. The UI maps it to a flag chip (unknown → the code).
+ language: str
+
+
+class TtsVoicesResponse(BaseModel):
+ provider: str
+ model: str
+ voices: list[TtsVoiceEntry]
+ # The model's own safe default voice (used to pre-select the picker).
+ default: str = ""
+ # The voice currently persisted in [tts] IF it is valid for this model,
+ # else "" (a stale voice from another model shows the placeholder instead).
+ current: str = ""
+
+
[email protected]("/tts/voices")
+async def list_tts_voices(
+ request: Request, provider: str = _VOICE_PICKER_PROVIDER, model: str = ""
+) -> TtsVoicesResponse:
+ """Voices for a TTS model, each tagged with its spoken language.
+
+ Feeds the voice picker after a model is chosen. ``language`` is an ISO-639-1
+ code or ``"multi"`` (multilingual / voice-agnostic model). Only
+ ``openrouter-tts`` exposes a per-model voice list today; any other provider
+ id is a clean 400.
+ """
+ if provider != _VOICE_PICKER_PROVIDER:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"Per-model voices are only available for '{_VOICE_PICKER_PROVIDER}' "
+ f"(got {provider!r})."
+ ),
+ )
+ from jarvis.plugins.tts.openrouter_speech_models import (
+ MODEL_DEFAULT_VOICE,
+ coerce_speech_model,
+ voice_entries_for_model,
+ )
+
+ resolved = coerce_speech_model(model)
+ entries = voice_entries_for_model(resolved)
+ default = MODEL_DEFAULT_VOICE.get(resolved, "") or (
+ entries[0]["id"] if entries else ""
+ )
+ # Reflect the persisted voice only when it belongs to THIS model, so the
+ # picker never shows a stale voice from a previously selected model.
+ cfg = _resolve_cfg(request)
+ persisted = getattr(getattr(cfg, "tts", None), "voice_de", "") or ""
+ valid_ids = {e["id"] for e in entries}
+ current = persisted if persisted in valid_ids else ""
+ return TtsVoicesResponse(
+ provider=provider,
+ model=resolved,
+ voices=[TtsVoiceEntry(**e) for e in entries],
+ default=default,
+ current=current,
+ )
+
+
+class TtsVoiceBody(BaseModel):
+ # Empty is not meaningful here — a voice must be chosen. Bounded like the
+ # other selection bodies.
+ voice: str = Field(default="", max_length=200)
+ persist: bool = Field(default=True)
+
+
[email protected]("/tts/voice")
+async def set_tts_voice_selection(
+ body: TtsVoiceBody, request: Request
+) -> BrainModelSaveResponse:
+ """Persist + live-apply the global TTS voice (``[tts] voice_de``/``voice_en``).
+
+ A TTS model ships several voices; this pins the chosen one. Reuses the shared
+ ``_apply_tts_selection`` path (config-soll-synced write + a live rebuild of
+ the running SpeechPipeline's TTS) so the next spoken turn uses it without a
+ restart when voice is active.
+ """
+ voice = body.voice.strip()
+ if not voice:
+ raise HTTPException(status_code=400, detail="A voice id is required.")
+ return _apply_tts_selection(
+ _VOICE_PICKER_PROVIDER,
+ voice,
+ "voice",
+ BrainModelBody(model=voice, persist=body.persist),
+ request,
+ )
+
+
+class TtsPreviewBody(BaseModel):
+ provider: str = Field(default=_VOICE_PICKER_PROVIDER)
+ model: str = Field(default="", max_length=200)
+ voice: str = Field(default="", max_length=200)
+ # The sample language to speak ("de" | "en" | "es"). Falls back to English.
+ language: str = Field(default=_TTS_PREVIEW_DEFAULT_LANG, max_length=16)
+
+
[email protected]("/tts/preview")
+async def tts_preview(body: TtsPreviewBody) -> Response:
+ """Synthesise a SHORT spoken sample with the given model + voice.
+
+ Returns ``audio/wav`` bytes (24 kHz mono s16le wrapped in a WAV container) so
+ an ``<audio>`` element can play it directly. Kept cheap: one tiny fixed
+ sentence. Any failure (no key / 4xx / transport) is a clean 4xx/5xx JSON
+ error — never a 500 that breaks the page — so the picker can show a toast.
+ """
+ if body.provider != _VOICE_PICKER_PROVIDER:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"Preview is only available for '{_VOICE_PICKER_PROVIDER}' "
+ f"(got {body.provider!r})."
+ ),
+ )
+ lang = (body.language or _TTS_PREVIEW_DEFAULT_LANG).lower().split("-", 1)[0]
+ sample = _TTS_PREVIEW_SAMPLES.get(lang, _TTS_PREVIEW_SAMPLES[_TTS_PREVIEW_DEFAULT_LANG])
+
+ from jarvis.plugins.tts.openrouter_speech_models import coerce_speech_model
+ from jarvis.plugins.tts.openrouter_tts import (
+ OPENROUTER_TTS_SAMPLE_RATE,
+ OpenRouterTTS,
+ OpenRouterTTSError,
+ )
+
+ model = coerce_speech_model(body.model)
+ voice = body.voice.strip() or None
+ tts = OpenRouterTTS(model=model)
+ pcm = bytearray()
+ try:
+ async for chunk in tts.synthesize(sample, voice=voice, language_code=lang):
+ pcm += bytes(chunk.pcm)
+ except OpenRouterTTSError as exc:
+ # No key / 401 / 402 / 429 / transport — the message is already clear
+ # English; surface it as a 502 so the picker shows an honest toast.
+ raise HTTPException(status_code=502, detail=f"Voice preview failed: {exc}") from exc
+ except Exception as exc: # noqa: BLE001 — never 500 the page
+ raise HTTPException(
+ status_code=500,
+ detail=f"Voice preview error: {type(exc).__name__}: {exc}",
+ ) from exc
+ finally:
+ await tts.aclose()
+
+ if not pcm:
+ raise HTTPException(status_code=502, detail="Voice preview produced no audio.")
+ wav = _pcm_to_wav(bytes(pcm), sample_rate=OPENROUTER_TTS_SAMPLE_RATE, channels=1)
+ return Response(
+ content=wav,
+ media_type="audio/wav",
+ headers={"Cache-Control": "no-store"},
+ )
+
+
@router.post("/stt/switch")
async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"""Wechselt den aktiven STT-Provider. Persistiert in jarvis.toml (tomlkit).