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(voice): stabilize subscription speech pipeline
rubenluetke10-beep23bd0872103d
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 4d115061c5..e2e9d46d5b 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -156,6 +156,18 @@ Mac as "you cannot pick all the keys"; it is cross-platform by design, not aparity defect. Changing it means choosing position- over label-fidelity forall three OSes at once.+**Fix pass 2026-08-09 (stable subscription voice).** P-30 is resolved and+removed. The ChatGPT-subscription card is now a compatibility alias for one+OS-neutral composition: Jarvis microphone/VAD/STT, streamed Codex App Server+text, then Jarvis sentence TTS and receipt-backed playback. The selected+profile therefore no longer depends on WebRTC, `aiortc`, PyAV, ChatGPT-Live+audio boundaries, or provider-side VAD. Windows, macOS, and graphical Linux+run the same pipeline; headless hosts report `headless_audio_unavailable`+instead of advertising a call they cannot play. The capability response also+reports subscription login, STT, TTS, desktop runtime, and platform readiness+separately. The old provider id migrates at read time, so existing selections+enter the stable pipeline without a destructive config rewrite.+## Audit verdict summary**No hard breakers found.** No feature crashes on macOS or headless Linux;@@ -181,7 +193,6 @@ experiences today.| # | Impact | Area | Gap | Evidence | Behavior off-Windows ||---|---|---|---|---|---|-| P-30 | Medium | Subscription voice | ChatGPT-Live carries its audio ONLY on a WebRTC media track, so the transport needs `aiortc` + PyAV in-process. Upstream publishes no compiler-free Windows ARM64 dependency chain, so base excludes `aiortc` on that one cell — and the same absence occurs anywhere the wheel chain cannot install. `webrtc_available()` exists but is called ONLY inside the endpoint constructor, so no surface asks it before advertising the provider | `pyproject.toml` (the `aiortc` marker), `jarvis/realtime/webrtc_transport.py::webrtc_available`, `jarvis/plugins/realtime/codex_subscription.py::external_login_ready`, `can_open_duplex_session`, `jarvis/ui/web/provider_routes.py::_codex_subscription_status_payload` | **Today, dishonest:** with a valid Codex login the card reports `ready`, `PUT /voice-mode` accepts `realtime`, and the call then fails at connect time with "needs the 'aiortc' package. Install Jarvis's requirements" — advice a Windows ARM64 user can never act on. Every other realtime provider and all standard voice stay available. **Wanted:** the media-stack probe joins the login probe, the card reports `lifecycle_unavailable` with a per-platform reason before the click, and the message stops prescribing an install that cannot work || P-29 | Low | Subscription voice | The dedicated ChatGPT-subscription voice login is an interactive browser flow, so a headless Linux host — and a graphical Linux desktop that ships no terminal emulator able to host the login for its full lifetime — can never CONNECT the profile there (an existing login still reports ready and calls work through the browser voice bridge) | `jarvis/codex_app_server.py::_login_required_state`, `_linux_login_terminal_missing`, `start_codex_subscription_login`, `jarvis/codex_auth.py::_LINUX_LOGIN_TERMINALS` | Both cases report the same `lifecycle_unavailable` truth on every surface (card, activation, voice-mode, Test), each with its own actionable reason — "run Jarvis on a desktop" or "install one of these terminals" — and never an enabled Connect button that can only produce an error toast || P-24 | Medium | Dictation shortcut | The global dictation/call shortcut needs `pynput` on Linux/X11, and `pynput` hard-requires `evdev` — which is published **source-only** (verified on PyPI 2026-07-28: evdev 1.9.3 ships an sdist and no wheels) and compiles against the kernel headers. Putting it in `[full]` would break the one advertised install path on a stock `python:3.11-slim`, so it is the opt-in `[desktop-linux]` extra instead. Wayland is a separate, unfixable-by-install case: the compositor owns global shortcuts by design (the XDG `GlobalShortcuts` portal lets the *compositor* assign the keys, and no wlroots compositor implements it at all) | `pyproject.toml` (`desktop-linux`), `jarvis/platform/probes.py::has_hotkey`, `jarvis/trigger/backends/noop.py::explain_unavailable` | X11 without the extra: no global shortcut, and the log/UI now names the actual cause and the exact `pip install` that fixes it (it used to blame Wayland unconditionally). Wayland: no global shortcut at all — bind a compositor shortcut to `jarvis api dictation start`. On both, dictation still works from the Jarvis Bar, the Dictation view and the CLI, and voice still works via the wake word || P-25 | Medium | Dictation insertion | Pasting the transcript into another application is blocked, silently, in three OS-specific situations: Windows UIPI when the foreground window is elevated and Jarvis is not (`SendInput` reports success and the input is discarded), macOS Secure Input while a password field is focused, and Wayland outright (no synthetic input). Detection exists for the first two; Wayland is refused up front | `jarvis/dictation/insert.py::describe_target`, `jarvis/platform/input_isolation.py::windows_foreground_window_is_elevated`, `macos_secure_input_enabled` | All three degrade to the SAME honest outcome instead of silence: the transcript is left on the clipboard, the result is reported as `clipboard_only`, and the bar plus the Dictation view say why and that Ctrl+V will paste it. macOS Secure Input detection is implemented but has not been verified on real hardware from this machine |diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex ba9b16ecc9..701d266665 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2464,6 +2464,13 @@ class VoiceConfig(BaseModel):# reserved for an EXPLICIT user pick (mode present in the TOML), so a# fresh keyless install degrades silently instead of nagging every call.mode: str = "realtime"+ # Session-scoped voice composition. Empty keeps the selected engine's+ # normal brain. ``codex-subscription-voice`` keeps the proven local+ # microphone/STT/TTS/playback pipeline and replaces only conversational+ # text generation with the stable Codex App Server subscription transport.+ # The legacy realtime provider id is migrated at read time by+ # ``jarvis.voice.subscription_profile``.+ profile: str = ""# Realtime tool exposure. "delegate" (default) gives the live model one# compact jarvis_action function and hands action turns to the key-aware# router Brain. This keeps the persistent realtime prompt small; declaringdiff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex c8a7fcb8b9..bcd6601e75 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -1227,6 +1227,27 @@ def set_voice_mode(mode: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:_patch_table(path, "voice", "mode", mode)+def set_voice_profile(+ profile: str,+ *,+ mode: str = "pipeline",+ path: Path = DEFAULT_CONFIG_FILE,+) -> None:+ """Persist one session-scoped voice profile and its compatible engine.++ Both keys land in the same atomic TOML rewrite. This prevents an upgrade+ or interrupted settings write from leaving the subscription profile paired+ with the experimental realtime engine.+ """+ _patch_table(+ path,+ "voice",+ "profile",+ str(profile or "").strip(),+ extra={"mode": str(mode or "pipeline").strip().lower()},+ )++def set_realtime_provider(provider: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist the active realtime-voice provider to ``[brain.realtime] provider``.diff --git a/jarvis/plugins/tts/piper_local.py b/jarvis/plugins/tts/piper_local.pyindex 096cb8b5d4..15373f0e29 100644--- a/jarvis/plugins/tts/piper_local.py+++ b/jarvis/plugins/tts/piper_local.py@@ -24,7 +24,10 @@ from __future__ import annotationsimport asyncioimport logging+import queue+import threadingfrom collections.abc import AsyncIterator+from contextlib import suppressfrom pathlib import Pathfrom typing import Any@@ -45,7 +48,7 @@ class PiperLocalTTS:"""Local neural text-to-speech (keyless, on-device, multilingual by voice)."""name = "piper-local"- supports_streaming = False+ supports_streaming = True#: Which voice actually spoke last — read by the per-turn transcript label,#: so a new provider that leaves these unset makes the label lie.last_voice: str | None = None@@ -218,23 +221,105 @@ class PiperLocalTTS:"voice output to a provider you have a key for.")engine = await self._engine_for(model_id)- audio = await asyncio.to_thread(engine.generate, spoken, 0, self._speed)-- samples = np.asarray(audio.samples, dtype=np.float32)- if samples.size == 0:- log.warning("Local voice %s produced no audio for the turn.", model_id)- return- # Clip before scaling: a value beyond [-1, 1] would wrap around into- # loud noise once cast to int16.- pcm = (np.clip(samples, -1.0, 1.0) * _INT16_FULL_SCALE).astype(np.int16)+ sample_rate = int(getattr(engine, "sample_rate", 0) or 0)+ chunks: queue.Queue[bytes | object] = queue.Queue(maxsize=8)+ end = object()+ stopped = threading.Event()+ failure: list[Exception] = []+ emitted = threading.Event()++ def _pcm(samples: Any) -> bytes:+ values = np.asarray(samples, dtype=np.float32)+ if values.size == 0:+ return b""+ return (+ np.clip(values, -1.0, 1.0) * _INT16_FULL_SCALE+ ).astype(np.int16).tobytes()++ def _put(value: bytes | object) -> bool:+ while not stopped.is_set():+ try:+ chunks.put(value, timeout=0.05)+ return True+ except queue.Full:+ continue+ return False++ def _callback(samples: Any, _progress: float) -> int:+ data = _pcm(samples)+ if data:+ emitted.set()+ if not _put(data):+ return 1+ return 1 if stopped.is_set() else 0++ nonlocal_rate = [sample_rate]++ def _generate() -> None:+ try:+ try:+ audio = engine.generate(+ spoken, 0, self._speed, callback=_callback+ )+ except TypeError as exc:+ # Older sherpa-onnx builds and lightweight test engines do+ # not expose the callback overload. Keep the compatible+ # whole-sentence path instead of failing silent.+ detail = str(exc).lower()+ if not any(+ marker in detail+ for marker in (+ "callback",+ "incompatible function arguments",+ "unexpected keyword",+ )+ ):+ raise+ audio = engine.generate(spoken, 0, self._speed)+ if not sample_rate:+ rate = int(getattr(audio, "sample_rate", 0) or 0)+ if rate:+ nonlocal_rate[0] = rate+ if not emitted.is_set():+ data = _pcm(getattr(audio, "samples", ()))+ if data:+ emitted.set()+ _put(data)+ except Exception as exc: # noqa: BLE001 - forwarded to async owner+ failure.append(exc)+ finally:+ _put(end)++ worker = asyncio.create_task(asyncio.to_thread(_generate), name="piper-tts")self.last_voice = model_idself.last_voice_provider = self.name- yield AudioChunk(- pcm=pcm.tobytes(),- sample_rate=int(audio.sample_rate),- timestamp_ns=0,- channels=1,- )+ try:+ while True:+ item = await asyncio.to_thread(chunks.get)+ if item is end:+ break+ assert isinstance(item, bytes)+ rate = nonlocal_rate[0] or int(+ getattr(engine, "sample_rate", 0) or 0+ )+ if rate <= 0:+ raise RuntimeError("The local voice returned no sample rate.")+ yield AudioChunk(+ pcm=item,+ sample_rate=rate,+ timestamp_ns=0,+ channels=1,+ )+ await worker+ if failure:+ raise failure[0]+ if not emitted.is_set() and chunks.empty():+ log.warning("Local voice %s produced no audio for the turn.", model_id)+ finally:+ stopped.set()+ if not worker.done():+ with suppress(TimeoutError):+ await asyncio.wait_for(asyncio.shield(worker), timeout=1.0)async def _ensure_client(self) -> None:"""Warm-up hook the speech pipeline calls; loads the default voice.diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 79a1bc1587..286e9da621 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -2142,7 +2142,19 @@ class SpeechPipeline:getattr(config.trigger, "require_hey_prefix", True))self._require_hey_prefix = bool(require_hey_prefix) and cfg_require- self._brain: BrainCallback = brain_callback or _echo_brain+ self._base_brain: BrainCallback = brain_callback or _echo_brain+ self._brain: BrainCallback = self._base_brain+ # This profile owns only conversational text generation. The mature+ # cross-platform STT, sentence-TTS, playback receipts, follow-up+ # listening and barge-in machinery below stays the single audio path.+ if config is not None:+ from jarvis.voice.subscription_profile import ( # noqa: PLC0415+ CodexSubscriptionVoiceBrain,+ subscription_voice_selected,+ )++ if subscription_voice_selected(config):+ self._brain = CodexSubscriptionVoiceBrain(self._brain, config)# Flash-Brain reference (None when feature disabled).self._ack_brain: Any = ack_brainself._turn_state = TurnTakingState.IDLE@@ -6015,6 +6027,14 @@ class SpeechPipeline:def _configured_voice_mode(self) -> str:"""Return the normalized configured engine for the next session."""+ config = getattr(self, "_config", None)+ if config is not None:+ from jarvis.voice.subscription_profile import ( # noqa: PLC0415+ subscription_voice_selected,+ )++ if subscription_voice_selected(config):+ return "pipeline"mode = str(getattr(getattr(getattr(self, "_config", None), "voice", None),@@ -6035,11 +6055,23 @@ class SpeechPipeline:"""active_mode = getattr(self, "_active_voice_mode", None)session_id = getattr(self, "_current_voice_session_id", None)+ config = getattr(self, "_config", None)+ configured_profile = ""+ if config is not None:+ from jarvis.voice.subscription_profile import ( # noqa: PLC0415+ configured_voice_profile,+ )++ configured_profile = configured_voice_profile(config)return {"configured_mode": self._configured_voice_mode(),+ "configured_profile": configured_profile,"session_active": bool(session_id),"session_id": str(session_id or ""),"active_session_mode": active_mode,+ "active_session_profile": (+ configured_profile if active_mode == "pipeline" and session_id else ""+ ),"active_session_provider": (getattr(self, "_active_realtime_provider", "")if active_mode == "realtime"@@ -6079,6 +6111,33 @@ class SpeechPipeline:return self._schedule_engine_reopen(f"mode:{normalized}")return False+ def apply_voice_profile(self, profile: str) -> bool:+ """Apply a session-scoped voice composition without restarting the app."""+ from jarvis.voice.subscription_profile import ( # noqa: PLC0415+ CODEX_SUBSCRIPTION_VOICE_PROFILE,+ CodexSubscriptionVoiceBrain,+ )++ normalized = str(profile or "").strip().lower()+ if normalized not in {"", CODEX_SUBSCRIPTION_VOICE_PROFILE}:+ raise ValueError(f"Unsupported voice profile: {profile!r}")+ voice = getattr(getattr(self, "_config", None), "voice", None)+ if voice is not None:+ voice.profile = normalized+ if normalized:+ voice.mode = "pipeline"+ if normalized:+ if not isinstance(self._brain, CodexSubscriptionVoiceBrain):+ self._brain = CodexSubscriptionVoiceBrain(+ getattr(self, "_base_brain", self._brain),+ self._config,+ )+ else:+ self._brain = getattr(self, "_base_brain", self._brain)+ if getattr(self, "_state", PipelineState.IDLE) != PipelineState.IDLE:+ return self._schedule_engine_reopen(f"profile:{normalized or 'default'}")+ 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":diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex d866ec9e36..619870c659 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -749,6 +749,13 @@ def _active_realtime(request: Request) -> str | None:"""try:cfg = _resolve_cfg(request)+ from jarvis.voice.subscription_profile import ( # noqa: PLC0415+ LEGACY_CODEX_REALTIME_PROVIDER,+ subscription_voice_selected,+ )++ if cfg is not None and subscription_voice_selected(cfg):+ return LEGACY_CODEX_REALTIME_PROVIDERrealtime_cfg = getattr(getattr(cfg, "brain", None), "realtime", None)provider = (getattr(realtime_cfg, "provider", None) or "").strip()if provider:@@ -3430,6 +3437,27 @@ async def get_realtime_options(provider_id: str, request: Request) -> RealtimeOpdicts directly rather than going through ``catalog_spec``."""_require_realtime_provider(provider_id)+ if provider_id == "codex-subscription-realtime":+ # The visible id is a compatibility alias. This profile no longer uses+ # ChatGPT-Live's server-selected model or voices: Codex streams text and+ # the configured Jarvis TTS owns synthesis. Keep the existing generic+ # control honest without coupling this backend fix to a frontend build.+ return RealtimeOptionsResponse(+ provider=provider_id,+ models=[+ RealtimeOptionInfo(+ id="auto", label="Codex App Server (subscription text)"+ )+ ],+ voices=[+ RealtimeOptionInfo(+ id="configured-tts", label="Configured Jarvis voice output"+ )+ ],+ current_model="auto",+ current_voice="configured-tts",+ preview_available=True,+ )from jarvis.brain.model_catalog import REALTIME_MODELS, REALTIME_VOICEScfg = _resolve_cfg(request)@@ -3688,39 +3716,57 @@ async def _openai_realtime_voice_sample(async def _codex_subscription_voice_sample(api_key: str, *, model: str, voice: str, text: str, language: str) -> tuple[bytes, int]:- """Sample the subscription voice through its own ChatGPT-Live transport."""- del api_key, model- from jarvis.plugins.realtime.codex_subscription import ( # noqa: PLC0415- CodexSubscriptionRealtimeProvider,+ """Exercise the stable subscription-text -> configured-TTS voice path."""+ del api_key, model, voice+ from jarvis.core.protocols import BrainMessage, BrainRequest # noqa: PLC0415+ from jarvis.plugins.brain.codex import CodexBrain # noqa: PLC0415+ from jarvis.plugins.tts import build_tts_from_config # noqa: PLC0415+ from jarvis.voice.subscription_profile import ( # noqa: PLC0415+ subscription_language_directive,)- from jarvis.realtime.protocol import RealtimeSessionConfig # noqa: PLC0415- provider = CodexSubscriptionRealtimeProvider(- binary_path=_codex_binary_path(),- # A preview sends no microphone audio and needs no input recognizer.- input_transcriber_factory=lambda: None,- )- session = await provider.open_session(- RealtimeSessionConfig(- instructions="Speak only the trusted sample text supplied by the client.",- language=language,- voice=voice,- )+ brain = CodexBrain(prefer_subscription=True)+ request = BrainRequest(+ messages=(+ BrainMessage(+ "user",+ "Reply with one short, natural spoken sentence matching this "+ f"message: {text}",+ ),+ ),+ system=subscription_language_directive(language),+ stream=True,)+ answer_parts: list[str] = []+ async for delta in brain.complete(request):+ if delta.content:+ answer_parts.append(delta.content)+ answer = "".join(answer_parts).strip()+ if not answer:+ raise RuntimeError("The subscription text transport returned no sample.")++ active_config = cfg_mod.load_config()+ tts = build_tts_from_config(active_config.tts)pcm = bytearray()- sample_rate = int(getattr(provider, "output_sample_rate", 24_000) or 24_000)+ sample_rate = 0+ language_code = {"de": "de-DE", "en": "en-US", "es": "es-ES"}.get(+ language, language+ )try:- await session.send_speech(text)- async for event in session.receive():- if event.type == "audio_delta" and event.audio is not None:- pcm += bytes(event.audio.pcm)- sample_rate = int(event.audio.sample_rate or sample_rate)- elif event.type == "error":- raise RuntimeError(str(event.error or "subscription preview failed"))- elif event.type == "turn_complete":- break+ async for chunk in tts.synthesize(answer, language_code=language_code):+ rate = int(chunk.sample_rate or 0)+ if sample_rate and rate != sample_rate:+ raise RuntimeError("The configured voice changed sample rate mid-sample.")+ sample_rate = rate+ pcm += bytes(chunk.pcm)finally:- await session.close()+ close = getattr(tts, "aclose", None)+ if callable(close):+ closed = close()+ if inspect.isawaitable(closed):+ await closed+ if not pcm or sample_rate <= 0:+ raise RuntimeError("The configured voice produced no audible sample.")return bytes(pcm), sample_rate@@ -3768,11 +3814,14 @@ async def realtime_voice_preview(voice = body.voice.strip()if not voice:raise HTTPException(status_code=400, detail="A voice id is required.")+ allowed_voices = {option.id for option in REALTIME_VOICES.get(provider_id, ())}+ if provider_id == "codex-subscription-realtime":+ allowed_voices.add("configured-tts")_validate_realtime_option(provider_id=provider_id,field="voice",value=voice,- allowed={option.id for option in REALTIME_VOICES.get(provider_id, ())},+ allowed=allowed_voices,)model = body.model.strip()_validate_realtime_option(@@ -4726,6 +4775,61 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:"Connect or configure this provider first."),)+ if spec.id == "codex-subscription-realtime":+ from jarvis.codex_app_server import (+ get_shared_codex_app_server,+ set_codex_subscription_activation_block,+ )+ from jarvis.voice.subscription_profile import (+ CODEX_SUBSCRIPTION_VOICE_PROFILE,+ )++ try:+ client = get_shared_codex_app_server(+ _codex_binary_path(request), purpose="text"+ )+ await asyncio.wait_for(client.require_chatgpt_login(), timeout=45.0)+ except TimeoutError as exc:+ raise HTTPException(+ status_code=409,+ detail="The ChatGPT subscription text check timed out. Try again.",+ ) from exc+ except Exception as exc: # noqa: BLE001 - safe activation refusal+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ await asyncio.to_thread(set_codex_subscription_activation_block, None)++ if body.persist:+ try:+ from jarvis.core.config_writer import set_voice_profile++ set_voice_profile(CODEX_SUBSCRIPTION_VOICE_PROFILE, mode="pipeline")+ except Exception as exc: # noqa: BLE001+ raise HTTPException(+ status_code=500, detail=f"TOML write failed: {exc}"+ ) from exc++ cfg = _resolve_cfg(request)+ voice_cfg = getattr(cfg, "voice", None) if cfg is not None else None+ if voice_cfg is not None:+ voice_cfg.profile = CODEX_SUBSCRIPTION_VOICE_PROFILE+ voice_cfg.mode = "pipeline"+ await _emit(request, SecretConfigured(key="voice.profile", action="set"))++ from jarvis.ui.web.voice_runtime import apply_voice_profile++ session_restarted = apply_voice_profile(+ request, CODEX_SUBSCRIPTION_VOICE_PROFILE+ )+ _invalidate_section_health_state(request)+ return {+ "ok": True,+ "active": body.provider,+ "profile": CODEX_SUBSCRIPTION_VOICE_PROFILE,+ "mode": "pipeline",+ "persisted": body.persist,+ "restart_required": False,+ "session_restarted": session_restarted,+ }try:from jarvis.core.registry import loadfrom jarvis.realtime.protocol import RealtimeProvider@@ -4765,9 +4869,23 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:if body.persist:try:- from jarvis.core.config_writer import set_realtime_provider+ from jarvis.core.config_writer import (+ set_realtime_provider,+ set_voice_profile,+ )set_realtime_provider(body.provider)+ cfg_now = _resolve_cfg(request)+ from jarvis.voice.subscription_profile import (+ subscription_voice_selected,+ )++ if cfg_now is not None and subscription_voice_selected(cfg_now):+ current_mode = str(+ getattr(getattr(cfg_now, "voice", None), "mode", "pipeline")+ or "pipeline"+ )+ set_voice_profile("", mode=current_mode)except FileNotFoundError as exc:raise HTTPException(status_code=500, detail=str(exc)) from excexcept Exception as exc: # noqa: BLE001@@ -4776,6 +4894,11 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:) from exccfg = _resolve_cfg(request)+ if cfg is not None and getattr(cfg, "voice", None) is not None:+ try:+ cfg.voice.profile = ""+ except Exception as exc: # noqa: BLE001 - detached config is harmless+ log.debug("In-memory voice.profile update skipped: %s", exc)if cfg is not None and getattr(cfg, "brain", None) is not None:try:realtime_cfg = getattr(cfg.brain, "realtime", None)@@ -4789,7 +4912,13 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:log.debug("In-memory realtime.provider update skipped: %s", exc)await _emit(request, SecretConfigured(key="brain.realtime.provider", action="set"))- from jarvis.ui.web.voice_runtime import reconnect_realtime, voice_engine_status+ from jarvis.ui.web.voice_runtime import (+ apply_voice_profile,+ reconnect_realtime,+ voice_engine_status,+ )++ profile_session_restarted = apply_voice_profile(request, "")# A switch REOPENS an open call immediately. A transport that needs a# browser WebRTC offer cannot start without one, and the client only learns@@ -4807,7 +4936,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:except Exception as exc: # noqa: BLE001 — never block a switch on thislog.debug("Realtime offer pre-wait skipped: %s", exc)- session_restarted = reconnect_realtime(+ session_restarted = profile_session_restarted or reconnect_realtime(request, reason=f"realtime_provider:{body.provider}")diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 923e30d4d0..f8a1e75e02 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -755,19 +755,15 @@ PROVIDERS: tuple[ProviderSpec, ...] = (install_hint="npm i -g @openai/[email protected]",signup_url="https://chatgpt.com",credential_help=(- "Beta — subscription voice through Codex is not finished yet and "- "can break without notice. "- "Uses the ChatGPT plan signed in through Codex. The voice itself "- "needs no API key, and the app never switches it silently to "- "metered API voice: if it cannot start, the call stops. Select an "- "API Realtime provider if you want usage billing. One caveat — "- "Jarvis transcribes your side of the call with the provider chosen "- "in Speech-to-Text, so a CLOUD recognizer is still billed per turn "- "to that key; choose an on-device one to keep the whole call off "- "metered billing. Brain and tool providers keep their separately "- "configured billing."- ),- experimental=True,+ "Uses the ChatGPT plan signed in through Codex for stable streamed "+ "text generation. Jarvis keeps ownership of microphone capture, "+ "speech recognition, sentence synthesis, playback, follow-ups, and "+ "interruption, so the same voice pipeline works on Windows, macOS, "+ "and Linux. No OpenAI API key is used. Cloud STT or TTS providers "+ "may still bill their own configured keys; choose on-device speech "+ "providers for a fully non-metered audio path."+ ),+ experimental=False,),ProviderSpec(id="openai-realtime",diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex e0b96b417a..c429737625 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -264,6 +264,14 @@ def _realtime_model_label(provider_id: str | None, model: str | None) -> str | Nasync def get_voice_mode(request: Request) -> dict[str, object]:cfg = getattr(request.app.state, "config", None) or getattr(request.app.state, "cfg", None)mode = getattr(getattr(cfg, "voice", None), "mode", "pipeline")+ from jarvis.voice.subscription_profile import (+ LEGACY_CODEX_REALTIME_PROVIDER,+ configured_voice_profile,+ )++ profile = configured_voice_profile(cfg) if cfg is not None else ""+ if profile:+ mode = "pipeline"# Cross-family (AP-22): resolved via the SAME ordering the realtime# session factory uses, so this never disagrees with what a realtime# session would actually build (Gemini-only users now get `true` too,@@ -271,9 +279,14 @@ async def get_voice_mode(request: Request) -> dict[str, object]:# External-login adapters may need a bounded CLI status probe. Keep that# subprocess off the event loop so a settings poll cannot punch a hole in# live Realtime audio playback.- prov = await asyncio.to_thread(_realtime_available_provider, cfg)+ prov = (+ LEGACY_CODEX_REALTIME_PROVIDER+ if profile+ else await asyncio.to_thread(_realtime_available_provider, cfg)+ )realtime_available = prov is not Nonerealtime_availability_pending = False+ codex_status: dict[str, object] | None = Noneif prov == "codex-subscription-realtime":# Runtime discovery deliberately fails open on ``busy`` because the# authoritative session opener can protect an in-flight/live call.@@ -290,11 +303,14 @@ async def get_voice_mode(request: Request) -> dict[str, object]:_codex_subscription_status_payload,_codex_binary_path(request),)- if codex_status.get("reason_code") in {"busy", "login_in_progress"}:+ reason_code = str(codex_status.get("reason_code") or "")+ if reason_code in {"busy", "login_in_progress"}:realtime_available = Falserealtime_availability_pending = True- requires_webrtc_offer = await asyncio.to_thread(- _realtime_requires_webrtc_offer, cfg+ requires_webrtc_offer = (+ False+ if profile+ else await asyncio.to_thread(_realtime_requires_webrtc_offer, cfg))# Capability, not a provider id (AP-21): the surface must not call a start# attempt dead while the backend is still inside a budget it declared.@@ -313,13 +329,34 @@ async def get_voice_mode(request: Request) -> dict[str, object]:))prov_label, prov_model, prov_model_label = _realtime_provider_display(cfg, prov)+ if profile:+ # The legacy provider id remains user-visible for migration only. Its+ # active generation path is stable subscription text, not ChatGPT-Live.+ prov_model = "subscription-text"+ prov_model_label = "Codex App Server (subscription text)"from jarvis.ui.web.voice_runtime import voice_engine_statusruntime = voice_engine_status(request)session_provider = str(runtime.get("active_session_provider", "") or "")session_model = str(runtime.get("active_session_model", "") or "")+ subscription_capability: dict[str, object] | None = None+ if profile:+ from jarvis.platform.capabilities import detect_capabilities+ from jarvis.voice.subscription_profile import subscription_voice_capability++ host = detect_capabilities()+ subscription_capability = subscription_voice_capability(+ cfg,+ account_ready=bool(codex_status and codex_status.get("connected")),+ runtime_attached=bool(+ getattr(request.app.state, "speech_pipeline", None)+ ),+ display_present=host.display_present,+ ).to_dict()return {"mode": mode,+ "profile": profile,+ "subscription_voice_capability": subscription_capability,"realtime_available": realtime_available,"realtime_availability_pending": realtime_availability_pending,"requires_webrtc_offer": requires_webrtc_offer,@@ -355,6 +392,16 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, objraise HTTPException(status_code=400, detail=f"mode must be one of {_VOICE_MODES}")cfg = getattr(request.app.state, "config", None) or getattr(request.app.state, "cfg", None)+ from jarvis.voice.subscription_profile import subscription_voice_selected++ if body.mode == "realtime" and cfg is not None and subscription_voice_selected(cfg):+ raise HTTPException(+ status_code=400,+ detail=(+ "ChatGPT subscription voice uses the stable Pipeline engine. "+ "Select a different Realtime provider before enabling Realtime mode."+ ),+ )# A3: never pin the boot default to an unreachable engine. A provider may# use an API key or an external subscription login, so readiness — not a@@ -403,6 +450,8 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, objif cfg is not None and getattr(cfg, "voice", None) is not None:try:cfg.voice.mode = body.mode # type: ignore[attr-defined]+ if body.mode == "realtime":+ cfg.voice.profile = "" # type: ignore[attr-defined]except Exception as exc: # noqa: BLE001 — frozen model is not an errorlog.debug("in-memory cfg.voice.mode update skipped: %s", exc)diff --git a/jarvis/ui/web/voice_runtime.py b/jarvis/ui/web/voice_runtime.pyindex 903de4e5c4..63df008293 100644--- a/jarvis/ui/web/voice_runtime.py+++ b/jarvis/ui/web/voice_runtime.py@@ -58,6 +58,18 @@ def apply_voice_mode(request: Any, mode: str) -> bool:return False+def apply_voice_profile(request: Any, profile: str) -> bool:+ pipeline = _pipeline(request)+ apply = getattr(pipeline, "apply_voice_profile", None)+ if not callable(apply):+ return False+ try:+ return bool(apply(profile))+ except Exception: # noqa: BLE001 -- config remains applied for next session+ log.warning("Live voice-profile 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)@@ -70,4 +82,9 @@ def reconnect_realtime(request: Any, *, reason: str) -> bool:return False-__all__ = ["apply_voice_mode", "reconnect_realtime", "voice_engine_status"]+__all__ = [+ "apply_voice_mode",+ "apply_voice_profile",+ "reconnect_realtime",+ "voice_engine_status",+]diff --git a/jarvis/voice/subscription_profile.py b/jarvis/voice/subscription_profile.pynew file mode 100644index 0000000000..5a72bfb64f--- /dev/null+++ b/jarvis/voice/subscription_profile.py@@ -0,0 +1,252 @@+"""Stable ChatGPT-subscription composition for classic voice sessions.++This module deliberately does not implement audio transport. It selects the+stable Codex App Server text protocol for conversational turns while the+existing SpeechPipeline continues to own capture, STT, TTS, playback receipts,+follow-up listening, and interruption on Windows, macOS, and Linux.+"""++from __future__ import annotations++import sys+from collections.abc import AsyncIterator+from dataclasses import asdict, dataclass+from typing import Any++from jarvis.brain.turn_planner import TurnReason, plan_turn+from jarvis.core.protocols import BrainMessage, BrainRequest+from jarvis.core.turn_language import is_substantive_turn, resolve_output_language+from jarvis.plugins.brain.codex import CodexBrain++CODEX_SUBSCRIPTION_VOICE_PROFILE = "codex-subscription-voice"+LEGACY_CODEX_REALTIME_PROVIDER = "codex-subscription-realtime"++_LANGUAGE_NAMES = {"de": "German", "en": "English", "es": "Spanish"}+_MAX_HISTORY_MESSAGES = 6+_SUPPORTED_DESKTOP_PLATFORMS = frozenset({"win32", "darwin", "linux"})+++@dataclass(frozen=True, slots=True)+class SubscriptionVoiceCapability:+ """One honest readiness snapshot for the composed subscription voice."""++ available: bool+ platform_supported: bool+ interactive_audio: bool+ account_ready: bool+ text_transport_ready: bool+ stt_configured: bool+ tts_configured: bool+ runtime_attached: bool+ reason: str++ def to_dict(self) -> dict[str, object]:+ return asdict(self)+++def subscription_voice_capability(+ config: object,+ *,+ account_ready: bool,+ runtime_attached: bool,+ display_present: bool,+ platform: str | None = None,+) -> SubscriptionVoiceCapability:+ """Compose account, text, speech, device, and OS readiness without IO."""+ platform_supported = str(platform or sys.platform) in _SUPPORTED_DESKTOP_PLATFORMS+ stt_configured = bool(str(getattr(getattr(config, "stt", None), "provider", "") or "").strip())+ tts_configured = bool(str(getattr(getattr(config, "tts", None), "provider", "") or "").strip())+ interactive_audio = bool(display_present)+ available = all(+ (+ platform_supported,+ interactive_audio,+ account_ready,+ stt_configured,+ tts_configured,+ runtime_attached,+ )+ )+ if not platform_supported:+ reason = "unsupported_platform"+ elif not interactive_audio:+ reason = "headless_audio_unavailable"+ elif not account_ready:+ reason = "subscription_login_required"+ elif not stt_configured:+ reason = "stt_not_configured"+ elif not tts_configured:+ reason = "tts_not_configured"+ elif not runtime_attached:+ reason = "desktop_runtime_not_attached"+ else:+ reason = "ready"+ return SubscriptionVoiceCapability(+ available=available,+ platform_supported=platform_supported,+ interactive_audio=interactive_audio,+ account_ready=bool(account_ready),+ text_transport_ready=bool(account_ready),+ stt_configured=stt_configured,+ tts_configured=tts_configured,+ runtime_attached=bool(runtime_attached),+ reason=reason,+ )+++def configured_voice_profile(config: object) -> str:+ """Return the canonical profile, including the legacy selection alias."""+ voice = getattr(config, "voice", None)+ profile = str(getattr(voice, "profile", "") or "").strip().lower()+ if profile == CODEX_SUBSCRIPTION_VOICE_PROFILE:+ return CODEX_SUBSCRIPTION_VOICE_PROFILE+ brain = getattr(config, "brain", None)+ realtime = getattr(brain, "realtime", None)+ provider = str(getattr(realtime, "provider", "") or "").strip().lower()+ if provider == LEGACY_CODEX_REALTIME_PROVIDER:+ return CODEX_SUBSCRIPTION_VOICE_PROFILE+ return ""+++def subscription_voice_selected(config: object) -> bool:+ """Whether the stable ChatGPT-subscription voice composition is selected."""+ return configured_voice_profile(config) == CODEX_SUBSCRIPTION_VOICE_PROFILE+++def subscription_language_directive(language: str) -> str:+ name = _LANGUAGE_NAMES.get(language, "English")+ return (+ f"REPLY LANGUAGE — MANDATORY: Always reply in {name}, no matter which "+ "language the user writes or speaks in. This overrides every other "+ f"language cue. Keep the reply natural and fluent in {name}."+ )+++class CodexSubscriptionVoiceBrain:+ """Route conversational voice turns to the subscription text transport.++ Tool, private-data, current-data, and local-state turns remain on the+ existing BrainManager. That preserves the complete Jarvis tool contract;+ the read-only subscription transport never guesses that an action happened.+ """++ def __init__(self, delegate: Any, config: object) -> None:+ self._delegate = delegate+ self._config = config+ self._subscription = CodexBrain(prefer_subscription=True)+ self._history: list[BrainMessage] = []+ self._conversation_language = ""+ self._last_turn_all_failed = False+ self._last_turn_suppressed = False+ self._last_turn_executed_action_tool = False++ def __getattr__(self, name: str) -> Any:+ # SpeechPipeline reads per-turn delivery flags and optional hooks from+ # BrainManager. Proxying keeps those contracts intact for delegated+ # action/evidence turns.+ return getattr(self._delegate, name)++ async def __call__(self, text: str) -> str:+ return "".join([chunk async for chunk in self.generate_stream(text)])++ async def generate(self, text: str, **kwargs: Any) -> str:+ return "".join([chunk async for chunk in self.generate_stream(text, **kwargs)])++ async def generate_stream(+ self,+ text: str,+ *,+ on_progress: Any | None = None,+ **kwargs: Any,+ ) -> AsyncIterator[str]:+ context = tuple(+ str(message.content)+ for message in self._history[-_MAX_HISTORY_MESSAGES:]+ if isinstance(message.content, str)+ )+ turn_plan = plan_turn(text, context=context)+ delegate_turn = turn_plan.requires_orchestrator+ if turn_plan.reasons == frozenset({TurnReason.ACTION}):+ action_detector = getattr(self._delegate, "_turn_has_action_intent", None)+ if callable(action_detector):+ delegate_turn = bool(action_detector(text))+ if delegate_turn:+ delegated_parts: list[str] = []+ try:+ async for chunk in self._delegate.generate_stream(+ text,+ on_progress=on_progress,+ **kwargs,+ ):+ delegated_parts.append(chunk)+ yield chunk+ finally:+ self._last_turn_all_failed = bool(+ getattr(self._delegate, "_last_turn_all_failed", False)+ )+ self._last_turn_suppressed = bool(+ getattr(self._delegate, "_last_turn_suppressed", False)+ )+ self._last_turn_executed_action_tool = bool(+ getattr(+ self._delegate,+ "_last_turn_executed_action_tool",+ False,+ )+ )+ delegated_answer = "".join(delegated_parts).strip()+ if delegated_answer:+ self._history.extend(+ [+ BrainMessage("user", text),+ BrainMessage("assistant", delegated_answer),+ ]+ )+ self._history = self._history[-_MAX_HISTORY_MESSAGES:]+ return++ self._last_turn_all_failed = False+ self._last_turn_suppressed = False+ self._last_turn_executed_action_tool = False++ reply_pin = getattr(getattr(self._config, "brain", None), "reply_language", "auto")+ language = resolve_output_language(+ reply_pin,+ "",+ text,+ conversation_language=self._conversation_language,+ )+ if is_substantive_turn(text):+ self._conversation_language = language++ messages = tuple([*self._history[-_MAX_HISTORY_MESSAGES:], BrainMessage("user", text)])+ request = BrainRequest(+ messages=messages,+ system=subscription_language_directive(language),+ stream=True,+ )+ answer_parts: list[str] = []+ async for delta in self._subscription.complete(request):+ if on_progress is not None:+ on_progress()+ if delta.content:+ answer_parts.append(delta.content)+ yield delta.content++ answer = "".join(answer_parts).strip()+ if answer:+ self._history.extend([BrainMessage("user", text), BrainMessage("assistant", answer)])+ if len(self._history) > _MAX_HISTORY_MESSAGES:+ self._history = self._history[-_MAX_HISTORY_MESSAGES:]+++__all__ = [+ "CODEX_SUBSCRIPTION_VOICE_PROFILE",+ "LEGACY_CODEX_REALTIME_PROVIDER",+ "CodexSubscriptionVoiceBrain",+ "SubscriptionVoiceCapability",+ "configured_voice_profile",+ "subscription_language_directive",+ "subscription_voice_capability",+ "subscription_voice_selected",+]diff --git a/tests/unit/core/test_voice_mode_config.py b/tests/unit/core/test_voice_mode_config.pyindex eec998d65f..621bde06e8 100644--- a/tests/unit/core/test_voice_mode_config.py+++ b/tests/unit/core/test_voice_mode_config.py@@ -33,6 +33,25 @@ def test_set_voice_mode_persists_toml_only(tmp_path: Path):assert 'mode = "realtime"' in toml.read_text(encoding="utf-8")+def test_set_subscription_voice_profile_persists_compatible_mode_atomically(+ tmp_path: Path,+):+ toml = tmp_path / "jarvis.toml"+ toml.write_text('[voice]\nmode = "realtime"\n', encoding="utf-8")++ config_writer.set_voice_profile(+ "codex-subscription-voice", mode="pipeline", path=toml+ )++ loaded = cfg_mod.JarvisConfig.model_validate(+ {"voice": {"mode": "pipeline", "profile": "codex-subscription-voice"}}+ )+ content = toml.read_text(encoding="utf-8")+ assert loaded.voice.profile == "codex-subscription-voice"+ assert 'mode = "pipeline"' in content+ assert 'profile = "codex-subscription-voice"' in content++def test_realtime_tier_field_accepts_brain_tier_config():cfg = cfg_mod.JarvisConfig.model_validate({"brain": {"realtime": {"provider": "openai"}}}diff --git a/tests/unit/plugins/tts/test_piper_local.py b/tests/unit/plugins/tts/test_piper_local.pyindex eda83b2354..bcc00171b5 100644--- a/tests/unit/plugins/tts/test_piper_local.py+++ b/tests/unit/plugins/tts/test_piper_local.py@@ -171,6 +171,41 @@ def test_declares_that_it_runs_on_device() -> None:assert PiperLocalTTS.runs_on_device is True+def test_callback_capable_engine_yields_incremental_audio(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class StreamingEngine:+ sample_rate = 22_050++ def generate(self, _text, _speaker, _speed, *, callback):+ callback(np.full(100, 0.1, dtype=np.float32), 0.5)+ callback(np.full(100, 0.2, dtype=np.float32), 1.0)+ return _FakeAudio(seconds=0.0)++ monkeypatch.setattr(+ "jarvis.speech.local_models.bundle_present",+ lambda _model_id, **_kwargs: True,+ )+ monkeypatch.setattr(+ PiperLocalTTS,+ "_build_engine",+ lambda _self, _model_id: StreamingEngine(),+ )+ tts = PiperLocalTTS()++ async def collect() -> list[bytes]:+ return [+ chunk.pcm+ async for chunk in tts.synthesize("Hello", language_code="en-US")+ ]++ chunks = asyncio.run(collect())++ assert PiperLocalTTS.supports_streaming is True+ assert len(chunks) == 2+ assert all(chunks)++def test_voices_cover_every_supported_reply_language() -> None:"""The catalog must not leave a supported language mute.diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.pyindex 9e8246e680..42deb25471 100644--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -32,7 +32,7 @@ def test_codex_subscription_realtime_spec_has_no_api_key_path() -> None:assert spec.auth_mode == "codex"assert spec.secret_keys == ()assert provider_billing(spec) == "subscription"- assert spec.experimental is True+ assert spec.experimental is False@pytest.mark.parametrize(@@ -214,7 +214,7 @@ async def test_plan_unsupported_activation_retries_the_live_gate() -> None:"""plan_unsupported must reach verify_activation (the only path that canCLEAR the sticky block) and answer with the plan diagnosis on re-refusal."""- import jarvis.core.registry as registry+ from jarvis import codex_app_serverfrom jarvis.codex_app_server import CodexSubscriptionPlanUnsupportedmonkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")@@ -232,15 +232,18 @@ async def test_plan_unsupported_activation_retries_the_live_gate(gate_calls: list[object] = []- class _Provider:- @classmethod- async def verify_activation(cls, cfg: object) -> None:- gate_calls.append(cfg)+ class _Client:+ async def require_chatgpt_login(self) -> None:+ gate_calls.append(self)raise CodexSubscriptionPlanUnsupported("Subscription voice permits only personal ChatGPT accounts.")- monkeypatch.setattr(registry, "load", lambda *_args, **_kwargs: _Provider)+ monkeypatch.setattr(+ codex_app_server,+ "get_shared_codex_app_server",+ lambda *_args, **_kwargs: _Client(),+ )request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=None, cfg=None))@@ -255,7 +258,7 @@ async def test_plan_unsupported_activation_retries_the_live_gate(request,)- assert gate_calls, "the live gate must re-judge a plan-blocked account"+ assert gate_calls, "the stable text gate must re-judge a plan-blocked account"assert caught.value.status_code == 409detail = str(caught.value.detail)assert "personal ChatGPT accounts" in detail@@ -801,29 +804,52 @@ def test_reason_code_vocabulary_is_pinned() -> None:@pytest.mark.asyncio-async def test_realtime_activation_requires_experimental_acknowledgement(+async def test_subscription_profile_no_longer_requires_experimental_acknowledgement(monkeypatch: pytest.MonkeyPatch,) -> None:- async def unexpected_probe(*_args, **_kwargs) -> bool:- pytest.fail("the experimental acknowledgement must be checked first")+ from jarvis import codex_app_servermonkeypatch.setattr(routes,- "_provider_credential_present_async",- unexpected_probe,+ "_codex_subscription_status_payload",+ lambda _binary_path: {+ "installed": True,+ "connected": True,+ "mode": "chatgpt",+ "message": "ready",+ "reason_code": "ready",+ },)- with pytest.raises(HTTPException) as caught:- await routes.realtime_switch(- routes.SwitchBody(- provider="codex-subscription-realtime",- persist=False,- ),- object(),- )+ class _Client:+ async def require_chatgpt_login(self) -> None:+ return None- assert caught.value.status_code == 409- assert "Explicitly acknowledge" in str(caught.value.detail)+ monkeypatch.setattr(+ codex_app_server,+ "get_shared_codex_app_server",+ lambda *_args, **_kwargs: _Client(),+ )+ monkeypatch.setattr(+ codex_app_server,+ "set_codex_subscription_activation_block",+ lambda _value: None,+ )+ config = SimpleNamespace(+ codex=SimpleNamespace(binary_path="codex"),+ voice=SimpleNamespace(profile="", mode="realtime"),+ brain=SimpleNamespace(realtime=None),+ )+ response = await routes.realtime_switch(+ routes.SwitchBody(+ provider="codex-subscription-realtime",+ persist=False,+ ),+ SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config))),+ )++ assert response["profile"] == "codex-subscription-voice"+ assert response["mode"] == "pipeline"@pytest.mark.asynciodiff --git a/tests/unit/voice/test_subscription_profile.py b/tests/unit/voice/test_subscription_profile.pynew file mode 100644index 0000000000..0409fed6d9--- /dev/null+++ b/tests/unit/voice/test_subscription_profile.py@@ -0,0 +1,156 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.core.protocols import BrainDelta+from jarvis.speech.pipeline import PipelineState, SpeechPipeline+from jarvis.voice.subscription_profile import (+ CODEX_SUBSCRIPTION_VOICE_PROFILE,+ CodexSubscriptionVoiceBrain,+ configured_voice_profile,+ subscription_voice_capability,+)+++def _config(*, profile: str = "", realtime_provider: str = "") -> SimpleNamespace:+ realtime = SimpleNamespace(provider=realtime_provider) if realtime_provider else None+ return SimpleNamespace(+ voice=SimpleNamespace(profile=profile, mode="realtime"),+ brain=SimpleNamespace(reply_language="auto", realtime=realtime),+ )+++def test_canonical_and_legacy_selections_resolve_to_stable_profile() -> None:+ assert (+ configured_voice_profile(profile := _config(profile=CODEX_SUBSCRIPTION_VOICE_PROFILE))+ == CODEX_SUBSCRIPTION_VOICE_PROFILE+ )+ assert profile.voice.mode == "realtime"+ assert (+ configured_voice_profile(_config(realtime_provider="codex-subscription-realtime"))+ == CODEX_SUBSCRIPTION_VOICE_PROFILE+ )+ assert configured_voice_profile(_config()) == ""+++def test_legacy_selection_forces_classic_pipeline_engine() -> None:+ pipeline = SpeechPipeline.__new__(SpeechPipeline)+ pipeline._config = _config(realtime_provider="codex-subscription-realtime")++ assert pipeline._configured_voice_mode() == "pipeline"+++def test_profile_can_be_applied_and_removed_without_process_restart() -> None:+ delegate = object()+ config = _config()+ pipeline = SpeechPipeline.__new__(SpeechPipeline)+ pipeline._config = config+ pipeline._base_brain = delegate+ pipeline._brain = delegate+ pipeline._state = PipelineState.IDLE++ assert pipeline.apply_voice_profile(CODEX_SUBSCRIPTION_VOICE_PROFILE) is False+ assert isinstance(pipeline._brain, CodexSubscriptionVoiceBrain)+ assert config.voice.mode == "pipeline"++ assert pipeline.apply_voice_profile("") is False+ assert pipeline._brain is delegate++[email protected]("platform", ["win32", "darwin", "linux"])+def test_capability_uses_the_same_composed_path_on_every_desktop_os(+ platform: str,+) -> None:+ config = _config(profile=CODEX_SUBSCRIPTION_VOICE_PROFILE)+ config.stt = SimpleNamespace(provider="nemotron-local")+ config.tts = SimpleNamespace(provider="piper-local")++ capability = subscription_voice_capability(+ config,+ account_ready=True,+ runtime_attached=True,+ display_present=True,+ platform=platform,+ )++ assert capability.available is True+ assert capability.reason == "ready"+++def test_capability_reports_headless_audio_as_unavailable() -> None:+ config = _config(profile=CODEX_SUBSCRIPTION_VOICE_PROFILE)+ config.stt = SimpleNamespace(provider="nemotron-local")+ config.tts = SimpleNamespace(provider="piper-local")++ capability = subscription_voice_capability(+ config,+ account_ready=True,+ runtime_attached=True,+ display_present=False,+ platform="linux",+ )++ assert capability.available is False+ assert capability.reason == "headless_audio_unavailable"+++async def test_conversation_turns_stream_through_subscription_with_history() -> None:+ requests = []++ class Subscription:+ async def complete(self, request):+ requests.append(request)+ yield BrainDelta(content="Hello.")+ yield BrainDelta(finish_reason="stop")++ class Delegate:+ @staticmethod+ def _turn_has_action_intent(_text: str) -> bool:+ return False++ async def generate_stream(self, *_args, **_kwargs):+ pytest.fail("conversational turns must not use the router brain")+ yield ""++ brain = CodexSubscriptionVoiceBrain(Delegate(), _config())+ brain._subscription = Subscription()++ first = [chunk async for chunk in brain.generate_stream("Share a short joke.")]+ second = [chunk async for chunk in brain.generate_stream("Tell me something amusing.")]++ assert first == ["Hello."]+ assert second == ["Hello."]+ assert [message.role for message in requests[1].messages] == [+ "user",+ "assistant",+ "user",+ ]+ assert "REPLY LANGUAGE" in str(requests[0].system)+++async def test_action_turns_keep_the_existing_orchestrator() -> None:+ delegated = []++ class Delegate:+ _last_turn_all_failed = False+ _last_turn_suppressed = False+ _last_turn_executed_action_tool = True++ @staticmethod+ def _turn_has_action_intent(_text: str) -> bool:+ return True++ async def generate_stream(self, text, **_kwargs):+ delegated.append(text)+ yield "Done."++ brain = CodexSubscriptionVoiceBrain(Delegate(), _config())+ result = [chunk async for chunk in brain.generate_stream("Open Chrome now.")]++ assert result == ["Done."]+ assert delegated == ["Open Chrome now."]+ assert brain._last_turn_executed_action_tool is Truediff --git a/tests/unit/web/test_realtime_option_validation.py b/tests/unit/web/test_realtime_option_validation.pyindex 689754eefa..5612628472 100644--- a/tests/unit/web/test_realtime_option_validation.py+++ b/tests/unit/web/test_realtime_option_validation.py@@ -119,4 +119,11 @@ def test_get_realtime_options_reports_preview_capability(assert subscription_response.status_code == 200body = subscription_response.json()assert body["preview_available"] is True- assert [voice["id"] for voice in body["voices"]][0] == "cove"+ assert body["models"] == [+ {"id": "auto", "label": "Codex App Server (subscription text)"}+ ]+ assert body["voices"] == [+ {"id": "configured-tts", "label": "Configured Jarvis voice output"}+ ]+ assert body["current_model"] == "auto"+ assert body["current_voice"] == "configured-tts"diff --git a/tests/unit/web/test_realtime_voice_preview.py b/tests/unit/web/test_realtime_voice_preview.pyindex ccbe2a7110..00fb98cae5 100644--- a/tests/unit/web/test_realtime_voice_preview.py+++ b/tests/unit/web/test_realtime_voice_preview.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport ioimport wave+from types import SimpleNamespaceimport pytestfrom fastapi import FastAPI@@ -17,6 +18,7 @@ from fastapi.testclient import TestClientfrom jarvis.core import config as cfg_modfrom jarvis.core.config import JarvisConfig+from jarvis.core.protocols import AudioChunk, BrainDeltafrom jarvis.ui.web import provider_routesfrom jarvis.ui.web.provider_routes import router@@ -111,6 +113,42 @@ def test_subscription_preview_does_not_require_an_api_key(assert response.status_code == 200+async def test_subscription_sampler_uses_text_brain_and_configured_tts(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.plugins import tts as tts_module+ from jarvis.plugins.brain import codex++ requests = []++ async def complete(_self, request):+ requests.append(request)+ yield BrainDelta(content="Ready.")+ yield BrainDelta(finish_reason="stop")++ class TTS:+ async def synthesize(self, text, *, language_code=None):+ assert text == "Ready."+ assert language_code == "de-DE"+ yield AudioChunk(b"\x01\x02" * 10, 22_050, 0, 1)++ async def aclose(self) -> None:+ return None++ monkeypatch.setattr(codex.CodexBrain, "complete", complete)+ monkeypatch.setattr(cfg_mod, "load_config", lambda: SimpleNamespace(tts=object()))+ monkeypatch.setattr(tts_module, "build_tts_from_config", lambda _cfg: TTS())++ pcm, rate = await provider_routes._codex_subscription_voice_sample(+ "", model="", voice="cove", text="Ready.", language="de"+ )++ assert pcm == b"\x01\x02" * 10+ assert rate == 22_050+ assert requests and requests[0].tools == ()++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]] = []diff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.pyindex 1a399572e3..a830eb1ff1 100644--- a/tests/unit/web/test_voice_mode_route.py+++ b/tests/unit/web/test_voice_mode_route.py@@ -124,6 +124,41 @@ def test_get_voice_mode_reports_browser_offer_capability(monkeypatch):assert body["transport_offer_detail"] == "Embedded desktop WebRTC offer is ready."+def test_get_voice_mode_reports_stable_subscription_profile(monkeypatch):+ from jarvis.platform import capabilities+ from jarvis.ui.web import provider_routes++ monkeypatch.setattr(+ provider_routes,+ "_codex_subscription_status_payload",+ lambda _binary: {+ "connected": True,+ "reason_code": "ready",+ },+ )+ monkeypatch.setattr(+ capabilities,+ "detect_capabilities",+ lambda: SimpleNamespace(display_present=True),+ )+ app = _app(mode="realtime")+ app.state.config.voice.profile = "codex-subscription-voice"+ app.state.config.brain = SimpleNamespace(realtime=None, providers={})+ app.state.config.stt = SimpleNamespace(provider="nemotron-local")+ app.state.config.tts = SimpleNamespace(provider="piper-local")+ app.state.speech_pipeline = object()++ body = TestClient(app).get("/api/settings/voice-mode").json()++ assert body["mode"] == "pipeline"+ assert body["profile"] == "codex-subscription-voice"+ assert body["active_provider"] == "codex-subscription-realtime"+ assert body["active_model"] == "subscription-text"+ assert body["active_model_label"] == "Codex App Server (subscription text)"+ assert body["requires_webrtc_offer"] is False+ assert body["subscription_voice_capability"]["available"] is True++def test_get_voice_mode_cross_family_gemini_only(monkeypatch):"""Feature A2: realtime_available must NOT be OpenAI-only — a user withonly a Gemini key gets realtime_available=true, active_provider=gemini-live."""