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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(realtime): per-voice audio preview for realtime provider voices
Ruben Lütkec8d457e46e5b
diff --git a/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsx b/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsxindex 5acfe99ef7..3fe25621ae 100644--- a/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsx+++ b/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsx@@ -413,8 +413,9 @@ function VoicePicker({);}-/** A small play / stop button with a loading spinner while the audio fetches. */-function PreviewButton({+/** A small play / stop button with a loading spinner while the audio fetches.+ * Shared with the realtime voice picker (RealtimeOptionsControl). */+export function PreviewButton({active,loading,onClick,diff --git a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsxindex 6e8b1b269d..314e5c039d 100644--- a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx+++ b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx@@ -1,10 +1,11 @@import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// Identity translator so rendered text equals the i18n key — matches the// pattern used by CuModelSelector.test.tsx.vi.mock("@/i18n", () => ({useT: () => (key: string) => key,+ useUiLanguage: () => "en",}));vi.mock("@/store/events", () => ({@@ -14,10 +15,13 @@ vi.mock("@/store/events", () => ({const getRealtimeOptions = vi.fn();const saveRealtimeOptions = vi.fn();+const fetchRealtimeVoicePreview = vi.fn();vi.mock("@/hooks/useProviders", () => ({getRealtimeOptions: (...args: unknown[]) => getRealtimeOptions(...args),saveRealtimeOptions: (...args: unknown[]) => saveRealtimeOptions(...args),+ fetchRealtimeVoicePreview: (...args: unknown[]) =>+ fetchRealtimeVoicePreview(...args),}));import { RealtimeOptionsControl } from "./RealtimeOptionsControl";@@ -36,46 +40,61 @@ const OPTIONS = {current_voice: "",};+// jsdom implements neither media playback nor object URLs — stub the pieces+// the preview path touches so play() resolves and blobs get URLs.+beforeEach(() => {+ vi.spyOn(window.HTMLMediaElement.prototype, "play").mockResolvedValue();+ vi.spyOn(window.HTMLMediaElement.prototype, "pause").mockReturnValue();+ URL.createObjectURL = vi.fn(() => "blob:mock");+ URL.revokeObjectURL = vi.fn();+});+afterEach(() => {cleanup();vi.restoreAllMocks();});+/** Open the voice picker panel via its trigger button. */+async function openVoicePanel() {+ const trigger = await screen.findByLabelText("apikeys_view.realtime_voice_label");+ fireEvent.click(trigger);+ return trigger;+}+describe("RealtimeOptionsControl", () => {- it("renders a MODEL and a VOICE dropdown, populated from getRealtimeOptions", async () => {+ it("renders a MODEL dropdown and a VOICE picker, populated from getRealtimeOptions", async () => {getRealtimeOptions.mockResolvedValue(OPTIONS);render(<RealtimeOptionsControl providerId="openai-realtime" />);const modelSelect = (await screen.findByLabelText("apikeys_view.realtime_model_label",)) as HTMLSelectElement;- const voiceSelect = (await screen.findByLabelText(- "apikeys_view.realtime_voice_label",- )) as HTMLSelectElement;expect(getRealtimeOptions).toHaveBeenCalledWith("openai-realtime");expect(Array.from(modelSelect.options).map((o) => o.value),).toEqual(["", "gpt-realtime", "gpt-realtime-mini"]);- expect(- Array.from(voiceSelect.options).map((o) => o.value),- ).toEqual(["", "alloy", "echo"]);++ await openVoicePanel();+ expect(screen.getByText("Alloy")).toBeTruthy();+ expect(screen.getByText("Echo")).toBeTruthy();});- it("maps the leading option to the 'Provider default' label and selects it when current_model/current_voice are empty", async () => {+ it("shows the 'Provider default' label when current_model/current_voice are empty", async () => {getRealtimeOptions.mockResolvedValue(OPTIONS);render(<RealtimeOptionsControl providerId="openai-realtime" />);const modelSelect = (await screen.findByLabelText("apikeys_view.realtime_model_label",)) as HTMLSelectElement;- const voiceSelect = (await screen.findByLabelText(+ const voiceTrigger = await screen.findByLabelText("apikeys_view.realtime_voice_label",- )) as HTMLSelectElement;+ );expect(modelSelect.value).toBe("");- expect(voiceSelect.value).toBe("");- expect(screen.getAllByText("apikeys_view.realtime_provider_default").length).toBe(2);+ expect(voiceTrigger.textContent).toContain(+ "apikeys_view.realtime_provider_default",+ );});it("pre-selects the persisted current_model/current_voice", async () => {@@ -89,12 +108,12 @@ describe("RealtimeOptionsControl", () => {const modelSelect = (await screen.findByLabelText("apikeys_view.realtime_model_label",)) as HTMLSelectElement;- const voiceSelect = (await screen.findByLabelText(+ const voiceTrigger = await screen.findByLabelText("apikeys_view.realtime_voice_label",- )) as HTMLSelectElement;+ );await waitFor(() => expect(modelSelect.value).toBe("gpt-realtime-mini"));- expect(voiceSelect.value).toBe("echo");+ expect(voiceTrigger.textContent).toContain("Echo");});it("selecting a model calls saveRealtimeOptions(id, {model})", async () => {@@ -118,7 +137,7 @@ describe("RealtimeOptionsControl", () => {);});- it("selecting a voice calls saveRealtimeOptions(id, {voice})", async () => {+ it("clicking a voice name in the panel calls saveRealtimeOptions(id, {voice})", async () => {getRealtimeOptions.mockResolvedValue(OPTIONS);saveRealtimeOptions.mockResolvedValue({ok: true,@@ -129,8 +148,8 @@ describe("RealtimeOptionsControl", () => {});render(<RealtimeOptionsControl providerId="openai-realtime" />);- const voiceSelect = await screen.findByLabelText("apikeys_view.realtime_voice_label");- fireEvent.change(voiceSelect, { target: { value: "echo" } });+ await openVoicePanel();+ fireEvent.click(screen.getByText("Echo"));await waitFor(() =>expect(saveRealtimeOptions).toHaveBeenCalledWith("openai-realtime", {@@ -143,6 +162,7 @@ describe("RealtimeOptionsControl", () => {getRealtimeOptions.mockResolvedValue({...OPTIONS,current_model: "gpt-realtime-mini",+ current_voice: "echo",});saveRealtimeOptions.mockResolvedValue({ok: true,@@ -159,9 +179,87 @@ describe("RealtimeOptionsControl", () => {await waitFor(() => expect(modelSelect.value).toBe("gpt-realtime-mini"));fireEvent.change(modelSelect, { target: { value: "" } });-await waitFor(() =>expect(saveRealtimeOptions).toHaveBeenCalledWith("openai-realtime", { model: "" }),);++ await openVoicePanel();+ // getByText would also match the model <select>'s default <option> — the+ // panel's default entry is the only BUTTON carrying this label here.+ fireEvent.click(+ screen.getByRole("button", {+ name: "apikeys_view.realtime_provider_default",+ }),+ );+ await waitFor(() =>+ expect(saveRealtimeOptions).toHaveBeenCalledWith("openai-realtime", { voice: "" }),+ );+ });++ it("the trigger-row preview button samples the pinned voice WITHOUT saving", async () => {+ getRealtimeOptions.mockResolvedValue({+ ...OPTIONS,+ current_model: "gpt-realtime-mini",+ current_voice: "echo",+ });+ fetchRealtimeVoicePreview.mockResolvedValue(new Blob(["x"], { type: "audio/wav" }));+ render(<RealtimeOptionsControl providerId="openai-realtime" />);++ // Panel closed → the only preview button belongs to the pinned voice.+ const previewButton = await screen.findByLabelText("apikeys_voice.preview");+ fireEvent.click(previewButton);++ await waitFor(() =>+ expect(fetchRealtimeVoicePreview).toHaveBeenCalledWith({+ providerId: "openai-realtime",+ voice: "echo",+ language: "en",+ model: "gpt-realtime-mini",+ }),+ );+ expect(saveRealtimeOptions).not.toHaveBeenCalled();+ });++ it("every voice row in the open panel can be auditioned without saving", async () => {+ getRealtimeOptions.mockResolvedValue(OPTIONS);+ fetchRealtimeVoicePreview.mockResolvedValue(new Blob(["x"], { type: "audio/wav" }));+ render(<RealtimeOptionsControl providerId="openai-realtime" />);++ await openVoicePanel();+ // No pinned voice → no trigger-row preview; the buttons map 1:1 onto the+ // listed voices in catalog order (alloy, echo).+ const previewButtons = screen.getAllByLabelText("apikeys_voice.preview");+ expect(previewButtons.length).toBe(2);+ fireEvent.click(previewButtons[0]);++ await waitFor(() =>+ expect(fetchRealtimeVoicePreview).toHaveBeenCalledWith({+ providerId: "openai-realtime",+ voice: "alloy",+ language: "en",+ model: "",+ }),+ );+ expect(saveRealtimeOptions).not.toHaveBeenCalled();+ });++ it("the panel's language toggle switches the sample language", async () => {+ getRealtimeOptions.mockResolvedValue(OPTIONS);+ fetchRealtimeVoicePreview.mockResolvedValue(new Blob(["x"], { type: "audio/wav" }));+ render(<RealtimeOptionsControl providerId="openai-realtime" />);++ await openVoicePanel();+ fireEvent.click(screen.getByText("de"));+ const previewButtons = screen.getAllByLabelText("apikeys_voice.preview");+ fireEvent.click(previewButtons[1]);++ await waitFor(() =>+ expect(fetchRealtimeVoicePreview).toHaveBeenCalledWith({+ providerId: "openai-realtime",+ voice: "echo",+ language: "de",+ model: "",+ }),+ );});});diff --git a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsxindex 1deb425306..60aeb002d6 100644--- a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx+++ b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx@@ -1,12 +1,15 @@-import { useEffect, useState } from "react";-import { Loader2 } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { Check, ChevronDown, Loader2 } from "lucide-react";import {+ fetchRealtimeVoicePreview,getRealtimeOptions,saveRealtimeOptions,type RealtimeOptionInfo,} from "@/hooks/useProviders";+import { PreviewButton } from "@/components/OpenRouterTtsVoicePicker";import { useEventStore } from "@/store/events";-import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useT, useUiLanguage } from "@/i18n";// "" always means "use the provider's own default" — mirrors the backend// contract (RealtimeOptionsResponse.current_model/current_voice empty when@@ -14,13 +17,18 @@ import { useT } from "@/i18n";const PROVIDER_DEFAULT = "";/**- * Per-realtime-provider MODEL + VOICE picker (two compact dropdowns).+ * Per-realtime-provider MODEL + VOICE picker.** Unlike every other tier, a realtime session needs BOTH a model and a voice* pinned per provider, so this is a small dedicated control against the* dedicated `GET/PUT /api/providers/{id}/realtime-options` endpoint rather- * than the shared search-heavy `BrainModelSelector` — the curated lists are- * short (a handful of models/voices), so a plain `<select>` is enough.+ * than the shared search-heavy `BrainModelSelector`.+ *+ * The model stays a plain `<select>` (a handful of curated entries). The+ * voice is a richer expanding picker with a per-voice audio preview+ * (`POST /api/providers/{id}/realtime-voice-preview`) so a voice can be+ * HEARD before it is pinned — auditioning must not write config or restart a+ * live realtime session; only clicking a name saves.** Renders only inside a realtime provider card (`tier === "realtime"`), gated* on the card already having a stored credential — see `ApiKeysView.tsx`.@@ -126,9 +134,11 @@ export function RealtimeOptionsControl({saving={savingField === "model"}onChange={(next) => void handleChange("model", next)}/>- <RealtimeSelectRow+ <RealtimeVoiceRow+ providerId={providerId}label={t("apikeys_view.realtime_voice_label")}value={voice}+ model={model}options={voices}saving={savingField === "voice"}onChange={(next) => void handleChange("voice", next)}@@ -178,3 +188,261 @@ function RealtimeSelectRow({</div>);}++/**+ * Voice row: current pick + preview button, expanding into the full voice+ * list where EVERY voice can be auditioned (play/stop) without saving —+ * clicking a name is what saves. The sample language is switchable DE/EN/ES,+ * seeded from the UI language (mirrors the TTS VoicePicker).+ */+function RealtimeVoiceRow({+ providerId,+ label,+ value,+ model,+ options,+ saving,+ onChange,+}: {+ providerId: string;+ label: string;+ value: string;+ model: string;+ options: RealtimeOptionInfo[];+ saving: boolean;+ onChange: (value: string) => void;+}) {+ const t = useT();+ const uiLang = useUiLanguage();+ const pushToast = useEventStore((s) => s.pushToast);++ const [open, setOpen] = useState(false);+ const [previewLang, setPreviewLang] = useState<"de" | "en" | "es">(+ uiLang === "de" ? "de" : uiLang === "es" ? "es" : "en",+ );+ // The voice currently PLAYING vs. the voice whose audio is being FETCHED —+ // the preview button shows a spinner while loading, a stop icon while+ // playing (same contract as the TTS VoicePicker).+ const [previewingId, setPreviewingId] = useState<string | null>(null);+ const [loadingId, setLoadingId] = useState<string | null>(null);++ const rootRef = useRef<HTMLDivElement>(null);+ const audioRef = useRef<HTMLAudioElement | null>(null);+ const urlRef = useRef<string | null>(null);++ function stopPreview() {+ if (audioRef.current) {+ audioRef.current.pause();+ audioRef.current = null;+ }+ if (urlRef.current) {+ URL.revokeObjectURL(urlRef.current);+ urlRef.current = null;+ }+ setPreviewingId(null);+ setLoadingId(null);+ }++ // Stop and free any playing preview when the component unmounts.+ useEffect(() => stopPreview, []);++ // Close the panel on an outside click.+ useEffect(() => {+ if (!open) return;+ function onDown(e: MouseEvent) {+ if (rootRef.current && !rootRef.current.contains(e.target as Node)) {+ setOpen(false);+ }+ }+ document.addEventListener("mousedown", onDown);+ return () => document.removeEventListener("mousedown", onDown);+ }, [open]);++ async function preview(voiceId: string) {+ // Toggle: a second click on the currently-playing / loading voice stops it.+ if (previewingId === voiceId || loadingId === voiceId) {+ stopPreview();+ return;+ }+ stopPreview();+ setLoadingId(voiceId);+ try {+ const blob = await fetchRealtimeVoicePreview({+ providerId,+ voice: voiceId,+ language: previewLang,+ model,+ });+ const url = URL.createObjectURL(blob);+ urlRef.current = url;+ const audio = new Audio(url);+ audioRef.current = audio;+ audio.onended = () => stopPreview();+ audio.onerror = () => stopPreview();+ setLoadingId(null);+ setPreviewingId(voiceId);+ await audio.play();+ } catch (e) {+ pushToast(+ "error",+ `${t("apikeys_voice.preview_failed")}: ${(e as Error).message}`,+ );+ stopPreview();+ }+ }++ function pick(next: string) {+ setOpen(false);+ if (next !== value) onChange(next);+ }++ const currentEntry = options.find((o) => o.id === value);++ return (+ <div ref={rootRef} className="space-y-1.5">+ <div className="flex items-center gap-2">+ <span className="w-14 shrink-0 text-[10px] uppercase tracking-wide text-muted-foreground">+ {label}+ </span>+ <button+ type="button"+ aria-label={label}+ aria-expanded={open}+ disabled={saving}+ onClick={() => setOpen((o) => !o)}+ className={cn(+ "flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md border bg-background px-2 py-1 text-left text-xs transition-colors disabled:opacity-60",+ open+ ? "border-primary/50 ring-1 ring-primary/20"+ : "border-input hover:border-primary/40",+ )}+ >+ <span className={cn("truncate", !value && "text-muted-foreground")}>+ {value+ ? currentEntry?.label || value+ : t("apikeys_view.realtime_provider_default")}+ </span>+ {saving ? (+ <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" />+ ) : (+ <ChevronDown+ className={cn(+ "h-3 w-3 shrink-0 text-muted-foreground transition-transform",+ open && "rotate-180",+ )}+ />+ )}+ </button>+ {/* The provider-default pick ("") resolves server-side — there is no+ single voice to honestly sample, so the trigger-row preview only+ renders for a concrete voice. */}+ {value && (+ <PreviewButton+ active={previewingId === value}+ loading={loadingId === value}+ onClick={() => void preview(value)}+ label={t("apikeys_voice.preview")}+ />+ )}+ </div>++ {/* Inline-expanding voice list with per-voice audition. */}+ {open && (+ <div className="overflow-hidden rounded-md border border-border bg-popover">+ <div+ className="flex items-center justify-end gap-1 border-b border-border px-2.5 py-1"+ role="group"+ aria-label={t("apikeys_voice.preview_language")}+ >+ <span className="text-[10px] text-muted-foreground">+ {t("apikeys_voice.preview_in")}+ </span>+ {(["de", "en", "es"] as const).map((lng) => (+ <button+ key={lng}+ type="button"+ onClick={() => setPreviewLang(lng)}+ aria-pressed={previewLang === lng}+ className={cn(+ "rounded-full border px-1.5 py-0.5 text-[10px] uppercase tracking-wide transition-colors",+ previewLang === lng+ ? "border-primary/40 bg-primary/20 text-primary"+ : "border-border bg-muted text-muted-foreground hover:text-foreground",+ )}+ >+ {lng}+ </button>+ ))}+ </div>+ <ul className="max-h-56 overflow-y-auto p-1 scrollbar-jarvis">+ <li>+ <div+ className={cn(+ "flex items-center rounded hover:bg-primary/10",+ !value && "bg-primary/20",+ )}+ >+ <button+ type="button"+ onClick={() => pick(PROVIDER_DEFAULT)}+ className="flex min-w-0 flex-1 items-center justify-between gap-2 px-2 py-1.5 text-left"+ >+ <span+ className={cn(+ "truncate text-xs",+ !value && "font-medium text-primary",+ )}+ >+ {t("apikeys_view.realtime_provider_default")}+ </span>+ {!value && <Check className="h-3 w-3 shrink-0 text-primary" />}+ </button>+ </div>+ </li>+ {options.map((v) => {+ const isPinned = v.id === value;+ return (+ <li key={v.id}>+ <div+ className={cn(+ "flex items-center rounded hover:bg-primary/10",+ isPinned && "bg-primary/20",+ )}+ >+ <PreviewButton+ active={previewingId === v.id}+ loading={loadingId === v.id}+ onClick={() => void preview(v.id)}+ label={t("apikeys_voice.preview")}+ className="ml-1"+ />+ <button+ type="button"+ onClick={() => pick(v.id)}+ className="flex min-w-0 flex-1 items-center justify-between gap-2 px-2 py-1.5 text-left"+ >+ <span+ className={cn(+ "truncate text-xs",+ isPinned && "font-medium text-primary",+ )}+ >+ {v.label}+ </span>+ {isPinned && <Check className="h-3 w-3 shrink-0 text-primary" />}+ </button>+ </div>+ </li>+ );+ })}+ </ul>+ {options.length > 0 && (+ <div className="border-t border-border px-2.5 py-1 text-[10px] text-muted-foreground">+ {t("apikeys_voice.count_hint").replace("{0}", String(options.length))}+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 6794eb113c..d4a8d1a47e 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -1019,3 +1019,43 @@ export async function saveRealtimeOptions(return body as RealtimeOptionsSaveResult;}+/**+ * Synthesises a short spoken sample of a realtime provider's voice and+ * returns it as a playable `audio/wav` blob. Mirrors+ * POST /api/providers/{id}/realtime-voice-preview. `model` matters only where+ * the sampler runs through a realtime session (openai-realtime); `""` uses+ * the adapter default. Throws with the backend's message on any failure+ * (no key / quota / transport).+ */+export async function fetchRealtimeVoicePreview(opts: {+ providerId: string;+ voice: string;+ language: "de" | "en" | "es";+ model?: string;+}): Promise<Blob> {+ const res = await fetch(+ `/api/providers/${encodeURIComponent(opts.providerId)}/realtime-voice-preview`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ voice: opts.voice,+ language: opts.language,+ model: opts.model ?? "",+ }),+ },+ );+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ const detail = (body as { detail?: unknown }).detail;+ throw new Error(+ typeof detail === "string" && detail+ ? detail+ : detail && typeof detail === "object" && "message" in detail+ ? String((detail as { message: unknown }).message)+ : `HTTP ${res.status}`,+ );+ }+ return await res.blob();+}+diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 3a4777fba1..94ebd40485 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -1861,6 +1861,247 @@ async def set_realtime_options()+# ── POST /providers/{id}/realtime-voice-preview ────────────────────────────+# Speak a short sample with one of a realtime provider's voices so the user+# can HEAR a voice before pinning it — same product contract as the TTS+# voice picker's POST /tts/preview below, but per realtime provider.++# Ceiling for one preview synthesis. Generous: the OpenAI path opens a real+# realtime session (handshake + generation), Gemini may cross its sibling+# bridge on a 429 — but the route must always answer so the play button's+# spinner resolves.+_REALTIME_PREVIEW_TIMEOUT_S = 30.0++# BCP-47 pronunciation pins for the sample languages. Gemini's prebuilt+# voices are language-agnostic; an unpinned call auto-detects per word and+# can code-switch mid-sentence, so the sample pins the language it speaks.+_REALTIME_PREVIEW_LANG_CODES = {"de": "de-DE", "en": "en-US", "es": "es-ES"}+++async def _gemini_live_voice_sample(+ api_key: str, *, model: str, voice: str, text: str, language: str+) -> tuple[bytes, int]:+ """Sample a Gemini Live voice via the Gemini TTS family.++ The Live API serves the same 30 prebuilt voices (Puck, Charon, Kore, …)+ as the Gemini TTS models, so a cheap ``generate_content`` call renders the+ identical voice without opening a duplex Live session. ``model`` (the+ pinned LIVE model) deliberately plays no role here — voices, not models,+ are what the sample demonstrates.+ """+ del model+ from jarvis.plugins.tts.gemini_flash_tts import GEMINI_TTS_SAMPLE_RATE, GeminiFlashTTS++ tts = GeminiFlashTTS(+ api_key=api_key,+ # One generation = one coherent voice take; no OS fallback voice may+ # ever impersonate the sampled voice.+ chunk_by_sentence=False,+ allow_sapi5_fallback=False,+ )+ pcm = bytearray()+ sample_rate = GEMINI_TTS_SAMPLE_RATE+ async for chunk in tts.synthesize(+ text, voice=voice, language_code=_REALTIME_PREVIEW_LANG_CODES.get(language)+ ):+ pcm += bytes(chunk.pcm)+ sample_rate = chunk.sample_rate+ return bytes(pcm), sample_rate+++async def _openai_realtime_voice_sample(+ api_key: str, *, model: str, voice: str, text: str, language: str+) -> tuple[bytes, int]:+ """Sample an OpenAI Realtime voice via a one-shot realtime session.++ Marin and Cedar exist ONLY in the Realtime API (no ``/v1/audio/speech``+ counterpart), so the sample opens the same duplex channel a live call+ uses — which also makes it exactly what a call will sound like. No+ microphone audio is sent; the session closes after one spoken response.+ """+ del language # the sample text itself carries the language+ import base64++ from openai import AsyncOpenAI # lazy (AP-26)++ output_rate = 24_000+ client = AsyncOpenAI(api_key=api_key)+ pcm = bytearray()+ try:+ async with client.realtime.connect(model=model or "gpt-realtime") as conn:+ # Mirrors the GA session shape of the live adapter+ # (jarvis/plugins/realtime/openai_realtime.py::_session_payload),+ # minus transcription/tools: manual-response mode so the server+ # never speaks on its own.+ await conn.session.update(+ session={+ "type": "realtime",+ "instructions": (+ "You generate voice samples. When asked to speak, say "+ "the requested text verbatim and nothing else."+ ),+ "output_modalities": ["audio"],+ "audio": {+ "input": {+ "format": {"type": "audio/pcm", "rate": output_rate},+ "turn_detection": {+ "type": "server_vad",+ "create_response": False,+ "interrupt_response": False,+ },+ },+ "output": {+ "format": {"type": "audio/pcm", "rate": output_rate},+ "voice": voice,+ },+ },+ }+ )+ # Request the response only after the server confirmed the session+ # (voice included) — a response generated before the update lands+ # would speak the DEFAULT voice, silently mislabeling the sample.+ response_requested = False+ async for event in conn:+ event_type = str(getattr(event, "type", "") or "")+ if event_type == "session.updated" and not response_requested:+ response_requested = True+ await conn.response.create(+ response={+ "instructions": (+ "Say exactly the following, in a natural tone, "+ f"and nothing else: {text}"+ )+ }+ )+ elif event_type == "response.output_audio.delta":+ pcm += base64.b64decode(getattr(event, "delta", "") or "")+ elif event_type == "response.done":+ response = getattr(event, "response", None)+ status = str(getattr(response, "status", "") or "")+ if status and status != "completed" and not pcm:+ details = getattr(response, "status_details", None)+ raise RuntimeError(+ f"the provider ended the sample as '{status}'"+ + (f" ({details})" if details else "")+ )+ break+ elif event_type == "error":+ error = getattr(event, "error", None)+ message = str(getattr(error, "message", "") or error or "unknown error")+ raise RuntimeError(message)+ finally:+ close = getattr(client, "close", None)+ if close is not None:+ result = close()+ if hasattr(result, "__await__"):+ await result+ return bytes(pcm), output_rate+++# Keyed like REALTIME_MODELS/REALTIME_VOICES: adding a realtime provider means+# adding its catalog entries AND its sampler here (the parity test guards it).+_REALTIME_PREVIEW_SAMPLERS: dict[str, Any] = {+ "gemini-live": _gemini_live_voice_sample,+ "openai-realtime": _openai_realtime_voice_sample,+}+++class RealtimeVoicePreviewBody(BaseModel):+ voice: str = Field(default="", max_length=200)+ # The sample language to speak ("de" | "en" | "es"). Falls back to English.+ language: str = Field(default="en", max_length=16)+ # The realtime model to sample through where the sampler needs one+ # (openai-realtime); "" = the adapter default. Validated when non-empty.+ model: str = Field(default="", max_length=200)++[email protected]("/providers/{provider_id}/realtime-voice-preview")+async def realtime_voice_preview(+ provider_id: str, body: RealtimeVoicePreviewBody+) -> Response:+ """Speak a SHORT sample with one of a realtime provider's voices.++ Returns ``audio/wav`` (24 kHz mono s16le in a WAV container) so the voice+ picker can play it directly — the same response contract as+ ``POST /tts/preview``. The sample is generated with the credential stored+ for THIS provider. Any failure (no key / quota / transport) is a clean+ 4xx/5xx JSON error the picker can toast — never a page-breaking 500.+ """+ _require_realtime_provider(provider_id)+ from jarvis.brain.model_catalog import REALTIME_MODELS, REALTIME_VOICES++ voice = body.voice.strip()+ if not voice:+ raise HTTPException(status_code=400, detail="A voice id is required.")+ _validate_realtime_option(+ provider_id=provider_id,+ field="voice",+ value=voice,+ allowed={option.id for option in REALTIME_VOICES.get(provider_id, ())},+ )+ model = body.model.strip()+ _validate_realtime_option(+ provider_id=provider_id,+ field="model",+ value=model,+ allowed={option.id for option in REALTIME_MODELS.get(provider_id, ())},+ )+ sampler = _REALTIME_PREVIEW_SAMPLERS.get(provider_id)+ if sampler is None:+ raise HTTPException(+ status_code=400,+ detail=f"Voice preview is not available for provider '{provider_id}'.",+ )++ api_key = cfg_mod.get_provider_secret(provider_id)+ if not api_key:+ raise HTTPException(+ status_code=409,+ detail=(+ f"Provider '{provider_id}' has no configured credentials. "+ "Add its API key first."+ ),+ )++ 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])++ try:+ pcm, sample_rate = await asyncio.wait_for(+ sampler(api_key, model=model, voice=voice, text=sample, language=lang),+ timeout=_REALTIME_PREVIEW_TIMEOUT_S,+ )+ except HTTPException:+ raise+ except TimeoutError as exc:+ raise HTTPException(+ status_code=502,+ detail=(+ f"Voice preview timed out after {_REALTIME_PREVIEW_TIMEOUT_S:.0f}s — "+ "the provider did not answer."+ ),+ ) from exc+ except Exception as exc: # noqa: BLE001 — never 500 the page+ raise HTTPException(+ status_code=502, detail=f"Voice preview failed: {exc}"+ ) from exc++ if not pcm:+ raise HTTPException(+ status_code=502,+ detail=(+ "Voice preview produced no audio — check the provider's API key "+ "and quota."+ ),+ )+ wav = _pcm_to_wav(pcm, sample_rate=sample_rate, channels=1)+ return Response(+ content=wav,+ media_type="audio/wav",+ headers={"Cache-Control": "no-store"},+ )++@router.get("/codex/status")async def codex_status(request: Request) -> dict[str, Any]:return CodexAuthService(_codex_binary_path(request)).status().to_dict()@@ -2193,11 +2434,17 @@ _VOICE_PICKER_PROVIDER = "openrouter-tts"# 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] = {+ # The German sentence is deliberately NOT a literal translation of the+ # English one: Gemini's AI-Studio TTS safety filter deterministically+ # blocked the former mirror-translation ("So klingt meine Stimme, wenn+ # ich für dich spreche und dir zuhöre") as PROHIBITED_CONTENT — 0/2 runs # i18n-allow: forensic quote of the blocked German sample+ # passed, voice-independent, while EN/ES passed (probe 2026-07-17). This+ # wording passed 4/4 runs across three voices."de": (- "Hallo! Ich bin dein " # i18n-allow: German TTS preview output.+ "Guten Tag! Ich bin dein " # i18n-allow: German TTS preview output."persönlicher Assistent. " # i18n-allow- "So klingt meine Stimme, " # i18n-allow- "wenn ich für dich spreche und dir zuhöre." # i18n-allow+ "So klingt meine Stimme. " # i18n-allow+ "Ich freue mich, dir bei deinen Aufgaben zu helfen." # i18n-allow),"en": ("Hi there! I am your personal assistant. "diff --git a/tests/unit/web/test_realtime_voice_preview.py b/tests/unit/web/test_realtime_voice_preview.pynew file mode 100644index 0000000000..e2b8ce067c--- /dev/null+++ b/tests/unit/web/test_realtime_voice_preview.py@@ -0,0 +1,215 @@+"""Contracts for POST /api/providers/{id}/realtime-voice-preview.++The route lets the user HEAR a realtime voice before pinning it. These tests+pin the validation surface (tier, catalog, credential) and the response+contract (playable WAV, clean 4xx/5xx on failure) with faked samplers — the+provider transports themselves are exercised live, not here.+"""++from __future__ import annotations++import io+import wave++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.core import config as cfg_mod+from jarvis.core.config import JarvisConfig+from jarvis.ui.web import provider_routes+from jarvis.ui.web.provider_routes import router+++def _app() -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ app.state.config = JarvisConfig()+ return app+++def _preview(client: TestClient, provider: str, **body: str):+ return client.post(+ f"/api/providers/{provider}/realtime-voice-preview", json=body+ )+++async def _silent_sampler(*_args, **_kwargs) -> tuple[bytes, int]:+ return b"\x01\x02" * 240, 24_000+++def test_every_cataloged_realtime_provider_has_a_preview_sampler() -> None:+ """Adding a realtime provider means adding its sampler too (parity)."""+ from jarvis.brain.model_catalog import REALTIME_VOICES++ assert set(REALTIME_VOICES) == set(provider_routes._REALTIME_PREVIEW_SAMPLERS)+++def test_unknown_provider_is_404() -> None:+ response = _preview(TestClient(_app()), "no-such-provider", voice="alloy")+ assert response.status_code == 404+++def test_non_realtime_tier_is_400() -> None:+ response = _preview(TestClient(_app()), "openai", voice="alloy")+ assert response.status_code == 400+++def test_missing_voice_is_400() -> None:+ response = _preview(TestClient(_app()), "openai-realtime", voice="")+ assert response.status_code == 400+++def test_uncatalogued_voice_is_422() -> None:+ response = _preview(+ TestClient(_app()), "openai-realtime", voice="not-a-voice"+ )+ assert response.status_code == 422+ assert response.json()["detail"]["code"] == "unsupported_realtime_voice"+++def test_uncatalogued_model_is_422() -> None:+ response = _preview(+ TestClient(_app()),+ "openai-realtime",+ voice="alloy",+ model="not-a-model",+ )+ assert response.status_code == 422+ assert response.json()["detail"]["code"] == "unsupported_realtime_model"+++def test_missing_credential_is_409(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _pid: None)+ response = _preview(TestClient(_app()), "openai-realtime", voice="alloy")+ assert response.status_code == 409+ assert "credentials" in response.json()["detail"]+++def test_happy_path_returns_playable_wav(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _pid: "sk-test")+ calls: list[dict[str, str]] = []++ async def sampler(+ api_key: str, *, model: str, voice: str, text: str, language: str+ ) -> tuple[bytes, int]:+ calls.append(+ {+ "api_key": api_key,+ "model": model,+ "voice": voice,+ "text": text,+ "language": language,+ }+ )+ return b"\x01\x02" * 240, 24_000++ monkeypatch.setitem(+ provider_routes._REALTIME_PREVIEW_SAMPLERS, "gemini-live", sampler+ )++ response = _preview(+ TestClient(_app()), "gemini-live", voice="Puck", language="de"+ )++ assert response.status_code == 200+ assert response.headers["content-type"] == "audio/wav"+ assert response.headers["cache-control"] == "no-store"+ with wave.open(io.BytesIO(response.content), "rb") as wav:+ assert wav.getframerate() == 24_000+ assert wav.getnchannels() == 1+ assert wav.getsampwidth() == 2+ assert wav.getnframes() == 240+ assert calls == [+ {+ "api_key": "sk-test",+ "model": "",+ "voice": "Puck",+ # The German sample sentence — the language pin must reach the+ # sampler as both the text AND the resolved language code.+ "text": provider_routes._TTS_PREVIEW_SAMPLES["de"],+ "language": "de",+ }+ ]+++def test_unknown_sample_language_falls_back_to_english(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _pid: "sk-test")+ seen: list[str] = []++ async def sampler(+ api_key: str, *, model: str, voice: str, text: str, language: str+ ) -> tuple[bytes, int]:+ seen.append(text)+ return b"\x00\x01", 24_000++ monkeypatch.setitem(+ provider_routes._REALTIME_PREVIEW_SAMPLERS, "gemini-live", sampler+ )++ response = _preview(+ TestClient(_app()), "gemini-live", voice="Puck", language="fr"+ )++ assert response.status_code == 200+ assert seen == [provider_routes._TTS_PREVIEW_SAMPLES["en"]]+++def test_sampler_failure_is_clean_502(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _pid: "sk-test")++ async def sampler(*_args, **_kwargs) -> tuple[bytes, int]:+ raise RuntimeError("quota exhausted")++ monkeypatch.setitem(+ provider_routes._REALTIME_PREVIEW_SAMPLERS, "openai-realtime", sampler+ )++ response = _preview(TestClient(_app()), "openai-realtime", voice="marin")+ assert response.status_code == 502+ assert "quota exhausted" in response.json()["detail"]+++def test_empty_audio_is_clean_502(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _pid: "sk-test")++ async def sampler(*_args, **_kwargs) -> tuple[bytes, int]:+ return b"", 24_000++ monkeypatch.setitem(+ provider_routes._REALTIME_PREVIEW_SAMPLERS, "gemini-live", sampler+ )++ response = _preview(TestClient(_app()), "gemini-live", voice="Charon")+ assert response.status_code == 502+ assert "no audio" in response.json()["detail"]+++def test_hung_sampler_times_out_as_502(monkeypatch: pytest.MonkeyPatch) -> None:+ import asyncio++ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _pid: "sk-test")+ monkeypatch.setattr(provider_routes, "_REALTIME_PREVIEW_TIMEOUT_S", 0.05)++ async def sampler(*_args, **_kwargs) -> tuple[bytes, int]:+ await asyncio.sleep(5.0)+ return b"\x00\x01", 24_000++ monkeypatch.setitem(+ provider_routes._REALTIME_PREVIEW_SAMPLERS, "openai-realtime", sampler+ )++ response = _preview(TestClient(_app()), "openai-realtime", voice="cedar")+ assert response.status_code == 502+ assert "timed out" in response.json()["detail"]+++def test_marin_and_cedar_are_in_the_openai_catalog() -> None:+ """The two Realtime-API-only voices must stay previewable (the whole+ reason the OpenAI sampler runs through a realtime session)."""+ from jarvis.brain.model_catalog import REALTIME_VOICES++ ids = {option.id for option in REALTIME_VOICES["openai-realtime"]}+ assert {"marin", "cedar"} <= ids