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-02 20:23)

Ruben Lütke0a6d34f0ba1b
diff --git a/jarvis/cu/engine.py b/jarvis/cu/engine.py
index 2faa960bfc..97aa83e211 100644
--- a/jarvis/cu/engine.py
+++ b/jarvis/cu/engine.py
@@ -577,7 +577,10 @@ async def run_cu_loop(
# 2026-07-02); window-scoped capture covers the grounding need untouched.
normalize_window = bool(getattr(ctx, "normalize_window", False))
coordinate_space = str(getattr(ctx, "coordinate_space", "auto") or "auto")
- settle_scale = float(getattr(ctx, "settle_scale", 1.0) or 1.0)
+ # NOTE: no `or 1.0` here — a configured 0 means "no settle waits" (tests,
+ # speed runs) and must be honored, not silently coerced back to 1.0.
+ raw_settle = getattr(ctx, "settle_scale", None)
+ settle_scale = 1.0 if raw_settle is None else float(raw_settle)
strict_verify = bool(getattr(ctx, "strict_verify", True))
image_cfg = _ImageCfg(
max_dimension=int(getattr(ctx, "image_max_dimension", 1366) or 1366),
@@ -960,7 +963,10 @@ async def run_cu_loop(
if pre is not None and post is not None and frames_differ(pre, post):
detail = (detail + " — screen reacted elsewhere").strip()
- elif await verify_click_focus_point(*resolved_xy) is True:
+ elif await verify_click_focus_point(
+ *resolved_xy,
+ capture_area=monitor.width * monitor.height,
+ ) is True:
# Zero pixel change because the target was
# ALREADY in the desired state: the click point
# sits inside the control that holds keyboard
diff --git a/jarvis/cu/verify.py b/jarvis/cu/verify.py
index d0213d01b1..499e420e5d 100644
--- a/jarvis/cu/verify.py
+++ b/jarvis/cu/verify.py
@@ -116,25 +116,39 @@ def typed_text_landed(nodes: tuple, typed: str) -> bool | None:
return False if focused_editable_seen else None
-#: Roles that are CONTAINERS, not controls — focus reported on one of these
-#: (a browser window, a web view, a panel) is NOT evidence that a click hit
-#: its intended target: accepting it would rescue every in-window miss and
-#: neuter the effect-check. Covers all three role vocabularies (UIA / AX /
-#: AT-SPI), since the point resolver returns platform-native role names.
+#: Roles that are CONTAINERS or large regions, not controls — focus reported
+#: on one of these (a browser window, a web view, a list, a document body)
+#: is NOT evidence that a click hit its intended target: accepting it would
+#: rescue genuine in-window misses and neuter the effect-check. Covers all
+#: three role vocabularies (UIA / AX / AT-SPI), since the point resolver
+#: returns platform-native role names. (Extended per the 2026-07-02
+#: adversarial review: lists/tables/toolbars and the AT-SPI document-canvas
+#: family were missing.)
_FOCUS_CONTAINER_ROLES = frozenset({
# UIA (also the mapped vocabulary of the walked tree nodes)
"Window", "Pane", "Document", "Group", "Custom", "TitleBar",
+ "List", "Tree", "DataGrid", "Table", "ToolBar", "MenuBar",
# macOS AX
"AXWindow", "AXSheet", "AXGroup", "AXScrollArea", "AXWebArea",
- "AXApplication", "AXDrawer",
+ "AXApplication", "AXDrawer", "AXList", "AXTable", "AXOutline",
+ "AXToolbar", "AXTabGroup", "AXSplitGroup", "AXLayoutArea",
# AT-SPI role names
"frame", "window", "panel", "application", "document frame",
- "document web", "filler",
+ "document web", "filler", "list", "table", "tree", "tree table",
+ "tool bar", "menu bar", "scroll pane", "viewport", "page tab list",
+ "document text", "document spreadsheet", "document presentation",
+ "document email",
})
+#: A focused element LARGER than this fraction of the capture area is a
+#: region, not a control — its focus is not click-target evidence (same
+#: container-trap reasoning as the snap cap in
+#: :data:`_SNAP_MAX_AREA_FRACTION`). Applied wherever bounds are known.
+_FOCUS_MAX_AREA_FRACTION = 0.15
+
def click_point_in_focused_element(
- nodes: tuple, x: int, y: int,
+ nodes: tuple, x: int, y: int, *, capture_area: int | None = None,
) -> bool | None:
"""Did the click point land inside the CONTROL holding keyboard focus?
@@ -148,15 +162,23 @@ def click_point_in_focused_element(
nothing visibly changed. Works on all three platforms (UIA / AX /
AT-SPI bounds are screen input units).
- Container roles never count (:data:`_FOCUS_CONTAINER_ROLES`): a focused
- WINDOW containing the point says nothing about the click's target.
+ Two container traps never count as evidence (a focused WINDOW/region
+ containing the point says nothing about the click's target, and would
+ also skip the zoom-refine retry a real miss deserves):
+ * role in :data:`_FOCUS_CONTAINER_ROLES`;
+ * element area above :data:`_FOCUS_MAX_AREA_FRACTION` of
+ ``capture_area`` (when the caller provides one).
- ``True`` — a focused non-container element's bounds contain the point.
+ ``True`` — a focused control-sized element's bounds contain the point.
``False`` — nodes are readable, no qualifying element contains the point.
``None`` — no nodes readable (cannot tell).
"""
if not nodes:
return None
+ max_area = (
+ max(1, int(capture_area * _FOCUS_MAX_AREA_FRACTION))
+ if capture_area else None
+ )
for node in nodes:
if not getattr(node, "focused", False):
continue
@@ -169,6 +191,8 @@ def click_point_in_focused_element(
bx, by, bw, bh = (int(v) for v in bounds)
except (TypeError, ValueError):
continue
+ if max_area is not None and bw * bh > max_area:
+ continue
if bw > 0 and bh > 0 and bx <= x < bx + bw and by <= y < by + bh:
return True
return False
@@ -388,7 +412,9 @@ async def verify_click_focus(name: str) -> bool | None:
return element_is_focused(tuple(getattr(obs, "nodes", ()) or ()), name)
-async def verify_click_focus_point(x: int, y: int) -> bool | None:
+async def verify_click_focus_point(
+ x: int, y: int, *, capture_area: int | None = None,
+) -> bool | None:
"""Is the element at ``(x, y)`` the focused control? Error → ``None``.
Two evidence paths, positive-only, both cross-platform:
@@ -400,9 +426,13 @@ async def verify_click_focus_point(x: int, y: int) -> bool | None:
2. Fallback: scan the walked foreground tree
(:func:`click_point_in_focused_element`).
- Container focus never counts (:data:`_FOCUS_CONTAINER_ROLES`). Runs
- ONLY on the click-miss path (no happy-path latency): the engine
- consults it before declaring a zero-pixel-change click a miss.
+ Container focus never counts (:data:`_FOCUS_CONTAINER_ROLES`), and a
+ focused element larger than :data:`_FOCUS_MAX_AREA_FRACTION` of
+ ``capture_area`` is a region, not a target (applied where bounds are
+ known — the macOS/Linux hit-test reports no bounds yet and relies on
+ the role deny-list). Runs ONLY on the click-miss path (no happy-path
+ latency): the engine consults it before declaring a zero-pixel-change
+ click a miss.
"""
try:
element = await asyncio.wait_for(
@@ -417,7 +447,14 @@ async def verify_click_focus_point(x: int, y: int) -> bool | None:
and str(getattr(element, "role", "") or "")
not in _FOCUS_CONTAINER_ROLES
):
- return True
+ bounds = getattr(element, "bounds", None) or (0, 0, 0, 0)
+ area = max(0, int(bounds[2])) * max(0, int(bounds[3]))
+ if (
+ not capture_area
+ or area == 0 # backend reports no bounds: role filter decides
+ or area <= max(1, int(capture_area * _FOCUS_MAX_AREA_FRACTION))
+ ):
+ return True
try:
obs = await asyncio.wait_for(
_get_ui_tree_source().observe(), timeout=UIA_TIMEOUT_S,
@@ -426,6 +463,7 @@ async def verify_click_focus_point(x: int, y: int) -> bool | None:
return None
return click_point_in_focused_element(
tuple(getattr(obs, "nodes", ()) or ()), int(x), int(y),
+ capture_area=capture_area,
)
diff --git a/jarvis/platform/monitors.py b/jarvis/platform/monitors.py
index 13c71bc538..1021bb84f2 100644
--- a/jarvis/platform/monitors.py
+++ b/jarvis/platform/monitors.py
@@ -123,17 +123,40 @@ def virtual_desktop_bounds() -> tuple[int, int, int, int] | None:
def _win_virtual_bounds() -> tuple[int, int, int, int] | None:
- """SM_*VIRTUALSCREEN metrics (physical px once the process is declared
- per-monitor DPI aware — the idempotent declaration runs first so an
- unaware host process does not read virtualized 96-dpi values)."""
+ """SM_*VIRTUALSCREEN metrics in physical pixels.
+
+ Uses a THREAD-scoped per-monitor DPI pin (restored afterwards) so the
+ metrics are not DPI-virtualized even in an unaware host process. A
+ process-wide awareness flip is deliberately NOT performed here — this is
+ a read-only getter reached from always-on tree sources, and mutating
+ process awareness as a side effect would race pywebview's own
+ declaration (2026-07-02 review finding, AP-9 class). The CU engine
+ declares the process context itself at mission start.
+ """
import ctypes # noqa: PLC0415
- from jarvis.core.win32_dpi import ensure_dpi_awareness # noqa: PLC0415
-
- ensure_dpi_awareness()
- gsm = ctypes.windll.user32.GetSystemMetrics
- # SM_XVIRTUALSCREEN=76, SM_YVIRTUALSCREEN=77, SM_CX=78, SM_CY=79
- left, top, width, height = gsm(76), gsm(77), gsm(78), gsm(79)
+ set_ctx = None
+ prev = None
+ try:
+ set_ctx = ctypes.windll.user32.SetThreadDpiAwarenessContext
+ set_ctx.restype = ctypes.c_void_p
+ set_ctx.argtypes = [ctypes.c_void_p]
+ for context in (-4, -3): # PER_MONITOR_AWARE_V2, then V1 (1607)
+ prev = set_ctx(ctypes.c_void_p(context))
+ if prev is not None:
+ break
+ except (OSError, AttributeError): # pre-1607: read unpinned
+ set_ctx = None
+ try:
+ gsm = ctypes.windll.user32.GetSystemMetrics
+ # SM_XVIRTUALSCREEN=76, SM_YVIRTUALSCREEN=77, SM_CX=78, SM_CY=79
+ left, top, width, height = gsm(76), gsm(77), gsm(78), gsm(79)
+ finally:
+ if set_ctx is not None and prev is not None:
+ try:
+ set_ctx(ctypes.c_void_p(prev))
+ except Exception: # noqa: BLE001 — restore is best-effort
+ pass
if width <= 0 or height <= 0:
return None
return (int(left), int(top), int(width), int(height))
@@ -162,7 +185,13 @@ def _macos_virtual_bounds() -> tuple[int, int, int, int] | None:
def _x11_virtual_bounds() -> tuple[int, int, int, int] | None:
- """X11 root-window geometry (the root spans all monitors)."""
+ """X11 root-window geometry (the root spans all monitors).
+
+ Known limitation: on the legacy separate-X-screens ("Zaphod") multihead
+ layout ``xdotool getdisplaygeometry`` reports only screen 0 — callers
+ keep their conservative fallback there. Modern XRandR/Xinerama setups
+ (one logical screen) report the full span.
+ """
if shutil.which("xdotool") is None:
return None
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: PLC0415
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index edd8822f6e..b15906d031 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -28,8 +28,10 @@ ENTRY_POINT_GROUP = "jarvis.stt"
_STT_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {
"groq-api": (("groq_api_key", "GROQ_API_KEY"),),
# OpenRouter STT reuses the SAME key slot as the OpenRouter brain, so a user
- # who configured OpenRouter for chat gets cloud STT for free.
- "openrouter": (("openrouter_api_key", "OPENROUTER_API_KEY"),),
+ # who configured OpenRouter for chat gets cloud STT for free. The id is
+ # ``openrouter-stt`` (distinct from the ``openrouter`` brain id) to avoid a
+ # collision in the shared model-catalog / provider-spec namespaces.
+ "openrouter-stt": (("openrouter_api_key", "OPENROUTER_API_KEY"),),
"openai-api": (("openai_api_key", "OPENAI_API_KEY"),),
"deepgram": (("deepgram_api_key", "DEEPGRAM_API_KEY"),),
"deepgram-flux": (("deepgram_api_key", "DEEPGRAM_API_KEY"),),
diff --git a/jarvis/plugins/stt/openrouter_stt.py b/jarvis/plugins/stt/openrouter_stt.py
index 3eeeb85083..ef8c682998 100644
--- a/jarvis/plugins/stt/openrouter_stt.py
+++ b/jarvis/plugins/stt/openrouter_stt.py
@@ -90,9 +90,17 @@ class Transcript:
class OpenRouterSTT:
- """OpenRouter-hosted cloud STT (non-streaming, JSON transcription API)."""
+ """OpenRouter-hosted cloud STT (non-streaming, JSON transcription API).
+
+ The provider id is ``openrouter-stt`` (NOT ``openrouter``) on purpose: the
+ OpenRouter *brain* already owns the ``openrouter`` id in the shared model-
+ catalog and provider-spec namespaces, so the STT variant takes a distinct id
+ — mirroring the repo's own ``openai`` (brain) vs ``openai-api`` (STT) split.
+ The underlying credential (``openrouter_api_key``) is still SHARED with the
+ brain, so no second key is needed.
+ """
- name = "openrouter"
+ name = "openrouter-stt"
supports_streaming = False
def __init__(
@@ -309,24 +317,22 @@ def _model_output_modalities(model: Any) -> tuple[str, ...] | None:
``None`` when the field is absent/unusable (→ treated as not-transcription).
"""
# 1) Object with an ``output_modalities`` attribute (e.g. ModelInfo).
- attr = getattr(model, "output_modalities", None)
- if attr is not None and not isinstance(model, dict):
- return tuple(str(x) for x in attr) if _is_seq(attr) else None
-
- if isinstance(model, dict):
- arch = model.get("architecture")
- if isinstance(arch, dict):
- mods = arch.get("output_modalities")
- if _is_seq(mods):
- return tuple(str(x) for x in mods)
- flat = model.get("output_modalities")
- if _is_seq(flat):
- return tuple(str(x) for x in flat)
- return None
-
+ if not isinstance(model, dict):
+ attr = getattr(model, "output_modalities", None)
+ if isinstance(attr, (list, tuple)):
+ return tuple(str(x) for x in attr)
+ return None
-def _is_seq(value: Any) -> bool:
- return isinstance(value, (list, tuple))
+ # 2) Raw OpenRouter ``/v1/models`` entry dict.
+ arch = model.get("architecture")
+ if isinstance(arch, dict):
+ mods = arch.get("output_modalities")
+ if isinstance(mods, (list, tuple)):
+ return tuple(str(x) for x in mods)
+ flat = model.get("output_modalities")
+ if isinstance(flat, (list, tuple)):
+ return tuple(str(x) for x in flat)
+ return None
def is_transcription_model(model: Any) -> bool:
diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.py
index 8bfe94c77c..2d131a5ea8 100644
--- a/jarvis/plugins/tts/__init__.py
+++ b/jarvis/plugins/tts/__init__.py
@@ -36,6 +36,9 @@ _GROK_TTS_ALIASES = frozenset({
"grok-voice", "grok_voice", "grok-tts", "xai-tts", "xai-voice",
})
_GEMINI_TTS_ALIASES = frozenset({"gemini-flash-tts", "gemini-flash", "gemini"})
+_OPENROUTER_TTS_ALIASES = frozenset({
+ "openrouter", "openrouter-tts", "openrouter_tts", "open-router-tts",
+})
# Credential candidates per TTS family — the (keyring_key, env_var) pairs that
# hold a usable key, matching what each plugin's own key lookup reads. A fresh
@@ -57,13 +60,17 @@ _TTS_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {
("xai_api_key", "XAI_API_KEY"),
("grok_api_key", "GROK_API_KEY"),
),
+ # OpenRouter TTS reuses the ONE OpenRouter key shared with the brain /
+ # Jarvis-Agent providers — a fresh downloader whose only credential is an
+ # OpenRouter key (a gateway to many models) gets working voice for free.
+ "openrouter": (("openrouter_api_key", "OPENROUTER_API_KEY"),),
}
# Cross-family probe order when the configured provider has no key: the family
# the maintainer ships first, then the common BYO-key alternatives. Only a family
# that actually has a key is ever chosen.
_TTS_CROSS_FAMILY_ORDER: tuple[str, ...] = (
- "gemini-flash-tts", "elevenlabs", "cartesia", "grok-voice",
+ "gemini-flash-tts", "elevenlabs", "cartesia", "grok-voice", "openrouter",
)
@@ -78,6 +85,8 @@ def _canonical_tts_name(name: str) -> str:
return "grok-voice"
if n in _GEMINI_TTS_ALIASES:
return "gemini-flash-tts"
+ if n in _OPENROUTER_TTS_ALIASES:
+ return "openrouter"
return n
@@ -322,6 +331,28 @@ def _build_provider(tts_cfg: Any, provider: str) -> Any:
allow_sapi5_fallback=allow_sapi5,
)
+ if provider in ("openrouter", "openrouter-tts", "openrouter_tts", "open-router-tts"):
+ try:
+ from jarvis.plugins.tts.openrouter_speech_models import DEFAULT_MODEL
+ from jarvis.plugins.tts.openrouter_tts import OpenRouterTTS
+ except ImportError as exc:
+ raise RuntimeError(
+ f"TTS provider 'openrouter' configured, but the plugin is not "
+ f"importable: {exc}. Check that "
+ f"jarvis/plugins/tts/openrouter_tts.py exists and httpx is "
+ f"installed.",
+ ) from exc
+ # OpenRouter TTS validates its own voices per selected model, so the
+ # config voice_de / voice_en are passed straight through (a foreign name
+ # is auto-corrected to the model default inside the plugin).
+ return OpenRouterTTS(
+ model=tts_cfg.model or DEFAULT_MODEL,
+ voice_de=getattr(tts_cfg, "voice_de", None),
+ voice_en=getattr(tts_cfg, "voice_en", None),
+ language=tts_cfg.language_code or "auto",
+ speed=tts_cfg.speed,
+ )
+
if provider not in ("gemini-flash-tts", "gemini-flash", "gemini"):
log.warning(
"Unknown TTS provider %r — falling back to gemini-flash-tts.",
diff --git a/jarvis/plugins/tts/openrouter_speech_models.py b/jarvis/plugins/tts/openrouter_speech_models.py
index 1fc73a209d..708ea6280b 100644
--- a/jarvis/plugins/tts/openrouter_speech_models.py
+++ b/jarvis/plugins/tts/openrouter_speech_models.py
@@ -125,7 +125,7 @@ MODEL_VOICES: dict[str, tuple[str, ...]] = {
# picker offline / when the live ``?output_modalities=speech`` fetch is
# unreachable — mirroring how ``CURATED_MODELS`` backs the brain picker.
CURATED_SPEECH_MODELS: tuple[tuple[str, str], ...] = (
- ("google/gemini-3.1-flash-tts-preview", "Google: Gemini 3.1 Flash TTS (multilingual, recommended)"),
+ ("google/gemini-3.1-flash-tts-preview", "Google: Gemini 3.1 Flash TTS (multilingual)"),
("hexgrad/kokoro-82m", "hexgrad: Kokoro 82M (cheapest, English)"),
("x-ai/grok-voice-tts-1.0", "xAI: Grok Voice TTS 1.0"),
("microsoft/mai-voice-2", "Microsoft: MAI-Voice-2"),
diff --git a/jarvis/plugins/tts/openrouter_tts.py b/jarvis/plugins/tts/openrouter_tts.py
new file mode 100644
index 0000000000..ce95a9bc9b
--- /dev/null
+++ b/jarvis/plugins/tts/openrouter_tts.py
@@ -0,0 +1,301 @@
+"""OpenRouter Text-to-Speech plugin (OpenAI Audio-Speech compatible).
+
+One OpenRouter API key — the SAME ``openrouter_api_key`` the OpenRouter brain /
+Jarvis-Agent providers already use — reaches every speech-synthesis model
+OpenRouter hosts (Gemini Flash TTS, Grok Voice, Microsoft MAI-Voice, Mistral
+Voxtral, Kokoro, Orpheus, Zonos, Sesame CSM, ...).
+
+Endpoint (verified live 2026-07-02):
+ ``POST https://openrouter.ai/api/v1/audio/speech`` — OpenAI-compatible.
+ Body ``{"model","input","voice","response_format":"pcm"|"mp3","speed"?}``.
+ ``response_format`` accepts ONLY ``"mp3"`` and ``"pcm"`` (``wav`` is rejected
+ with a Zod validation error). We request ``pcm`` and the endpoint answers with
+ ``Content-Type: audio/pcm;rate=24000;channels=1`` — raw 16-bit signed
+ little-endian mono PCM at 24 kHz, i.e. EXACTLY the format the Jarvis playback
+ pipeline consumes (same as Gemini / Grok / Cartesia), so no decode and no
+ resample is needed. Streaming is real chunked-transfer over ``aiter_bytes``, so
+ the first audio frame leaves as soon as the provider flushes it.
+
+Error contract (open-source AP-22 resilience): a fatal error (missing key,
+401/402/403/429, or a transport failure) is raised BEFORE the first
+``AudioChunk`` is yielded. The provider-level ``FallbackTTS`` wrapper catches a
+pre-first-chunk failure and crosses to the configured fallback voice, so a dead
+/ keyless / rate-limited OpenRouter never bricks the TTS tier. Once audio has
+started we re-raise rather than restart (no duplicated opening words).
+"""
+from __future__ import annotations
+
+import logging
+from collections.abc import AsyncIterator
+from typing import Any
+
+from jarvis.core import config as cfg
+from jarvis.core.protocols import AudioChunk
+from jarvis.plugins.tts.openrouter_speech_models import (
+ DEFAULT_MODEL,
+ GENERIC_DEFAULT_VOICE,
+ MODEL_DEFAULT_VOICE,
+ MODEL_VOICES,
+)
+
+log = logging.getLogger("jarvis.tts.openrouter")
+
+# Raw PCM the endpoint returns: 16-bit signed LE, mono, 24 kHz — the pipeline's
+# native playback format (audio/pcm;rate=24000;channels=1, verified live).
+OPENROUTER_TTS_SAMPLE_RATE = 24_000
+OPENROUTER_TTS_ENDPOINT_PATH = "/audio/speech"
+BASE_URL = "https://openrouter.ai/api/v1"
+_HTTP_TIMEOUT_S = 60.0
+# OpenAI-style speech endpoints cap input length; keep a generous bound.
+_MAX_CHARS_PER_REQUEST = 12_000
+
+
+class OpenRouterTTSError(RuntimeError):
+ """Fatal OpenRouter TTS error (no key / auth / quota / transport).
+
+ Raised before any audio is yielded so ``FallbackTTS`` can cross to another
+ TTS family instead of leaving Jarvis mute.
+ """
+
+
+class OpenRouterTTS:
+ """TTS provider for OpenRouter's ``/audio/speech`` endpoint.
+
+ Structurally compatible with the ``TTSProvider`` protocol — no inheritance
+ from ``jarvis.*`` (the factory dispatches on it explicitly).
+ """
+
+ name = "openrouter"
+ supports_streaming = True
+
+ def __init__(
+ self,
+ model: str | None = None,
+ default_voice: str | None = None,
+ voice_de: str | None = None,
+ voice_en: str | None = None,
+ language: str = "auto",
+ speed: float = 1.0,
+ ) -> None:
+ self._model = (model or DEFAULT_MODEL).strip()
+ # Per-language config voices (mirrors the [tts] voice_de / voice_en split).
+ self._voice_de = (voice_de or "").strip() or None
+ self._voice_en = (voice_en or "").strip() or None
+ # A single explicit default voice (used when no per-language voice fits).
+ self._default_voice = (default_voice or "").strip() or None
+ self._language = language or "auto"
+ self._speed = speed
+ self._client: Any = None # httpx.AsyncClient, lazy
+ # Overridden by _ensure_client with the resolved endpoint; a default here
+ # lets a directly-injected client (tests / warm reuse) synthesise without
+ # re-resolving the key.
+ self._base_url = BASE_URL
+
+ # ------------------------------------------------------------------
+ # Auth + client
+ # ------------------------------------------------------------------
+
+ def _ensure_client(self) -> None:
+ """Build the shared httpx client, resolving the ONE OpenRouter key.
+
+ Raises :class:`OpenRouterTTSError` when no credential is configured — the
+ same clear, fail-closed signal the factory / FallbackTTS expects.
+ """
+ if self._client is not None:
+ return
+ ep = cfg.resolve_provider_endpoint(
+ "openrouter", vendor_default_base_url=BASE_URL
+ )
+ if not ep.credential:
+ raise OpenRouterTTSError(
+ "No OpenRouter API key found (openrouter_api_key / "
+ "OPENROUTER_API_KEY). It is the SAME key the OpenRouter brain "
+ "uses — set it in the API-Keys view or in .env."
+ )
+ import httpx
+
+ self._base_url = (ep.base_url or BASE_URL).rstrip("/")
+ self._client = httpx.AsyncClient(
+ timeout=_HTTP_TIMEOUT_S,
+ headers={
+ "Authorization": f"Bearer {ep.credential}",
+ "Content-Type": "application/json",
+ # OpenRouter attribution headers (same as the brain plugin).
+ "HTTP-Referer": "https://github.com/PersonalJarvis",
+ "X-Title": "Personal Jarvis",
+ },
+ )
+
+ async def aclose(self) -> None:
+ """Close the HTTP client. Idempotent."""
+ if self._client is not None:
+ try:
+ await self._client.aclose()
+ finally:
+ self._client = None
+
+ # ------------------------------------------------------------------
+ # Voice resolution
+ # ------------------------------------------------------------------
+
+ def _resolve_voice(self, voice: str | None, language_code: str | None) -> str:
+ """Pick a voice VALID for the current model.
+
+ Priority: explicit per-call ``voice`` → the config voice for the resolved
+ language (``voice_de`` for German, else ``voice_en``) → the single
+ ``default_voice`` → the model's own default. The chosen voice is then
+ validated against the model's ``supported_voices`` (curated snapshot); an
+ invalid voice (e.g. a Gemini name left over after switching to Grok) is
+ replaced by the model default with a logged note, so the provider never
+ 400s on a foreign voice id.
+ """
+ chosen = voice
+ if not chosen:
+ lang = (language_code or self._language or "").lower()
+ is_de = lang.startswith("de")
+ chosen = (self._voice_de if is_de else self._voice_en) or self._default_voice
+ return self._validate_voice(chosen)
+
+ def _validate_voice(self, voice: str | None) -> str:
+ allowed = MODEL_VOICES.get(self._model)
+ model_default = (
+ MODEL_DEFAULT_VOICE.get(self._model)
+ or (allowed[0] if allowed else None)
+ or GENERIC_DEFAULT_VOICE
+ )
+ # Unknown model (not in the curated snapshot): trust the caller's voice,
+ # since we cannot validate it — never block a model we simply do not know.
+ if allowed is None:
+ return voice or model_default
+ if voice and voice in allowed:
+ return voice
+ if voice:
+ log.info(
+ "Voice %r is not valid for OpenRouter TTS model %r — using %r.",
+ voice, self._model, model_default,
+ )
+ return model_default
+
+ def list_voices(self, language: str | None = None) -> list[str]:
+ """Voices valid for the CURRENT model (from the curated per-model map).
+
+ When ``language`` is given and the model's voice ids are language-prefixed
+ (e.g. Kokoro's ``de_``/``af_``, MAI-Voice's ``de-DE-...``), the list is
+ narrowed to that language — but never to empty, so the picker always shows
+ something valid. Language-agnostic models (Gemini, Grok) return all voices.
+ """
+ voices = list(MODEL_VOICES.get(self._model, ()))
+ if not voices:
+ dv = MODEL_DEFAULT_VOICE.get(self._model) or self._default_voice
+ 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)]
+ if narrowed:
+ return narrowed
+ return voices
+
+ # ------------------------------------------------------------------
+ # Synthesis (streaming)
+ # ------------------------------------------------------------------
+
+ async def synthesize(
+ self,
+ text: str,
+ voice: str | None = None,
+ language_code: str | None = None,
+ ) -> AsyncIterator[AudioChunk]:
+ """Stream synthesised speech as 24 kHz mono s16le PCM ``AudioChunk``s.
+
+ A fatal error (no key / 4xx / transport) is raised BEFORE the first chunk
+ so ``FallbackTTS`` can cross to another provider. Language is inferred by
+ the model from ``input`` (the OpenAI speech API takes no language field);
+ ``voice`` pins the speaker.
+ """
+ text = (text or "").strip()
+ if not text:
+ return
+
+ # No key / build failure → raise before any chunk (FallbackTTS crosses).
+ self._ensure_client()
+
+ resolved_voice = self._resolve_voice(voice, language_code)
+ payload: dict[str, Any] = {
+ "model": self._model,
+ "input": text[:_MAX_CHARS_PER_REQUEST],
+ "voice": resolved_voice,
+ "response_format": "pcm",
+ }
+ # Only send speed when non-default: some speech models reject an
+ # unexpected field; the default (1.0) never needs it.
+ if self._speed and self._speed != 1.0:
+ payload["speed"] = self._speed
+
+ assert self._client is not None
+ url = self._base_url + OPENROUTER_TTS_ENDPOINT_PATH
+ carry = b""
+ try:
+ async with self._client.stream("POST", url, json=payload) as resp:
+ if resp.status_code >= 400:
+ body = await resp.aread()
+ detail = body.decode("utf-8", "replace")[:300] if body else "<empty>"
+ raise OpenRouterTTSError(
+ f"OpenRouter TTS HTTP {resp.status_code} "
+ f"(model={self._model}, voice={resolved_voice}): {detail}"
+ )
+ async for raw in resp.aiter_bytes():
+ if not raw:
+ continue
+ buf = carry + raw
+ # Keep 16-bit sample alignment; hold back an odd trailing byte.
+ aligned = len(buf) - (len(buf) % 2)
+ chunk, carry = buf[:aligned], buf[aligned:]
+ if chunk:
+ yield AudioChunk(
+ pcm=chunk,
+ sample_rate=OPENROUTER_TTS_SAMPLE_RATE,
+ timestamp_ns=0,
+ channels=1,
+ )
+ except OpenRouterTTSError:
+ raise
+ except Exception as exc: # noqa: BLE001 — transport/stream failure
+ # Wrap as a fatal error so a pre-first-chunk failure crosses families;
+ # if chunks already flowed, FallbackTTS re-raises (no double audio).
+ raise OpenRouterTTSError(
+ f"OpenRouter TTS request failed ({exc.__class__.__name__}): {exc}"
+ ) from exc
+
+ if carry:
+ # Flush a leftover odd byte padded to a full sample (defensive; the
+ # 24 kHz s16le stream is byte-even in practice).
+ yield AudioChunk(
+ pcm=carry + b"\x00",
+ sample_rate=OPENROUTER_TTS_SAMPLE_RATE,
+ 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/vision/atspi_tree.py b/jarvis/vision/atspi_tree.py
index df96a8bf54..d695479597 100644
--- a/jarvis/vision/atspi_tree.py
+++ b/jarvis/vision/atspi_tree.py
@@ -296,6 +296,8 @@ class AtspiTreeSource:
enabled=n.enabled,
parent_index=n.parent_index,
value=n.value,
+ is_password=n.is_password,
+ focused=n.focused,
)
for n in raw
]
@@ -351,6 +353,22 @@ def _atspi_pick_active_app(desktop: Any) -> Any:
first = child
if _atspi_is_active(child):
return child
+ # The ACTIVE/FOCUSED state lives on the FRAME (window), not on the
+ # application object — probe one level down before moving on
+ # (2026-07-02 review finding: the app-level probe practically never
+ # matched, so the tree silently enumerated the FIRST app instead of
+ # the active one on multi-app desktops).
+ try:
+ frame_count = int(getattr(child, "childCount", 0) or 0)
+ except Exception: # noqa: BLE001
+ frame_count = 0
+ for j in range(frame_count):
+ try:
+ frame = child.getChildAtIndex(j)
+ except Exception: # noqa: BLE001, S112 — skip an unreadable frame
+ continue
+ if frame is not None and _atspi_is_active(frame):
+ return child
return first
@@ -440,6 +458,29 @@ def _atspi_enabled(accessible: Any) -> bool:
return True
+def _atspi_focused(accessible: Any) -> bool:
+ """True when the AT-SPI state set contains FOCUSED (best-effort).
+
+ Feeds ``UIANode.focused`` — the click-rescue and focus-verification
+ evidence. Until 2026-07-02 the Linux flatten never populated it, which
+ silently disabled those verifications on Linux (review finding).
+ """
+ try:
+ get_state = getattr(accessible, "getState", None)
+ if not callable(get_state):
+ return False
+ state = get_state()
+ contains = getattr(state, "contains", None)
+ if not callable(contains):
+ return False
+ pyatspi = _import_pyatspi()
+ if pyatspi is not None:
+ return bool(contains(pyatspi.STATE_FOCUSED))
+ return bool(contains("STATE_FOCUSED"))
+ except Exception: # noqa: BLE001
+ return False
+
+
def _atspi_bounds(accessible: Any) -> tuple[int, int, int, int]:
"""Read screen bounds via the AT-SPI Component interface (best-effort)."""
extents = None
@@ -500,6 +541,9 @@ def _atspi_flatten(
automation_id = "" # AT-SPI has no stable AutomationId equivalent.
bounds = _atspi_bounds(element)
enabled = _atspi_enabled(element)
+ focused = _atspi_focused(element)
+ # AT-SPI marks secure edits with a dedicated ROLE, not a flag.
+ is_password = native_role.strip().upper() == "ROLE_PASSWORD_TEXT"
except Exception: # noqa: BLE001
return
@@ -524,6 +568,8 @@ def _atspi_flatten(
depth=depth,
parent_index=parent_index,
value=value,
+ is_password=is_password,
+ focused=focused,
))
if depth >= max_depth:
diff --git a/jarvis/vision/element_at_point.py b/jarvis/vision/element_at_point.py
index 00eece1f67..41f46b2663 100644
--- a/jarvis/vision/element_at_point.py
+++ b/jarvis/vision/element_at_point.py
@@ -244,13 +244,28 @@ def _ax_query_element_at_point(x: int, y: int) -> PointerElement | None:
focused: bool | None = bool(val_f) if err_f == 0 else None
except Exception: # noqa: BLE001 — attribute read is best-effort
focused = None
+ # kAXWindowAttribute returns the containing window ELEMENT, not a string
+ # — str() on it would inject an object repr like '<AXUIElementRef 0x…>'
+ # into the model-facing context (2026-07-02 review finding). Resolve the
+ # window's AXTitle instead; any failure degrades to "".
+ window_title = ""
+ try:
+ err_w, win_elem = AXUIElementCopyAttributeValue(elem, "AXWindow", None)
+ if err_w == 0 and win_elem is not None:
+ err_t, title_val = AXUIElementCopyAttributeValue(
+ win_elem, "AXTitle", None,
+ )
+ if err_t == 0 and title_val is not None:
+ window_title = str(title_val).strip()
+ except Exception: # noqa: BLE001 — window-title read is best-effort
+ window_title = ""
return PointerElement(
name=name,
role=role,
value=value,
bounds=(0, 0, 0, 0),
app_name="",
- window_title=_attr("AXWindow"),
+ window_title=window_title,
source="ax_tree",
focused=focused,
)
@@ -273,22 +288,48 @@ def _atspi_query_element_at_point(x: int, y: int) -> PointerElement | None:
except Exception:
return None
- # Find the top-level window/app under the point, then descend into it.
+ def _hit(acc: Any) -> Any | None:
+ comp = _component(acc)
+ if comp is None:
+ return None
+ try:
+ return comp.getAccessibleAtPoint(int(x), int(y), coord)
+ except Exception: # noqa: BLE001
+ return None
+
+ # Find the top-level surface under the point. The desktop's direct
+ # children are AT-SPI APPLICATION objects, which do NOT implement the
+ # Component interface — only their child frames/windows do (2026-07-02
+ # review finding: hit-testing the applications directly returned None
+ # for every query). Try the application first anyway (cheap, and some
+ # toolkits do expose Component there), then descend one level into its
+ # frames.
node: Any = None
for i in range(desktop.childCount):
try:
app = desktop.getChildAtIndex(i)
except Exception: # noqa: S112 - best-effort scan; the resolver wraps all errors
continue
- comp = _component(app)
- if comp is None:
+ if app is None:
continue
+ node = _hit(app)
+ if node is not None:
+ break
try:
- hit = comp.getAccessibleAtPoint(int(x), int(y), coord)
- except Exception:
- hit = None
- if hit is not None:
- node = hit
+ frame_count = int(getattr(app, "childCount", 0) or 0)
+ except Exception: # noqa: BLE001
+ frame_count = 0
+ for j in range(frame_count):
+ try:
+ frame = app.getChildAtIndex(j)
+ except Exception: # noqa: S112 - skip an unreadable frame
+ continue
+ if frame is None:
+ continue
+ node = _hit(frame)
+ if node is not None:
+ break
+ if node is not None:
break
if node is None:
diff --git a/tests/unit/cu/test_conventions_ledger_verify.py b/tests/unit/cu/test_conventions_ledger_verify.py
index 210c5562a4..a810d745b5 100644
--- a/tests/unit/cu/test_conventions_ledger_verify.py
+++ b/tests/unit/cu/test_conventions_ledger_verify.py
@@ -224,6 +224,34 @@ def test_focused_container_is_never_click_evidence():
bar = _node(role="Edit", name="Address",
focused=True, bounds=(100, 40, 800, 36))
assert click_point_in_focused_element((window, bar), 400, 58) is True
+ # Large-region roles from all three vocabularies are containers too
+ # (2026-07-02 adversarial review: List/Table/Toolbar and the AT-SPI
+ # document-canvas family were missing from the deny-list).
+ for role in ("List", "Table", "ToolBar", "AXToolbar", "AXList",
+ "document text", "tool bar"):
+ region = _node(role=role, name="big region",
+ focused=True, bounds=(0, 0, 1200, 900))
+ assert click_point_in_focused_element((region,), 400, 58) is False, role
+
+
+def test_focused_giant_control_is_not_click_evidence_with_area_cap():
+ # A focused element spanning most of the capture is a REGION even if its
+ # role sounds like a control — rescuing there would mask a genuine miss
+ # anywhere inside it (and skip the zoom-refine retry).
+ giant = _node(role="Edit", name="Editor surface",
+ focused=True, bounds=(0, 0, 1900, 1000))
+ area = 1920 * 1080
+ assert click_point_in_focused_element(
+ (giant,), 400, 500, capture_area=area,
+ ) is False
+ # Without a capture_area reference the role filter alone decides.
+ assert click_point_in_focused_element((giant,), 400, 500) is True
+ # A normal-sized focused control passes with the cap in force.
+ bar = _node(role="Edit", name="Address",
+ focused=True, bounds=(100, 40, 800, 36))
+ assert click_point_in_focused_element(
+ (bar,), 400, 58, capture_area=area,
+ ) is True
def test_field_values_hint_lists_filled_fields_only():
diff --git a/tests/unit/plugins/stt/test_openrouter_stt.py b/tests/unit/plugins/stt/test_openrouter_stt.py
index 52b7ca9506..7db3a6379d 100644
--- a/tests/unit/plugins/stt/test_openrouter_stt.py
+++ b/tests/unit/plugins/stt/test_openrouter_stt.py
@@ -34,6 +34,13 @@ def _silent_pcm(num_samples: int = 1600) -> bytes:
return b"\x00\x00" * num_samples
+def test_provider_identity_is_distinct_from_brain() -> None:
+ """The STT provider id must NOT be ``openrouter`` (that is the brain's id in
+ the shared catalog / provider-spec namespaces) and must be non-streaming."""
+ assert OpenRouterSTT.name == "openrouter-stt"
+ assert OpenRouterSTT.supports_streaming is False
+
+
def _mock_client(handler) -> httpx.AsyncClient:
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
diff --git a/tests/unit/plugins/tts/test_openrouter_tts.py b/tests/unit/plugins/tts/test_openrouter_tts.py
new file mode 100644
index 0000000000..7651a4ac6d
--- /dev/null
+++ b/tests/unit/plugins/tts/test_openrouter_tts.py
@@ -0,0 +1,281 @@
+"""Unit tests for the OpenRouter TTS plugin + its speech-model filter.
+
+Uses lightweight fake httpx stream objects (no unittest.mock, per repo policy);
+no live network. Covers: request body shape, streaming AudioChunk yielding at
+24 kHz mono, per-model voice validation + list_voices, the missing-key fatal
+error path (FallbackTTS contract), and the speech-model filter (mixed catalog ->
+only speech models survive).
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from typing import Any
+
+import pytest
+
+from jarvis.core.protocols import AudioChunk
+from jarvis.plugins.tts import openrouter_tts as ortts
+from jarvis.plugins.tts.openrouter_speech_models import (
+ DEFAULT_MODEL,
+ filter_tts_models,
+ is_speech_model,
+ voices_for_model,
+)
+from jarvis.plugins.tts.openrouter_tts import (
+ OPENROUTER_TTS_SAMPLE_RATE,
+ OpenRouterTTS,
+ OpenRouterTTSError,
+)
+
+# --------------------------------------------------------------------------- #
+# Fake httpx streaming client #
+# --------------------------------------------------------------------------- #
+
+
+class _FakeStreamResponse:
+ def __init__(self, status_code: int, chunks: list[bytes] | None = None,
+ error_body: bytes = b"") -> None:
+ self.status_code = status_code
+ self._chunks = chunks or []
+ self._error_body = error_body
+
+ async def aread(self) -> bytes:
+ return self._error_body
+
+ async def aiter_bytes(self) -> AsyncIterator[bytes]:
+ for c in self._chunks:
+ yield c
+
+
+class _FakeStreamCM:
+ def __init__(self, resp: _FakeStreamResponse) -> None:
+ self._resp = resp
+
+ async def __aenter__(self) -> _FakeStreamResponse:
+ return self._resp
+
+ async def __aexit__(self, *exc: Any) -> bool:
+ return False
+
+
+class _FakeClient:
+ """Records the last stream() call and returns a canned response."""
+
+ def __init__(self, resp: _FakeStreamResponse) -> None:
+ self._resp = resp
+ self.captured: dict[str, Any] = {}
+
+ def stream(self, method: str, url: str, json: dict[str, Any] | None = None) -> _FakeStreamCM:
+ self.captured = {"method": method, "url": url, "payload": json}
+ return _FakeStreamCM(self._resp)
+
+
+def _tts_with_client(resp: _FakeStreamResponse, **kw: Any) -> tuple[OpenRouterTTS, _FakeClient]:
+ tts = OpenRouterTTS(**kw)
+ client = _FakeClient(resp)
+ tts._client = client # inject; skips key resolution
+ return tts, client
+
+
+# --------------------------------------------------------------------------- #
+# synthesize — request shape + streaming #
+# --------------------------------------------------------------------------- #
+
+
+async def test_request_body_shape() -> None:
+ """Body carries model/input/voice/response_format=pcm and NO language field."""
+ resp = _FakeStreamResponse(200, chunks=[b"\x00\x01" * 10])
+ tts, client = _tts_with_client(resp, model=DEFAULT_MODEL, voice_en="Kore")
+
+ _ = [c async for c in tts.synthesize("Hello there.", language_code="en-US")]
+
+ payload = client.captured["payload"]
+ assert payload["model"] == DEFAULT_MODEL
+ assert payload["input"] == "Hello there."
+ assert payload["voice"] == "Kore"
+ assert payload["response_format"] == "pcm"
+ assert "language" not in payload # OpenAI speech API takes no language field
+ assert "speed" not in payload # default speed is omitted
+ assert client.captured["url"].endswith("/audio/speech")
+
+
+async def test_speed_included_when_non_default() -> None:
+ resp = _FakeStreamResponse(200, chunks=[b"\x00\x01" * 4])
+ tts, client = _tts_with_client(resp, speed=1.25)
+ _ = [c async for c in tts.synthesize("Hi.")]
+ assert client.captured["payload"]["speed"] == 1.25
+
+
+async def test_streaming_yields_pcm_24k_mono() -> None:
+ """Multiple byte chunks -> multiple AudioChunks at 24 kHz mono s16le."""
+ chunks = [b"\x01\x02" * 100, b"\x03\x04" * 100, b"\x05\x06" * 100]
+ resp = _FakeStreamResponse(200, chunks=chunks)
+ tts, _ = _tts_with_client(resp)
+
+ out = [c async for c in tts.synthesize("Stream this.")]
+
+ assert len(out) == 3
+ assert all(isinstance(c, AudioChunk) for c in out)
+ assert all(c.sample_rate == OPENROUTER_TTS_SAMPLE_RATE for c in out)
+ assert all(c.channels == 1 for c in out)
+ assert b"".join(c.pcm for c in out) == b"".join(chunks)
+
+
+async def test_odd_byte_alignment_is_preserved() -> None:
+ """A 16-bit sample split across two network chunks is not dropped/misaligned."""
+ # 3 bytes then 1 byte => 4 bytes total (2 samples), no loss, no split sample.
+ resp = _FakeStreamResponse(200, chunks=[b"\xaa\xbb\xcc", b"\xdd"])
+ tts, _ = _tts_with_client(resp)
+ out = [c async for c in tts.synthesize("x")]
+ joined = b"".join(c.pcm for c in out)
+ assert joined == b"\xaa\xbb\xcc\xdd"
+ assert len(joined) % 2 == 0
+
+
+async def test_empty_text_yields_nothing() -> None:
+ resp = _FakeStreamResponse(200, chunks=[b"\x00\x00"])
+ tts, _ = _tts_with_client(resp)
+ out = [c async for c in tts.synthesize(" ")]
+ assert out == []
+
+
+# --------------------------------------------------------------------------- #
+# Fatal error paths (FallbackTTS contract: raise before first chunk) #
+# --------------------------------------------------------------------------- #
+
+
[email protected]("status", [401, 402, 403, 429, 500])
+async def test_http_error_raises_before_any_chunk(status: int) -> None:
+ resp = _FakeStreamResponse(status, error_body=b'{"error":"nope"}')
+ tts, _ = _tts_with_client(resp)
+ with pytest.raises(OpenRouterTTSError):
+ _ = [c async for c in tts.synthesize("Test.")]
+
+
+async def test_missing_key_raises_clear_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No credential -> OpenRouterTTSError before any audio (FallbackTTS crosses)."""
+
+ class _Endpoint:
+ credential = ""
+ base_url = ortts.BASE_URL
+
+ monkeypatch.setattr(
+ ortts.cfg, "resolve_provider_endpoint", lambda *a, **k: _Endpoint()
+ )
+ tts = OpenRouterTTS() # no injected client -> _ensure_client runs
+ with pytest.raises(OpenRouterTTSError, match="OpenRouter API key"):
+ _ = [c async for c in tts.synthesize("Test.")]
+
+
+# --------------------------------------------------------------------------- #
+# Voice resolution + list_voices #
+# --------------------------------------------------------------------------- #
+
+
+async def test_foreign_voice_corrected_to_model_default() -> None:
+ """A voice not valid for the model is replaced by the model default (no 400)."""
+ resp = _FakeStreamResponse(200, chunks=[b"\x00\x00"])
+ # Grok model does not accept a Gemini "Charon" voice.
+ tts, client = _tts_with_client(
+ resp, model="x-ai/grok-voice-tts-1.0", voice_en="Charon"
+ )
+ _ = [c async for c in tts.synthesize("Hi.", language_code="en")]
+ assert client.captured["payload"]["voice"] == "leo" # grok model default
+
+
+async def test_valid_voice_passes_through() -> None:
+ resp = _FakeStreamResponse(200, chunks=[b"\x00\x00"])
+ tts, client = _tts_with_client(resp, model=DEFAULT_MODEL, voice_de="Charon")
+ # de-DE language_code selects the voice_de slot (voice resolves from the
+ # language code, not the text), so the input text stays English.
+ _ = [c async for c in tts.synthesize("Hello.", language_code="de-DE")]
+ assert client.captured["payload"]["voice"] == "Charon"
+
+
+async def test_explicit_voice_override_wins() -> None:
+ resp = _FakeStreamResponse(200, chunks=[b"\x00\x00"])
+ tts, client = _tts_with_client(resp, model=DEFAULT_MODEL, voice_en="Kore")
+ _ = [c async for c in tts.synthesize("Hi.", voice="Puck", language_code="en")]
+ assert client.captured["payload"]["voice"] == "Puck"
+
+
+def test_list_voices_returns_model_voices() -> None:
+ tts = OpenRouterTTS(model="x-ai/grok-voice-tts-1.0")
+ voices = tts.list_voices()
+ assert set(voices) == {"eve", "ara", "rex", "sal", "leo"}
+
+
+def test_list_voices_narrows_by_language_for_prefixed_model() -> None:
+ """Kokoro voices are language-prefixed; a German filter narrows, never empties."""
+ tts = OpenRouterTTS(model="hexgrad/kokoro-82m")
+ en = tts.list_voices(language="en-US")
+ assert en and all(v[0] in ("a", "b") for v in en) # a*/b* = English families
+ # A language the model has no voices for falls back to the full valid list.
+ de = tts.list_voices(language="de")
+ assert de # never empty
+
+
+# --------------------------------------------------------------------------- #
+# Speech-model filter (the TTS model picker predicate) #
+# --------------------------------------------------------------------------- #
+
+
+def _model(mid: str, out_mods: list[str], voices: list[str] | None = None) -> dict[str, Any]:
+ obj: dict[str, Any] = {
+ "id": mid,
+ "architecture": {"output_modalities": out_mods, "modality": f"text->{out_mods[0]}"},
+ }
+ if voices is not None:
+ obj["supported_voices"] = voices
+ return obj
+
+
+def test_is_speech_model_predicate() -> None:
+ assert is_speech_model(_model("google/gemini-3.1-flash-tts-preview", ["speech"]))
+ assert not is_speech_model(_model("openai/gpt-5.5", ["text"]))
+ assert not is_speech_model(_model("google/gemini-3-pro", ["text", "image"]))
+ assert not is_speech_model(_model("openai/gpt-audio", ["text", "audio"])) # audio-chat, not TTS
+ assert not is_speech_model(_model("google/lyria-3-pro", ["text", "audio"])) # music
+ assert not is_speech_model({"id": "broken"}) # no architecture -> False
+
+
+def test_is_speech_model_via_modality_string_fallback() -> None:
+ obj = {"id": "x", "architecture": {"modality": "text->speech"}}
+ assert is_speech_model(obj)
+
+
+def test_filter_tts_models_keeps_only_speech() -> None:
+ catalog = [
+ _model("openai/gpt-5.5", ["text"]),
+ _model("google/gemini-3.1-flash-tts-preview", ["speech"]),
+ _model("x-ai/grok-voice-tts-1.0", ["speech"]),
+ _model("openai/gpt-audio", ["text", "audio"]),
+ _model("some/embedding-model", ["text"]),
+ _model("google/lyria-3-pro", ["text", "audio"]),
+ ]
+ kept = filter_tts_models(catalog)
+ ids = {m["id"] for m in kept}
+ assert ids == {
+ "google/gemini-3.1-flash-tts-preview",
+ "x-ai/grok-voice-tts-1.0",
+ }
+
+
+def test_voices_for_model_reads_live_supported_voices() -> None:
+ obj = _model("x-ai/grok-voice-tts-1.0", ["speech"], voices=["eve", "leo"])
+ assert voices_for_model(obj) == ["eve", "leo"]
+
+
+def test_voices_for_model_falls_back_to_curated_by_id() -> None:
+ obj = {"id": "x-ai/grok-voice-tts-1.0"} # no live supported_voices
+ assert set(voices_for_model(obj)) == {"eve", "ara", "rex", "sal", "leo"}