Skip to content

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

fix(realtime): reconnect active calls on engine switch

Ruben Lütke54c0af44d455
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 8710a45cc6..0ae3ad0f60 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -32,7 +32,9 @@ _REALTIME_SAFETY_APPENDIX = (
_LANGUAGE_NAMES = {"de": "German", "en": "English", "es": "Spanish"}
-def _session_instructions(language: str) -> str:
+def _session_instructions(
+ language: str, *, provider: str = "", model: str = ""
+) -> str:
from jarvis.brain.persona_loader import load_effective_persona_prompt
persona = load_effective_persona_prompt().strip()
@@ -40,6 +42,14 @@ def _session_instructions(language: str) -> str:
parts = [
persona,
_REALTIME_SAFETY_APPENDIX,
+ (
+ "Runtime identity: this voice session is using the Realtime engine"
+ + (f", provider {provider}" if provider else "")
+ + (f", model {model}" if model else "")
+ + ". If the user asks which engine, provider, or model is active, "
+ "answer from this runtime identity exactly; do not describe the "
+ "classic text brain configuration."
+ ),
f"Reply only in {language_name} for this turn.",
]
return "\n\n".join(part for part in parts if part)
@@ -140,6 +150,7 @@ class RealtimeVoiceSession:
{
"type": "audio_ready",
"provider": self.active_provider,
+ "model": self._active_model,
"input_sample_rate": self._input_sample_rate,
"output_sample_rate": int(
getattr(self._provider, "output_sample_rate", 24_000) or 24_000
@@ -177,7 +188,11 @@ class RealtimeVoiceSession:
input_rate = int(getattr(provider, "input_sample_rate", 16_000) or 16_000)
output_rate = int(getattr(provider, "output_sample_rate", 24_000) or 24_000)
session_config = RealtimeSessionConfig(
- instructions=_session_instructions(self._language),
+ instructions=_session_instructions(
+ self._language,
+ provider=str(getattr(provider, "name", "") or ""),
+ model=model,
+ ),
language=self._language,
model=model,
voice=voice,
@@ -261,7 +276,11 @@ class RealtimeVoiceSession:
self._language = new_language
self._gate = ScrubHoldGate(new_language)
await self._session.update_session(
- instructions=_session_instructions(new_language),
+ instructions=_session_instructions(
+ new_language,
+ provider=self.active_provider,
+ model=self._active_model,
+ ),
language=new_language,
)
if self._tool_bridge is not None:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 4a626a588a..e20070305c 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1438,6 +1438,16 @@ class SpeechPipeline:
self._call_event = asyncio.Event()
self._hangup_event = asyncio.Event()
self._current_voice_session_id: str | None = None
+ # Configured voice mode and effective in-flight engine are deliberately
+ # separate. A settings write can happen while a call is already open;
+ # without this runtime state the UI used to report "Realtime" while the
+ # existing call continued through classic STT -> Brain -> TTS.
+ self._active_voice_mode: str | None = None
+ self._active_realtime_provider: str = ""
+ self._active_realtime_model: str = ""
+ self._voice_engine_transitioning: bool = False
+ self._reopen_after_engine_change: bool = False
+ self._engine_change_reason: str = ""
# Optionale Event-Bus-Integration — wenn None, sind alle
# _transition/_emit-Calls no-ops (Rueckwaertskompatibilitaet)
self._bus = bus
@@ -4092,6 +4102,88 @@ class SpeechPipeline:
self._call_event.set()
return True
+ def _configured_voice_mode(self) -> str:
+ """Return the normalized configured engine for the next session."""
+ mode = str(
+ getattr(
+ getattr(getattr(self, "_config", None), "voice", None),
+ "mode",
+ "pipeline",
+ )
+ or "pipeline"
+ ).strip().lower()
+ return "realtime" if mode == "realtime" else "pipeline"
+
+ def voice_engine_status(self) -> dict[str, Any]:
+ """Snapshot configured and effective voice-engine state for the UI.
+
+ ``configured_mode`` is the user's selection for new calls.
+ ``active_session_mode`` is what the currently open call actually uses.
+ They may differ while a controlled reconnect is in progress or when
+ every realtime provider failed and classic fallback was entered.
+ """
+ active_mode = getattr(self, "_active_voice_mode", None)
+ session_id = getattr(self, "_current_voice_session_id", None)
+ return {
+ "configured_mode": self._configured_voice_mode(),
+ "session_active": bool(session_id),
+ "session_id": str(session_id or ""),
+ "active_session_mode": active_mode,
+ "active_session_provider": (
+ getattr(self, "_active_realtime_provider", "")
+ if active_mode == "realtime"
+ else ""
+ ),
+ "active_session_model": (
+ getattr(self, "_active_realtime_model", "")
+ if active_mode == "realtime"
+ else ""
+ ),
+ "transitioning": bool(
+ getattr(self, "_voice_engine_transitioning", False)
+ or getattr(self, "_reopen_after_engine_change", False)
+ ),
+ }
+
+ def apply_voice_mode(self, mode: str) -> bool:
+ """Apply a mode selection and reconnect an incompatible active call.
+
+ Returns ``True`` when the current session was scheduled for a controlled
+ close-and-reopen. An idle pipeline simply uses the new value on its next
+ activation.
+ """
+ normalized = str(mode or "").strip().lower()
+ if normalized not in {"pipeline", "realtime"}:
+ raise ValueError(f"Unsupported voice mode: {mode!r}")
+ voice = getattr(getattr(self, "_config", None), "voice", None)
+ if voice is not None:
+ voice.mode = normalized
+ active_mode = getattr(self, "_active_voice_mode", None)
+ if self._state != PipelineState.IDLE and active_mode != normalized:
+ return self._schedule_engine_reopen(f"mode:{normalized}")
+ return False
+
+ def reconnect_realtime_session(self, *, reason: str) -> bool:
+ """Reconnect an active realtime call after provider/model changes."""
+ if self._configured_voice_mode() != "realtime":
+ return False
+ if self._state == PipelineState.IDLE:
+ return False
+ return self._schedule_engine_reopen(reason)
+
+ def _schedule_engine_reopen(self, reason: str) -> bool:
+ if self._state == PipelineState.IDLE:
+ return False
+ self._reopen_after_engine_change = True
+ self._engine_change_reason = str(reason or "configuration_change")
+ self._voice_engine_transitioning = True
+ log.info(
+ "Voice engine changed during an active session; reconnecting (%s).",
+ self._engine_change_reason,
+ )
+ self._trigger_voice_hangup()
+ return True
+
def _post_hangup_lock_seconds(self) -> float:
"""Wake-lock duration for the session that just ended (one-shot).
@@ -4727,6 +4819,10 @@ class SpeechPipeline:
self._session_has_assistant_spoken = False
session_id = str(uuid4())
self._current_voice_session_id = session_id
+ self._active_voice_mode = self._configured_voice_mode()
+ self._active_realtime_provider = ""
+ self._active_realtime_model = ""
+ self._voice_engine_transitioning = self._active_voice_mode == "realtime"
session_started_at = time.time()
wake_keyword = (
"push_to_talk"
@@ -4743,16 +4839,28 @@ class SpeechPipeline:
)
)
hangup_reason = HANGUP_ERROR
- log.info("📞 ANRUF angenommen")
- # Orb einblenden & Mic-Pulsieren aktivieren
+ log.info("Voice session accepted (configured engine=%s).", self._active_voice_mode)
+ # Reveal the voice surface and enable microphone feedback.
await self._set_turn_state(TurnTakingState.LISTENING)
try:
await self._play_ack(ptt=self._ptt_mode)
hangup_reason = await self._active_session()
except Exception as exc: # noqa: BLE001
- log.exception("Session-Fehler: %s", exc)
+ log.exception("Voice session failed: %s", exc)
finally:
+ reopen_after_engine_change = bool(
+ getattr(self, "_reopen_after_engine_change", False)
+ )
+ engine_change_reason = str(
+ getattr(self, "_engine_change_reason", "")
+ )
+ self._reopen_after_engine_change = False
+ self._engine_change_reason = ""
self._current_voice_session_id = None
+ self._active_voice_mode = None
+ self._active_realtime_provider = ""
+ self._active_realtime_model = ""
+ self._voice_engine_transitioning = False
# PTT is one-shot per hold — disarm before the next session so a
# stale flag can never reroute a later wake-word session into
# the raw-recording path.
@@ -4779,15 +4887,29 @@ class SpeechPipeline:
)
)
self._state = PipelineState.IDLE
- # Supervisor zurueck auf IDLE — Orb verschwindet
+ # Return the supervisor to IDLE and hide the active surface.
await self._set_turn_state(TurnTakingState.IDLE)
- # Disconnect-Sound als hörbares Hangup-Signal (earcon — gated
- # by the global "Sound effects" switch).
- await self._play_earcon(DISCONNECT_PCM)
- # Cooldown setzen damit Speaker-Echo nicht sofort re-triggert.
- lock_s = self._post_hangup_lock_seconds()
- self._wake_lock_until = time.time() + lock_s
- log.info("📵 AUFGELEGT — zurück zu IDLE (Wake-Lock %.1fs).", lock_s)
+ if reopen_after_engine_change and self._activation_allowed():
+ # An internal engine reconnect has no response tail to
+ # protect against. Re-arm immediately with the latest
+ # config; a disconnect earcon would leak into the new mic.
+ self._explicit_hard_hangup = False
+ self._wake_lock_until = 0.0
+ self._last_wake_keyword = "engine_switch"
+ self._call_event.set()
+ log.info(
+ "Voice session re-armed after engine change (%s).",
+ engine_change_reason or "configuration_change",
+ )
+ else:
+ # Normal disconnect earcon followed by speaker-echo lock.
+ await self._play_earcon(DISCONNECT_PCM)
+ lock_s = self._post_hangup_lock_seconds()
+ self._wake_lock_until = time.time() + lock_s
+ log.info(
+ "Voice session ended; returning to idle (wake lock %.1fs).",
+ lock_s,
+ )
def _earcons_enabled(self) -> bool:
"""Whether synthesized UI earcons may play.
@@ -4854,20 +4976,23 @@ class SpeechPipeline:
# edge is its endpoint and the duplex protocols do not expose one
# provider-neutral commit primitive. Normal wake/hotkey sessions
# use Realtime when selected.
+ self._active_voice_mode = "pipeline"
+ self._active_realtime_provider = ""
+ self._active_realtime_model = ""
+ self._voice_engine_transitioning = False
return await self._ptt_session()
- requested_mode = str(
- getattr(
- getattr(getattr(self, "_config", None), "voice", None),
- "mode",
- "pipeline",
- )
- or "pipeline"
- ).strip().lower()
+ requested_mode = self._configured_voice_mode()
+ self._active_voice_mode = requested_mode
+ self._voice_engine_transitioning = requested_mode == "realtime"
if requested_mode == "realtime":
realtime_reason = await self._active_realtime_session()
if realtime_reason is not None:
return realtime_reason
await self._speak_realtime_unavailable()
+ self._active_voice_mode = "pipeline"
+ self._active_realtime_provider = ""
+ self._active_realtime_model = ""
+ self._voice_engine_transitioning = False
async with MicrophoneCapture(
device=self._input_device,
max_queue_chunks=REALTIME_QUEUE_CHUNKS,
@@ -5035,9 +5160,16 @@ class SpeechPipeline:
playback.set_sample_rate(
int(message.get("output_sample_rate", 24_000) or 24_000)
)
+ self._active_voice_mode = "realtime"
+ self._active_realtime_provider = str(
+ message.get("provider", "") or ""
+ )
+ self._active_realtime_model = str(message.get("model", "") or "")
+ self._voice_engine_transitioning = False
log.info(
- "Realtime desktop session ready: provider=%s input=%sHz output=%sHz",
+ "Realtime desktop session ready: provider=%s model=%s input=%sHz output=%sHz",
message.get("provider", "unknown"),
+ message.get("model", "unknown"),
message.get("input_sample_rate", "unknown"),
message.get("output_sample_rate", "unknown"),
)
diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
index f095a5676c..1a93296713 100644
--- a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts
@@ -1,10 +1,22 @@
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
-type VoiceModeResp = { mode: string; realtime_available: boolean; active_provider: string | null };
+import { useEventStore } from "@/store/events";
+
+type VoiceModeResp = {
+ mode: string;
+ realtime_available: boolean;
+ active_provider: string | null;
+ session_active: boolean;
+ active_session_mode: "pipeline" | "realtime" | null;
+ active_session_provider: string;
+ active_session_model: string;
+ transitioning: boolean;
+};
export function useVoiceMode() {
const qc = useQueryClient();
+ const events = useEventStore((state) => state.events);
const q = useQuery<VoiceModeResp>({
queryKey: ["voice-mode"],
queryFn: async () => (await fetch("/api/settings/voice-mode")).json(),
@@ -50,9 +62,32 @@ export function useVoiceMode() {
return () => window.removeEventListener("jarvis:realtime-switched", onRealtimeSwitched);
}, [qc]);
+ // Configured mode and effective in-flight mode are distinct. Refresh the
+ // runtime snapshot on voice boundaries and on the accepted realtime
+ // handshake so the switch never labels an old classic call as Realtime.
+ const lastRuntimeEvent = useMemo(
+ () =>
+ events.find((event) =>
+ ["VoiceSessionStarted", "RealtimeSessionReady", "VoiceSessionEnded"].includes(
+ event.name,
+ ),
+ ) ?? null,
+ [events],
+ );
+ useEffect(() => {
+ if (lastRuntimeEvent !== null) {
+ qc.invalidateQueries({ queryKey: ["voice-mode"] });
+ }
+ }, [lastRuntimeEvent, qc]);
+
return {
mode: q.data?.mode ?? "pipeline",
realtimeAvailable: q.data?.realtime_available ?? false,
+ sessionActive: q.data?.session_active ?? false,
+ activeSessionMode: q.data?.active_session_mode ?? null,
+ activeSessionProvider: q.data?.active_session_provider ?? "",
+ activeSessionModel: q.data?.active_session_model ?? "",
+ transitioning: q.data?.transitioning ?? false,
setMode: m.mutate,
isLoading: q.isLoading,
isSaving: m.isPending,
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 0e58f9b02e..a001950ea6 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -893,10 +893,15 @@
"mode_needs_key": "Realtime braucht einen API-Key — unten einen hinzufügen, dann umschalten.",
"mode_desc_pipeline": "Drei Schritte: Sprache zu Text, das Brain denkt, Text zu Sprache.",
"mode_desc_realtime": "Ein Modell hört zu und antwortet im selben Live-Audiostrom.",
+ "runtime_switching": "Die aktuelle Sprach-Session wird mit der ausgewählten Engine neu gestartet…",
+ "runtime_idle": "Keine Sprach-Session ist aktiv. Die Auswahl gilt für die nächste Session.",
+ "runtime_realtime": "Aktuelle Session: Realtime",
+ "runtime_pipeline": "Aktuelle Session: Pipeline",
+ "runtime_fallback_pipeline": "Die aktuelle Session ist auf die Pipeline zurückgefallen; Realtime bedient diesen Anruf nicht.",
"cat_brain_desc": "Das Modell, das Chat, Routing und Computer-Use antreibt.",
"cat_tts_desc": "Die Stimme, mit der Jarvis spricht.",
"cat_stt_desc": "Wie Jarvis deine Sprache in Text umwandelt.",
- "cat_realtime_desc": "Die Vollduplex-Sprache-zu-Sprache-Engine (OpenAI Realtime). Nutzt deinen vorhandenen OpenAI-Key mit. Standardmäßig AUS, bis der Browser-Client angebunden ist (Phase 2).",
+ "cat_realtime_desc": "Vollduplex-Sprache-zu-Sprache über jeden eingerichteten Realtime-Provider, auf dem Desktop oder im Browser.",
"cat_computer_use_desc": "Computer-Use liest deinen Bildschirm; wähle, welcher Provider das plant — unabhängig von deinem Chat-Brain. Realtime-Modelle können den Bildschirm nicht sehen, deshalb läuft es auch dort darüber.",
"cat_subagents_title": "Jarvis-Agents",
"cat_subagents_desc": "Wähle, welcher Provider schwere Hintergrund-Aufgaben übernimmt.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index ba3d2cc4ab..ee863b3a7d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -893,10 +893,15 @@
"mode_needs_key": "Realtime needs an API key — add one below to switch.",
"mode_desc_pipeline": "Three steps: speech-to-text, the Brain thinks, text-to-speech.",
"mode_desc_realtime": "One model listens and answers in the same live audio stream.",
+ "runtime_switching": "Restarting the current voice session with the selected engine…",
+ "runtime_idle": "No voice session is active. This selection applies to the next one.",
+ "runtime_realtime": "Current session: Realtime",
+ "runtime_pipeline": "Current session: Pipeline",
+ "runtime_fallback_pipeline": "Current session fell back to Pipeline; Realtime is not serving this call.",
"cat_brain_desc": "The model that powers chat, routing, and Computer-Use.",
"cat_tts_desc": "The voice Jarvis speaks with.",
"cat_stt_desc": "How Jarvis turns your speech into text.",
- "cat_realtime_desc": "The full-duplex speech-to-speech engine (OpenAI Realtime). Reuses your OpenAI key. Default-OFF until the browser client is wired in (Phase 2).",
+ "cat_realtime_desc": "Full-duplex speech-to-speech through any configured Realtime provider, on desktop or in the browser.",
"cat_computer_use_desc": "Computer-Use reads your screen; pick which provider plans it — independent of your chat Brain. Realtime models can't see the screen, so this runs it there too.",
"cat_subagents_title": "Jarvis-Agents",
"cat_subagents_desc": "Choose which provider runs heavy background tasks.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index fa66329cd8..36d78d8d01 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -893,10 +893,15 @@
"mode_needs_key": "Tiempo real necesita una clave API — añade una abajo para cambiar.",
"mode_desc_pipeline": "Tres pasos: voz a texto, el Brain piensa, texto a voz.",
"mode_desc_realtime": "Un solo modelo escucha y responde en el mismo flujo de audio en vivo.",
+ "runtime_switching": "Reiniciando la sesión de voz actual con el motor seleccionado…",
+ "runtime_idle": "No hay ninguna sesión de voz activa. Esta selección se aplicará a la siguiente.",
+ "runtime_realtime": "Sesión actual: Tiempo real",
+ "runtime_pipeline": "Sesión actual: Pipeline",
+ "runtime_fallback_pipeline": "La sesión actual volvió a Pipeline; Tiempo real no está atendiendo esta llamada.",
"cat_brain_desc": "El modelo que impulsa el chat, el enrutamiento y Computer-Use.",
"cat_tts_desc": "La voz con la que habla Jarvis.",
"cat_stt_desc": "Cómo convierte Jarvis tu voz en texto.",
- "cat_realtime_desc": "El motor de voz a voz en tiempo real (dúplex completo, OpenAI Realtime). Reutiliza tu clave de OpenAI. Desactivado por defecto hasta que el cliente de navegador esté conectado (Fase 2).",
+ "cat_realtime_desc": "Voz a voz dúplex completo mediante cualquier proveedor de tiempo real configurado, en escritorio o navegador.",
"cat_computer_use_desc": "Computer-Use lee tu pantalla; elige qué proveedor lo planifica, independientemente de tu Brain de chat. Los modelos Realtime no pueden ver la pantalla, así que esto también se ejecuta ahí.",
"cat_subagents_title": "Jarvis-Agents",
"cat_subagents_desc": "Elige qué proveedor ejecuta las tareas pesadas en segundo plano.",
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 8fff48f49b..117677a56c 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -156,6 +156,11 @@ export function ApiKeysView() {
const {
mode: liveMode,
realtimeAvailable,
+ sessionActive,
+ activeSessionMode,
+ activeSessionProvider,
+ activeSessionModel,
+ transitioning,
setMode: setVoiceMode,
isLoading: liveModeLoading,
} = useVoiceMode();
@@ -191,6 +196,11 @@ export function ApiKeysView() {
mode={engineMode}
liveMode={liveMode}
realtimeAvailable={realtimeAvailable}
+ sessionActive={sessionActive}
+ activeSessionMode={activeSessionMode}
+ activeSessionProvider={activeSessionProvider}
+ activeSessionModel={activeSessionModel}
+ transitioning={transitioning}
onSelect={setEngineMode}
onSetVoiceMode={setVoiceMode}
/>
@@ -271,6 +281,11 @@ function EngineModeSwitch({
mode,
liveMode,
realtimeAvailable,
+ sessionActive,
+ activeSessionMode,
+ activeSessionProvider,
+ activeSessionModel,
+ transitioning,
onSelect,
onSetVoiceMode,
}: {
@@ -279,6 +294,12 @@ function EngineModeSwitch({
liveMode: string;
/** Whether SOME realtime family (OpenAI/Gemini) has a key configured. */
realtimeAvailable: boolean;
+ /** What the currently open voice session actually uses. */
+ sessionActive: boolean;
+ activeSessionMode: "pipeline" | "realtime" | null;
+ activeSessionProvider: string;
+ activeSessionModel: string;
+ transitioning: boolean;
onSelect: (mode: VoiceEngineMode) => void;
/** Persists `[voice].mode` — gated per the rule above. */
onSetVoiceMode: (mode: string) => void;
@@ -289,6 +310,20 @@ function EngineModeSwitch({
{ key: "realtime", label: t("apikeys_view.mode_realtime"), icon: Radio },
];
const liveIndex = liveMode === "realtime" ? 1 : 0;
+ const runtimeDetail = [activeSessionProvider, activeSessionModel]
+ .filter(Boolean)
+ .join(" · ");
+ const runtimeText = transitioning
+ ? t("apikeys_view.runtime_switching")
+ : sessionActive && activeSessionMode === "realtime"
+ ? `${t("apikeys_view.runtime_realtime")}${runtimeDetail ? ` · ${runtimeDetail}` : ""}`
+ : sessionActive && activeSessionMode === "pipeline" && liveMode === "realtime"
+ ? t("apikeys_view.runtime_fallback_pipeline")
+ : sessionActive && activeSessionMode === "pipeline"
+ ? t("apikeys_view.runtime_pipeline")
+ : t("apikeys_view.runtime_idle");
+ const runtimeMatchesSelection =
+ !sessionActive || activeSessionMode === null || activeSessionMode === liveMode;
function handleSelect(seg: VoiceEngineMode) {
onSelect(seg);
@@ -357,6 +392,32 @@ function EngineModeSwitch({
? t("apikeys_view.mode_desc_realtime")
: t("apikeys_view.mode_desc_pipeline")}
</p>
+ <div
+ className="mt-2 flex max-w-64 items-start justify-end gap-1.5 text-right text-[11px] leading-snug"
+ aria-live="polite"
+ data-testid="voice-engine-runtime-status"
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ "mt-1 h-1.5 w-1.5 shrink-0 rounded-full",
+ transitioning
+ ? "animate-pulse bg-amber-400 motion-reduce:animate-none"
+ : runtimeMatchesSelection
+ ? "bg-emerald-400"
+ : "bg-amber-400",
+ )}
+ />
+ <span
+ className={cn(
+ runtimeMatchesSelection && !transitioning
+ ? "text-muted-foreground"
+ : "text-amber-300",
+ )}
+ >
+ {runtimeText}
+ </span>
+ </div>
</div>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx
index 20e34b33e4..f5e7cc6a07 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx
@@ -36,11 +36,20 @@ vi.mock("@/hooks/useProviders", () => ({
// `vi.mock` call, matching this file's existing hoisting pattern) so the
// "realtime unavailable" describe block below can flip it.
let mockRealtimeAvailable = true;
+let mockVoiceMode = "pipeline";
+let mockSessionActive = false;
+let mockActiveSessionMode: "pipeline" | "realtime" | null = null;
+let mockTransitioning = false;
const putVoiceMode = vi.fn();
vi.mock("@/hooks/useVoiceMode", () => ({
useVoiceMode: () => ({
- mode: "pipeline",
+ mode: mockVoiceMode,
realtimeAvailable: mockRealtimeAvailable,
+ sessionActive: mockSessionActive,
+ activeSessionMode: mockActiveSessionMode,
+ activeSessionProvider: "",
+ activeSessionModel: "",
+ transitioning: mockTransitioning,
setMode: putVoiceMode,
isLoading: false,
isSaving: false,
@@ -53,6 +62,10 @@ afterEach(() => {
cleanup();
vi.clearAllMocks();
mockRealtimeAvailable = true;
+ mockVoiceMode = "pipeline";
+ mockSessionActive = false;
+ mockActiveSessionMode = null;
+ mockTransitioning = false;
});
describe("ApiKeysView two-mode", () => {
@@ -78,6 +91,18 @@ describe("ApiKeysView two-mode", () => {
expect(realtimeSegment.textContent).not.toMatch(/active/i);
});
+ it("shows when the selected Realtime mode is still served by Pipeline", () => {
+ mockVoiceMode = "realtime";
+ mockSessionActive = true;
+ mockActiveSessionMode = "pipeline";
+
+ render(<ApiKeysView />);
+
+ expect(screen.getByTestId("voice-engine-runtime-status").textContent).toMatch(
+ /fell back to Pipeline/i,
+ );
+ });
+
it("switching to Realtime mode shows only Realtime/Subagents/Advanced and persists voice-mode (available)", () => {
render(<ApiKeysView />);
fireEvent.click(screen.getByRole("button", { name: /^realtime$/i })); // the segment
diff --git a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx
index ba47072cc1..2fa98fff06 100644
--- a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx
@@ -16,8 +16,31 @@ import { useT } from "@/i18n";
*/
export function RealtimeVoiceGroup() {
const t = useT();
- const { mode, realtimeAvailable, setMode, isLoading, isSaving } = useVoiceMode();
+ const {
+ mode,
+ realtimeAvailable,
+ sessionActive,
+ activeSessionMode,
+ activeSessionProvider,
+ activeSessionModel,
+ transitioning,
+ setMode,
+ isLoading,
+ isSaving,
+ } = useVoiceMode();
const on = mode === "realtime";
+ const runtimeDetail = [activeSessionProvider, activeSessionModel]
+ .filter(Boolean)
+ .join(" · ");
+ const runtimeText = transitioning
+ ? t("apikeys_view.runtime_switching")
+ : sessionActive && activeSessionMode === "realtime"
+ ? `${t("apikeys_view.runtime_realtime")}${runtimeDetail ? ` · ${runtimeDetail}` : ""}`
+ : sessionActive && activeSessionMode === "pipeline" && on
+ ? t("apikeys_view.runtime_fallback_pipeline")
+ : sessionActive
+ ? t("apikeys_view.runtime_pipeline")
+ : t("apikeys_view.runtime_idle");
return (
<div className="mt-2 rounded-lg border border-border bg-card/60 p-4">
<div className="flex items-start gap-3">
@@ -36,6 +59,9 @@ export function RealtimeVoiceGroup() {
? t("settings_view.realtime_voice.description")
: t("settings_view.realtime_voice.unavailable")}
</p>
+ <p className="mt-1.5 text-[11px] text-muted-foreground" aria-live="polite">
+ {runtimeText}
+ </p>
</div>
</div>
</div>
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index c433994b8b..f0f9ab85c8 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -225,6 +225,7 @@ class RealtimeOptionsSaveResponse(BaseModel):
model: str
voice: str
restart_required: bool = False
+ session_restarted: bool = False
# ----------------------------------------------------------------------
@@ -1702,10 +1703,11 @@ async def set_realtime_options(
"""Pin the model and/or voice for a realtime provider.
Persists to ``[brain.providers.<id>].model`` / ``.voice`` (+ drift-soll)
- and updates the in-memory config so the next realtime session picks it up
- with no process restart (``session.py::_open`` reads it fresh per
- session). Only the fields present in the body are written — an omitted
- field leaves its current value untouched.
+ and updates the in-memory config. If this provider owns the active realtime
+ call, that call is closed and reopened immediately; otherwise the selection
+ applies to the next session. No process restart is required. Only fields
+ present in the body are written — an omitted field leaves its current value
+ untouched.
"""
spec = _require_realtime_provider(provider_id)
if not _is_credential_present(spec):
@@ -1752,6 +1754,17 @@ async def set_realtime_options(
SecretConfigured(key=f"brain.providers.{provider_id}", action="set"),
)
current_model, current_voice = _current_realtime_selection(cfg, provider_id)
+ selected_provider = str(
+ getattr(getattr(getattr(cfg, "brain", None), "realtime", None), "provider", "")
+ or ""
+ )
+ session_restarted = False
+ if selected_provider == provider_id:
+ from jarvis.ui.web.voice_runtime import reconnect_realtime
+
+ session_restarted = reconnect_realtime(
+ request, reason=f"realtime_options:{provider_id}"
+ )
_invalidate_section_health_state(request)
return RealtimeOptionsSaveResponse(
ok=True,
@@ -1759,6 +1772,7 @@ async def set_realtime_options(
model=current_model,
voice=current_voice,
restart_required=False,
+ session_restarted=session_restarted,
)
@@ -2379,11 +2393,11 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
@router.post("/realtime/switch")
async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
- """Switch the active realtime provider for the next voice session.
+ """Switch the active realtime provider.
The desktop and browser runtimes resolve ``voice.mode`` plus the selected
- provider when each new voice session opens. An already-open duplex stream
- keeps its negotiated provider, but no application restart is required.
+ provider whenever a voice session opens. An active desktop call is closed
+ and reopened against the new selection; no application restart is required.
Realtime is cross-family (AP-22), so validation is registry/tier based.
Activating a realtime provider also makes Realtime the ACTIVE voice mode
@@ -2454,6 +2468,12 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
await _emit(request, SecretConfigured(key="brain.realtime.provider", action="set"))
await _emit(request, SecretConfigured(key="voice.mode", action="set"))
+ from jarvis.ui.web.voice_runtime import reconnect_realtime
+
+ session_restarted = reconnect_realtime(
+ request, reason=f"realtime_provider:{body.provider}"
+ )
+
_invalidate_section_health_state(request)
return {
"ok": True,
@@ -2466,6 +2486,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"persisted": body.persist and voice_mode_write_ok,
"voice_mode_persisted": voice_mode_write_ok,
"restart_required": False,
+ "session_restarted": session_restarted,
}
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 7cf99b4126..d9a14a08a5 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -151,10 +151,20 @@ async def get_voice_mode(request: Request) -> dict[str, object]:
# session would actually build (Gemini-only users now get `true` too,
# not just OpenAI — Feature A2).
prov = _realtime_available_provider(cfg)
+ from jarvis.ui.web.voice_runtime import voice_engine_status
+
+ runtime = voice_engine_status(request)
return {
"mode": mode,
"realtime_available": prov is not None,
"active_provider": prov,
+ "session_active": bool(runtime.get("session_active", False)),
+ "active_session_mode": runtime.get("active_session_mode"),
+ "active_session_provider": str(
+ runtime.get("active_session_provider", "") or ""
+ ),
+ "active_session_model": str(runtime.get("active_session_model", "") or ""),
+ "transitioning": bool(runtime.get("transitioning", False)),
}
@@ -176,6 +186,10 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, obj
except Exception as exc: # noqa: BLE001 — frozen model is not an error
log.debug("in-memory cfg.voice.mode update skipped: %s", exc)
+ from jarvis.ui.web.voice_runtime import apply_voice_mode
+
+ session_restarted = apply_voice_mode(request, body.mode)
+
persisted = False
if body.persist:
try:
@@ -186,7 +200,12 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, obj
except Exception as exc: # noqa: BLE001
log.warning("voice-mode persist failed (live switch still applied): %s", exc)
- return {"ok": True, "mode": body.mode, "persisted": persisted}
+ return {
+ "ok": True,
+ "mode": body.mode,
+ "persisted": persisted,
+ "session_restarted": session_restarted,
+ }
# ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/voice_runtime.py b/jarvis/ui/web/voice_runtime.py
new file mode 100644
index 0000000000..903de4e5c4
--- /dev/null
+++ b/jarvis/ui/web/voice_runtime.py
@@ -0,0 +1,73 @@
+"""Bridge voice-setting routes to the effective desktop speech runtime.
+
+The persisted/configured engine and an already-open call are separate pieces
+of state. These helpers keep routes honest without making headless/browser-only
+deployments depend on the desktop speech stack.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+
+def _pipeline(request: Any) -> Any | None:
+ app = getattr(request, "app", None)
+ state = getattr(app, "state", None)
+ return getattr(state, "speech_pipeline", None)
+
+
+def voice_engine_status(request: Any) -> dict[str, Any]:
+ pipeline = _pipeline(request)
+ snapshot = getattr(pipeline, "voice_engine_status", None)
+ if not callable(snapshot):
+ return {
+ "session_active": False,
+ "session_id": "",
+ "active_session_mode": None,
+ "active_session_provider": "",
+ "active_session_model": "",
+ "transitioning": False,
+ }
+ try:
+ value = snapshot()
+ except Exception: # noqa: BLE001 -- status must never break settings
+ log.debug("Voice-engine status snapshot failed", exc_info=True)
+ return {
+ "session_active": False,
+ "session_id": "",
+ "active_session_mode": None,
+ "active_session_provider": "",
+ "active_session_model": "",
+ "transitioning": False,
+ }
+ return dict(value) if isinstance(value, dict) else {}
+
+
+def apply_voice_mode(request: Any, mode: str) -> bool:
+ pipeline = _pipeline(request)
+ apply = getattr(pipeline, "apply_voice_mode", None)
+ if not callable(apply):
+ return False
+ try:
+ return bool(apply(mode))
+ except Exception: # noqa: BLE001 -- config remains applied for next session
+ log.warning("Live voice-mode application failed", exc_info=True)
+ return False
+
+
+def reconnect_realtime(request: Any, *, reason: str) -> bool:
+ pipeline = _pipeline(request)
+ reconnect = getattr(pipeline, "reconnect_realtime_session", None)
+ if not callable(reconnect):
+ return False
+ try:
+ return bool(reconnect(reason=reason))
+ except Exception: # noqa: BLE001 -- new config still applies next session
+ log.warning("Live realtime reconnect failed", exc_info=True)
+ return False
+
+
+__all__ = ["apply_voice_mode", "reconnect_realtime", "voice_engine_status"]
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 925cff4123..e7a50252dd 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -134,10 +134,11 @@ async def test_open_injects_active_providers_model_and_voice():
"fake": SimpleNamespace(model="gpt-realtime-2.1", voice="echo"),
"other-provider": SimpleNamespace(model="should-not-be-used", voice="should-not-be-used"),
}
+ messages = []
sess = RealtimeVoiceSession(
session_id="s-model-voice",
send_binary=lambda b: asyncio.sleep(0),
- send_json=lambda m: asyncio.sleep(0),
+ send_json=lambda message: messages.append(message) or asyncio.sleep(0),
provider=FakeProvider([]),
config=_cfg(providers=providers),
bus=None,
@@ -149,6 +150,10 @@ async def test_open_injects_active_providers_model_and_voice():
opened_cfg = sess._provider.opened_with
assert opened_cfg.model == "gpt-realtime-2.1"
assert opened_cfg.voice == "echo"
+ assert "Realtime engine, provider fake, model gpt-realtime-2.1" in opened_cfg.instructions
+ ready = next(message for message in messages if message["type"] == "audio_ready")
+ assert ready["provider"] == "fake"
+ assert ready["model"] == "gpt-realtime-2.1"
@pytest.mark.asyncio
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index d560092fda..aee2376dc9 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -99,6 +99,13 @@ def _pipe(mode: str = "realtime") -> SpeechPipeline:
pipe._hangup_event = asyncio.Event()
pipe._continue_listening_after_response = False
pipe._current_voice_session_id = "desktop-session"
+ pipe._active_voice_mode = mode
+ pipe._active_realtime_provider = ""
+ pipe._active_realtime_model = ""
+ pipe._voice_engine_transitioning = False
+ pipe._reopen_after_engine_change = False
+ pipe._engine_change_reason = ""
+ pipe._state = pipeline_mod.PipelineState.IDLE
pipe._muted = False
pipe._input_suppressed_until_ns = 0
pipe._ptt_mode = False
@@ -211,3 +218,33 @@ async def test_pipeline_mode_never_enters_realtime_branch(
monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic())
assert await asyncio.wait_for(pipe._active_session(), timeout=2.0) == HANGUP_SHUTDOWN
+
+
+def test_live_mode_change_schedules_active_call_for_reopen() -> None:
+ pipe = _pipe(mode="pipeline")
+ pipe._state = pipeline_mod.PipelineState.ACTIVE
+ pipe._active_voice_mode = "pipeline"
+ hangups: list[bool] = []
+ pipe._trigger_voice_hangup = lambda: hangups.append(True) # type: ignore[method-assign]
+
+ restarted = pipe.apply_voice_mode("realtime")
+
+ assert restarted is True
+ assert pipe._config.voice.mode == "realtime"
+ assert pipe._reopen_after_engine_change is True
+ assert pipe._voice_engine_transitioning is True
+ assert hangups == [True]
+
+
+def test_runtime_status_never_confuses_configured_and_effective_mode() -> None:
+ pipe = _pipe(mode="realtime")
+ pipe._state = pipeline_mod.PipelineState.ACTIVE
+ pipe._active_voice_mode = "pipeline"
+ pipe._current_voice_session_id = "classic-call"
+
+ status = pipe.voice_engine_status()
+
+ assert status["configured_mode"] == "realtime"
+ assert status["active_session_mode"] == "pipeline"
+ assert status["session_active"] is True
+ assert status["active_session_provider"] == ""
diff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.py
index a0789a58c2..09ebabe0ed 100644
--- a/tests/unit/web/test_voice_mode_route.py
+++ b/tests/unit/web/test_voice_mode_route.py
@@ -64,6 +64,8 @@ def test_get_voice_mode(monkeypatch):
assert body["mode"] == "realtime"
assert body["realtime_available"] is True
assert body["active_provider"] == "openai-realtime"
+ assert body["session_active"] is False
+ assert body["active_session_mode"] is None
def test_get_voice_mode_cross_family_gemini_only(monkeypatch):
@@ -124,6 +126,66 @@ def test_put_voice_mode_updates_live_and_persists(monkeypatch):
client = TestClient(app)
r = client.put("/api/settings/voice-mode", json={"mode": "realtime", "persist": True})
assert r.status_code == 200
- assert r.json() == {"ok": True, "mode": "realtime", "persisted": True}
+ assert r.json() == {
+ "ok": True,
+ "mode": "realtime",
+ "persisted": True,
+ "session_restarted": False,
+ }
assert app.state.config.voice.mode == "realtime"
assert persisted["called"] is True
+
+
+def test_put_voice_mode_restarts_an_incompatible_active_session(monkeypatch):
+ import jarvis.realtime.factory as rf
+
+ monkeypatch.setattr(rf, "get_secret_any", lambda _candidates: "sk-x")
+ import jarvis.core.config_writer as cw
+
+ monkeypatch.setattr(cw, "set_voice_mode", lambda _mode, **_kw: None)
+
+ applied: list[str] = []
+
+ class LivePipeline:
+ def apply_voice_mode(self, mode: str) -> bool:
+ applied.append(mode)
+ return True
+
+ app = _app(mode="pipeline")
+ app.state.speech_pipeline = LivePipeline()
+ client = TestClient(app)
+
+ response = client.put(
+ "/api/settings/voice-mode",
+ json={"mode": "realtime", "persist": True},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["session_restarted"] is True
+ assert applied == ["realtime"]
+
+
+def test_get_voice_mode_reports_effective_active_engine(monkeypatch):
+ import jarvis.realtime.factory as rf
+
+ monkeypatch.setattr(rf, "get_secret_any", lambda _candidates: "sk-x")
+ app = _app(mode="realtime")
+ app.state.speech_pipeline = SimpleNamespace(
+ voice_engine_status=lambda: {
+ "session_active": True,
+ "active_session_mode": "realtime",
+ "active_session_provider": "openai-realtime",
+ "active_session_model": "gpt-realtime-2.1",
+ "transitioning": False,
+ }
+ )
+ client = TestClient(app)
+
+ body = client.get("/api/settings/voice-mode").json()
+
+ assert body["mode"] == "realtime"
+ assert body["session_active"] is True
+ assert body["active_session_mode"] == "realtime"
+ assert body["active_session_provider"] == "openai-realtime"
+ assert body["active_session_model"] == "gpt-realtime-2.1"
+ assert body["transitioning"] is False