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
fix(realtime): make the subscription voice surface tell the truth while a call starts
rubenluetke10-beepb66284ae8ed3
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex c8c434cfba..dcbe069b22 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -8182,6 +8182,27 @@ class SpeechPipeline:await self._set_turn_state(TurnTakingState.LISTENING)elif kind == "provider_error":log.warning("Realtime desktop status: %s", message)+ elif kind == "provider_fallback":+ # The call is crossing to a DIFFERENT provider family, which can+ # mean a different billing path (AP-22). The user-facing notice+ # rides the bus (``ErrorOccurred`` on the ``realtime.*`` layer,+ # published alongside this frame) so it reaches every surface in+ # the UI language; this branch exists so the desktop dispatch+ # never drops the frame in silence (AP-30). The rebuilt session+ # announces itself with a fresh ``audio_ready``, whose own+ # branch above returns the turn state to LISTENING.+ log.warning(+ "Realtime desktop provider fallback: from=%s status=%s error=%s",+ message.get("provider", "unknown"),+ message.get("status", "unknown"),+ message.get("error", ""),+ )+ elif kind == "provider_warning":+ # Recoverable: the session continues on the same provider.+ log.warning(+ "Realtime desktop provider warning: %s",+ message.get("error", ""),+ )# Open the microphone BEFORE building the realtime session AND before# the provider handshake, buffering locally until the session acceptsdiff --git a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsxindex ac2a738e1e..8662e3e01d 100644--- a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx+++ b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx@@ -81,6 +81,33 @@ export function RealtimeOptionsControl({};}, [providerId, reloadNonce]);+ // The pin can move without this card: a voice command, the control CLI, or a+ // second window all write `[brain.providers.<id>].model/voice` and announce+ // it. Without this the card kept showing the previous voice — a picker that+ // quietly disagrees with what the next call will actually use.+ useEffect(() => {+ const modelKey = `brain.providers.${providerId}.model`;+ const voiceKey = `brain.providers.${providerId}.voice`;+ function onConfigReloaded(event: Event) {+ const detail = (event as CustomEvent<{ changed_keys?: unknown }>).detail;+ const keys = Array.isArray(detail?.changed_keys)+ ? (detail.changed_keys as string[])+ : [];+ if (keys.includes(modelKey) || keys.includes(voiceKey)) {+ setReloadNonce((value) => value + 1);+ }+ }+ function onRealtimeSwitched() {+ setReloadNonce((value) => value + 1);+ }+ window.addEventListener("jarvis:config-reloaded", onConfigReloaded);+ window.addEventListener("jarvis:realtime-switched", onRealtimeSwitched);+ return () => {+ window.removeEventListener("jarvis:config-reloaded", onConfigReloaded);+ window.removeEventListener("jarvis:realtime-switched", onRealtimeSwitched);+ };+ }, [providerId]);+async function handleChange(field: "model" | "voice", next: string) {const prev = field === "model" ? model : voice;if (field === "model") setModel(next);diff --git a/jarvis/ui/web/frontend/src/components/VoiceIndicator.tsx b/jarvis/ui/web/frontend/src/components/VoiceIndicator.tsxindex ae27b1c06e..7abb867141 100644--- a/jarvis/ui/web/frontend/src/components/VoiceIndicator.tsx+++ b/jarvis/ui/web/frontend/src/components/VoiceIndicator.tsx@@ -1,27 +1,33 @@import { useEventStore, type VoiceState } from "@/store/events";+import { useT } from "@/i18n";import { cn } from "@/lib/utils";-const STATE_STYLE: Record<VoiceState, { color: string; label: string; ring: string }> = {- idle: { color: "bg-blue-500", label: "Idle", ring: "ring-blue-500/40" },- listening: { color: "bg-emerald-500", label: "Listening", ring: "ring-emerald-500/50 animate-pulse" },- thinking: { color: "bg-yellow-500", label: "Thinking", ring: "ring-yellow-500/50 animate-pulse" },- speaking: { color: "bg-pink-500", label: "Speaking", ring: "ring-pink-500/50 animate-pulse" },- error: { color: "bg-red-500", label: "Error", ring: "ring-red-500/50" },+// Exhaustive by construction: adding a member to VoiceState without a style+// here fails the TypeScript build instead of rendering an undefined swatch.+const STATE_STYLE: Record<VoiceState, { color: string; ring: string }> = {+ idle: { color: "bg-blue-500", ring: "ring-blue-500/40" },+ listening: { color: "bg-emerald-500", ring: "ring-emerald-500/50 animate-pulse" },+ thinking: { color: "bg-yellow-500", ring: "ring-yellow-500/50 animate-pulse" },+ speaking: { color: "bg-pink-500", ring: "ring-pink-500/50 animate-pulse" },+ paused: { color: "bg-amber-500", ring: "ring-amber-500/40" },+ error: { color: "bg-red-500", ring: "ring-red-500/50" },};export function VoiceIndicator() {+ const t = useT();const state = useEventStore((s) => s.voiceState);- const style = STATE_STYLE[state];+ const style = STATE_STYLE[state] ?? STATE_STYLE.idle;+ const label = t(`voice_state.${state}`);return (<divrole="status"- aria-label={`Voice state: ${style.label}`}+ aria-label={`${t("voice_state.indicator_label")}: ${label}`}className={cn("h-8 w-8 rounded-full ring-4 transition-colors",style.color,style.ring,)}- title={style.label}+ title={label}/>);}diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 762de757ad..5b1d820336 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -164,7 +164,12 @@ const VOICE_STATE_STYLE: Record<string, { dot: string; pulse: boolean }> = {listening: { dot: "bg-emerald-400", pulse: true },thinking: { dot: "bg-primary", pulse: true },speaking: { dot: "bg-primary", pulse: true },+ // The user muted or suspended the pipeline: neither working nor broken.+ paused: { dot: "bg-amber-400", pulse: false },error: { dot: "bg-destructive", pulse: false },+ // Not a supervisor state — the surface's own "a realtime transport is+ // negotiating" phase, which no backend state covers.+ connecting: { dot: "bg-amber-400", pulse: true },};export interface SidebarProps {@@ -237,31 +242,41 @@ export function Sidebar({ width = SIDEBAR_DEFAULT_WIDTH }: SidebarProps = {}) {s.events.filter((e) => e.name === "AgentStateChange").length > 0 ? undefined : 0,);+ // Read before the status line because BOTH depend on it now: the footer card+ // follows the VOICE MODE rather than the pipeline brain (in realtime mode the+ // pipeline brain is dormant, and showing it there misled the user —+ // "OpenRouter" while Gemini Live was doing all the talking), and the status+ // line needs its connecting phase. A RUNNING realtime session's live+ // provider/model outrank the configured pick (a mid-call cross-family+ // fallback must be visible, AP-22); when idle the resolved provider + its+ // pinned/default model are shown.+ const voiceMode = useVoiceMode();+// The window connects in ~1s but the voice feature warms up ~20s in the// background. During that gap show a "Voice starting…" spinner instead of the// normal idle "Ready" dot (which would falsely imply the mic already works).// Disconnected outranks warmup — "Offline" is the honest state with no socket.// voiceWarming / bootWarming / warming come from the shared useVoiceReadiness// hook so the sidebar dot, the banner and the chat empty-state never disagree.- const showSpinner = warming;- const vs = VOICE_STATE_STYLE[voiceState] ?? VOICE_STATE_STYLE.idle;+ const showSpinner = warming || voiceMode.connecting;+ const vs = voiceMode.connecting+ ? VOICE_STATE_STYLE.connecting+ : VOICE_STATE_STYLE[voiceState] ?? VOICE_STATE_STYLE.idle;+ // A negotiating realtime transport outranks the pipeline's own state: the+ // subscription route needs 15-45 s before it can hear anything, and showing+ // the stale pre-call state there is what made a live handshake look frozen.const voiceLabel = !connected? bootWarming? t("voice_state.booting"): t("voice_state.offline"): voiceWarming? t("voice_state.starting")- : t(`voice_state.${voiceState}`);+ : voiceMode.connecting+ ? t("voice_state.connecting")+ : t(`voice_state.${voiceState}`);const providerLabel = useMemo(() => prettyProviderName(brainProvider), [brainProvider]);- // The footer card follows the VOICE MODE, not always the pipeline brain:- // in realtime mode the pipeline brain is dormant, so showing it there- // misled the user ("OpenRouter" while Gemini Live was doing all the talking).- // A RUNNING realtime session's live provider/model outrank the configured- // pick (a mid-call cross-family fallback must be visible, AP-22); when idle- // the resolved provider + its pinned/default model are shown.- const voiceMode = useVoiceMode();const realtimeFooter = voiceMode.mode === "realtime";const liveRealtimeSession =realtimeFooter &&diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex fc013d082b..32ca02128e 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx@@ -17,9 +17,28 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-import { ProviderCard } from "@/components/providers/ProviderTierSection";+import {+ PROVIDER_STATE_CHIPS,+ ProviderCard,+ type ProviderStateChip,+} from "@/components/providers/ProviderTierSection";import type { ProviderDescriptor, ProviderTestResult } from "@/hooks/useProviders";import { useI18nStore, type UiLanguage } from "@/i18n";+import enLocale from "@/i18n/locales/en.json";++/** The rendered label of one state chip, resolved through its i18n key.+ *+ * These chips used to be bare English literals in the component, so a test+ * asserting the literal could not tell a translated chip from an untranslated+ * one. Going through the key keeps the assertion about the STATE, not about+ * one locale's wording. */+function chipLabel(chip: ProviderStateChip): string {+ const [namespace, key] = PROVIDER_STATE_CHIPS[chip].key.split(".");+ const bucket = (enLocale as unknown as Record<string, Record<string, string>>)[+ namespace+ ];+ return bucket[key];+}const EXPERIMENTAL_CONSENT_KEY ="jarvis.experimentalConsent.codex-subscription-realtime";@@ -481,8 +500,8 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {).toBeNull();// The state chip next to the provider name must not shout "missing" (red)// about an install the probe has not judged yet.- expect(screen.queryByText("missing")).toBeNull();- expect(screen.getByText("checking")).toBeTruthy();+ expect(screen.queryByText(chipLabel("missing"))).toBeNull();+ expect(screen.getByText(chipLabel("checking"))).toBeTruthy();// The connect action stays available: login validates itself and a busy// flicker must not lock the user out of it.const connect = screen.getByRole("button", {@@ -603,8 +622,8 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {expect(connect.disabled).toBe(true);// The state chip stays neutral — nothing is "missing" on an OS the// feature does not support.- expect(screen.queryByText("missing")).toBeNull();- expect(screen.getByText("unavailable")).toBeTruthy();+ expect(screen.queryByText(chipLabel("missing"))).toBeNull();+ expect(screen.getByText(chipLabel("unavailable"))).toBeTruthy();});it("shows the sticky plan diagnosis after a refused activation", () => {diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex c0f59d6ac6..fe1016a80d 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -36,6 +36,11 @@ import {import { useEventStore } from "@/store/events";import { agentBrand, agentsBrand } from "@/lib/agentBrand";import { robustCopy } from "@/lib/clipboard";+import {+ realtimeTransportIssueKey,+ requestRealtimeTransportOffer,+ type RealtimeTransportIssue,+} from "@/lib/realtimeTransportIssue";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -338,6 +343,11 @@ export function VoiceEngineContext({mode,realtimeAvailable,statusKnown,+ connecting = false,+ requiresWebRtcOffer = false,+ transportOfferReady = null,+ transportOfferDetail = "",+ transportIssue = null,sessionActive,activeSessionMode,activeSessionProvider,@@ -349,6 +359,16 @@ export function VoiceEngineContext({mode: VoiceEngineMode;realtimeAvailable: boolean;statusKnown: boolean;+ /** A realtime call is negotiating right now — neither idle nor running. */+ connecting?: boolean;+ /** The resolved realtime transport needs a browser WebRTC offer. */+ requiresWebRtcOffer?: boolean;+ /** Whether an offer is registered; null on a backend that does not report it. */+ transportOfferReady?: boolean | null;+ /** Backend one-liner naming WHY no offer is available. Rendered verbatim. */+ transportOfferDetail?: string;+ /** Client-side broker blocker; outranks the backend line when set. */+ transportIssue?: RealtimeTransportIssue | null;sessionActive: boolean;activeSessionMode: "pipeline" | "realtime" | null;activeSessionProvider: string;@@ -361,17 +381,35 @@ export function VoiceEngineContext({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");+ // "Connecting" comes FIRST. A subscription transport spends 15-45 s spawning+ // its app-server, verifying the account and negotiating WebRTC; reporting+ // that window as "no voice session is active" is what made a working call+ // look frozen.+ const runtimeText = connecting+ ? t("apikeys_view.runtime_connecting")+ : 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;+ // The one honest explanation for a call that never starts on an+ // offer-requiring transport (only the subscription route requires one).+ // Rendered verbatim: the backend one-liner names the actual blocker.+ const offerBlocked =+ liveMode === "realtime" &&+ requiresWebRtcOffer &&+ transportOfferReady === false;+ const offerDetail = !offerBlocked+ ? ""+ : transportIssue+ ? t(realtimeTransportIssueKey(transportIssue))+ : transportOfferDetail;const modeDescription =mode === "realtime" && !realtimeAvailable? t(@@ -417,7 +455,7 @@ export function VoiceEngineContext({aria-hidden="true"className={cn("h-1.5 w-1.5 shrink-0 rounded-full",- transitioning+ transitioning || connecting? "animate-pulse bg-amber-400 motion-reduce:animate-none": runtimeMatchesSelection? "bg-emerald-400"@@ -426,7 +464,7 @@ export function VoiceEngineContext({/><spanclassName={cn(- runtimeMatchesSelection && !transitioning+ runtimeMatchesSelection && !transitioning && !connecting? "text-muted-foreground": "text-amber-300",)}@@ -436,6 +474,16 @@ export function VoiceEngineContext({</div></div>+ {offerDetail && (+ <p+ data-testid="voice-engine-transport-offer-detail"+ className="mt-1 text-[11px] leading-snug text-amber-600 dark:text-amber-400"+ aria-live="polite"+ >+ {offerDetail}+ </p>+ )}+<pdata-testid="voice-engine-keys-hint"className="mt-1 text-[11px] leading-snug text-muted-foreground/80"@@ -778,20 +826,30 @@ export function ProviderCard({// into a generic "does not work".pushToast("warning",- `${descriptor.label} is selected, but it did not answer: ${- result.detail || result.status- }`,+ t("apikeys_view.polish_verify_failed")+ .replace("{0}", descriptor.label)+ .replace("{1}", result.detail || result.status),);// Let the card repaint with the health this test just produced.onChanged();}+ /** "<tier> → <provider>", plus the "from the next voice start" note. */+ function switchToast(key: string, restartRequired = false): string {+ const line = t(key).replace("{0}", descriptor.label);+ return restartRequired+ ? `${line}${t("apikeys_view.switch_note_next_start")}`+ : line;+ }+async function activate(assumeConfigured = false) {if (descriptor.active) return;if (!isBrainSwitchable) {pushToast("warning",- `${descriptor.label} is only available for ${agentsBrand(assistantName)}.`,+ t("apikeys_view.agents_only_toast")+ .replace("{0}", descriptor.label)+ .replace("{1}", agentsBrand(assistantName)),);return;}@@ -862,25 +920,25 @@ export function ProviderCard({try {if (descriptor.tier === "brain") {await switchBrainProvider(descriptor.id);- pushToast("success", `Brain → ${descriptor.label}`);+ pushToast("success", switchToast("apikeys_view.switch_done_brain"));window.dispatchEvent(new CustomEvent("jarvis:brain-switched"));} else if (descriptor.tier === "tts") {const result = await switchTtsProvider(descriptor.id);- const note = result.restart_required- ? " (active from next voice start)"- : "";- pushToast("success", `Voice output → ${descriptor.label}${note}`);+ pushToast(+ "success",+ switchToast("apikeys_view.switch_done_tts", result.restart_required),+ );window.dispatchEvent(new CustomEvent("jarvis:tts-switched"));} else if (descriptor.tier === "stt") {const result = await switchSttProvider(descriptor.id);- const note = result.restart_required- ? " (active from next voice start)"- : "";- pushToast("success", `Voice input → ${descriptor.label}${note}`);+ pushToast(+ "success",+ switchToast("apikeys_view.switch_done_stt", result.restart_required),+ );window.dispatchEvent(new CustomEvent("jarvis:stt-switched"));} else if (descriptor.tier === "computer-use") {await switchComputerUseProvider(descriptor.id);- pushToast("success", `Computer-Use → ${descriptor.label}`);+ pushToast("success", switchToast("apikeys_view.switch_done_computer_use"));window.dispatchEvent(new CustomEvent("jarvis:computer-use-switched"));} else if (descriptor.tier === "dictation") {// Its own branch on purpose: this tier has no `/switch` route (the pin@@ -896,7 +954,7 @@ export function ProviderCard({// exact "it says it did it but nothing changed" failure. Falling back to// `id` keeps an older payload without the field working.await switchDictationPolishProvider(descriptor.polish_family || descriptor.id);- pushToast("success", `Dictation wording → ${descriptor.label}`);+ pushToast("success", switchToast("apikeys_view.switch_done_dictation"));window.dispatchEvent(new CustomEvent("jarvis:dictation-polish-switched"));// A stored key is not a working provider, and this tier is where the// gap bites hardest: the pass is INVISIBLE when it fails (it delivers@@ -908,14 +966,20 @@ export function ProviderCard({// cheap here (a handful of tokens) and the only honest signal.void verifyPolishProvider();} else {+ // The switch reconnects an OPEN call synchronously, and an+ // offer-requiring transport cannot start without a registered browser+ // offer. Ask for one before the POST rather than after the reconnect+ // already failed. Dispatched for every realtime switch, never keyed on+ // a provider name (AP-21) — a transport that needs none ignores it.+ requestRealtimeTransportOffer();const result = await switchRealtimeProvider(descriptor.id,descriptor.experimental === true,);- const note = result.restart_required- ? " (active from next voice start)"- : "";- pushToast("success", `Realtime → ${descriptor.label}${note}`);+ pushToast(+ "success",+ switchToast("apikeys_view.switch_done_realtime", result.restart_required),+ );window.dispatchEvent(new CustomEvent("jarvis:realtime-switched"));}onChanged();@@ -968,7 +1032,7 @@ export function ProviderCard({const consentDialog = consentPending ? (<div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"+ className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/60 p-4"onClick={(event) => {event.stopPropagation();setConsentPending(false);@@ -980,7 +1044,11 @@ export function ProviderCard({><div className="text-sm font-semibold">{descriptor.label}</div><p className="text-sm leading-relaxed text-muted-foreground">- {t("apikeys_view.experimental_subscription_consent")}+ {t(+ isSubscriptionLoginOnly+ ? "apikeys_view.experimental_subscription_consent"+ : "apikeys_view.experimental_consent",+ )}</p><div className="flex justify-end gap-2"><button@@ -1020,7 +1088,10 @@ export function ProviderCard({descriptor.active? t("apikeys_view.active_tooltip"): !isBrainSwitchable- ? `Available for ${agentsBrand(assistantName)} only`+ ? t("apikeys_view.agents_only_short").replace(+ "{0}",+ agentsBrand(assistantName),+ ): descriptor.configured? t("apikeys_view.click_to_activate"): descriptor.auth_mode === "codex"@@ -1100,10 +1171,7 @@ export function ProviderCard({<code className="font-mono">{descriptor.id}</code>{" · "}<span>- {descriptor.auth_mode === "api_key" && "API key auth"}- {descriptor.auth_mode === "codex" && "ChatGPT / Codex login"}- {descriptor.auth_mode === "antigravity" && "Google subscription login"}- {descriptor.auth_mode === "none" && "Local — no auth"}+ {t(`apikeys_view.auth_mode_${descriptor.auth_mode}`)}</span></p></div>@@ -1121,7 +1189,10 @@ export function ProviderCard({}disabledReason={!isBrainSwitchable- ? `Available for ${agentsBrand(assistantName)} only`+ ? t("apikeys_view.agents_only_short").replace(+ "{0}",+ agentsBrand(assistantName),+ ): isCodexBrain && !descriptor.codex_brain_ready? t("apikeys_codex.brain_needs_openai_key"): undefined@@ -1154,8 +1225,10 @@ export function ProviderCard({{!isBrainSwitchable && (<p className="rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[11px] leading-relaxed text-amber-700">- {agentBrand(assistantName)} only. This provider cannot be used as the main Brain or- Computer-Use planner because it does not receive screenshots.+ {t("apikeys_view.agents_only_note").replace(+ "{0}",+ agentBrand(assistantName),+ )}</p>)}@@ -1412,11 +1485,11 @@ export function ActiveControl({}) {const t = useT();const labelTitle = descriptor.active- ? "This provider is active"+ ? t("apikeys_view.activate_tooltip_active"): disabled- ? disabledReason ?? "Provider cannot be activated"+ ? disabledReason ?? t("apikeys_view.activate_tooltip_blocked"): descriptor.configured- ? "Activate this provider"+ ? t("apikeys_view.activate_tooltip_activate"): descriptor.codex_status?.reason_code? // The reason-specific line names the actual remedy; a generic// "connect first" is wrong for most non-ready codex states.@@ -1653,6 +1726,10 @@ export function AuthWidget({onSavedActivate?: () => void;}) {const t = useT();+ // "Billed through a login, not a key" — the SHAPE that makes the+ // subscription wording true, never a provider id (AP-21).+ const isSubscriptionBilled =+ descriptor.billing === "subscription" && descriptor.secret_keys.length === 0;return (<div className="space-y-2"><ProviderBillingBadge billing={descriptor.billing} />@@ -1662,8 +1739,19 @@ export function AuthWidget({className="rounded-md border border-violet-500/30 bg-violet-500/[0.06] px-2.5 py-1.5 text-[11px] leading-snug text-muted-foreground"><p>- <span>{t("apikeys_view.subscription_realtime_description")}</span>{" "}- <span>{t("apikeys_view.experimental_subscription_fallback")}</span>+ {/* The subscription wording ("uses the ChatGPT plan…") belongs to+ a card that IS billed through a subscription login — the shape,+ never a provider name (AP-21). Bound to `experimental` alone it+ would tell the next experimental provider's users that their+ ChatGPT plan pays for it. */}+ {isSubscriptionBilled ? (+ <>+ <span>{t("apikeys_view.subscription_realtime_description")}</span>{" "}+ <span>{t("apikeys_view.experimental_subscription_fallback")}</span>+ </>+ ) : (+ <span>{t("apikeys_view.experimental_note")}</span>+ )}</p></div>)}@@ -1675,8 +1763,8 @@ export function AuthWidget({<><p className="text-xs text-muted-foreground">{descriptor.secret_keys.length > 0- ? "Local provider — runs without credentials. The key below is optional, only for servers that enforce one (e.g. vLLM --api-key)."- : "Local provider — no credentials needed."}+ ? t("apikeys_view.local_optional_key_hint")+ : t("apikeys_view.local_no_credentials_hint")}</p>{descriptor.secret_keys.map((k) => (<ApiKeyForm@@ -1780,7 +1868,16 @@ function CodexAuthWidget({: "apikeys_codex.status_login_required";useEffect(() => {- if (!loginPolling || loginReady) return;+ if (!loginPolling) return;+ if (loginReady) {+ // The login just landed. `/api/providers` alone does not unlock the+ // engine switch: realtime AVAILABILITY lives on the voice-mode snapshot,+ // which listens for this event. Without it the card went green while the+ // Pipeline|Realtime segment stayed disabled — for up to five minutes, and+ // on a long-open window indefinitely.+ window.dispatchEvent(new CustomEvent("jarvis:realtime-switched"));+ return;+ }let stopped = false;const deadline = Date.now() + 5 * 60_000;let timer: number | null = null;@@ -1837,6 +1934,9 @@ function CodexAuthWidget({await codexLogout(subscriptionOnly);pushToast("info", t("apikeys_codex.disconnected"));onChanged();+ // Losing the login removes a realtime provider: the engine switch has to+ // re-read availability, or it keeps offering a mode that cannot start.+ window.dispatchEvent(new CustomEvent("jarvis:realtime-switched"));} catch (e) {pushToast("error", (e as Error).message);} finally {@@ -1915,6 +2015,12 @@ function CodexAuthWidget({)}</div>+ {/* Deliberately `codex_status.installed`, NOT the payload's+ `cli_installed`. The backend's carve-out for an ownership window+ (answer "is it installed" from PATH instead of the owned profile)+ protects exactly the states this row already suppresses below, so+ reading both would add a second source of truth that can disagree —+ and the two DO disagree in practice. See useProviders.ts. */}{!status?.installed &&!CODEX_NO_INSTALL_PROMPT_REASONS.has(status?.reason_code ?? "") && (<div className="flex flex-wrap items-center gap-2">@@ -2138,31 +2244,57 @@ export function StateChip({);}-export function StatusBadge({ descriptor }: { descriptor: ProviderDescriptor }) {- if (descriptor.active) return <StateChip tone="active">active</StateChip>;+/**+ * The card's state chip vocabulary — the summary a user actually scans.+ *+ * Every member maps to one `apikeys_view.state_*` key present in en/de/es+ * (pinned by `provider-state-chip-parity.test.ts`). These used to be bare+ * English literals, so a translated card carried an untranslated chip.+ */+export const PROVIDER_STATE_CHIPS = {+ active: { tone: "active", key: "apikeys_view.state_active" },+ ready: { tone: "ready", key: "apikeys_view.state_ready" },+ checking: { tone: "neutral", key: "apikeys_view.state_checking" },+ unavailable: { tone: "neutral", key: "apikeys_view.state_unavailable" },+ blocked: { tone: "missing", key: "apikeys_view.state_blocked" },+ missing: { tone: "missing", key: "apikeys_view.state_missing" },+ not_connected: { tone: "neutral", key: "apikeys_view.state_not_connected" },+ open: { tone: "neutral", key: "apikeys_view.state_open" },+} as const satisfies Record<+ string,+ { tone: keyof typeof STATE_CHIP_TONE; key: string }+>;++export type ProviderStateChip = keyof typeof PROVIDER_STATE_CHIPS;++/** Which chip a descriptor deserves. Pure, so the mapping stays testable. */+export function providerStateChip(+ descriptor: ProviderDescriptor,+): ProviderStateChip {+ if (descriptor.active) return "active";if (descriptor.auth_mode === "codex") {const status = descriptor.codex_status;// Transient: the status is being probed right now. Neither "missing" nor// "not connected" is known yet, and the red chip on a healthy install was// exactly the bug this state exists to prevent.- if (status?.reason_code === "busy")- return <StateChip tone="neutral">checking</StateChip>;+ if (status?.reason_code === "busy") return "checking";// Nothing is "missing" on an OS the feature does not support at all.- if (status?.reason_code === "lifecycle_unavailable")- return <StateChip tone="neutral">unavailable</StateChip>;+ if (status?.reason_code === "lifecycle_unavailable") return "unavailable";// Terminal until the account changes — "not connected" would undersell it.- if (status?.reason_code === "plan_unsupported")- return <StateChip tone="missing">blocked</StateChip>;- if (!status?.installed) return <StateChip tone="missing">missing</StateChip>;- if (descriptor.configured) return <StateChip tone="ready">ready</StateChip>;- return <StateChip tone="neutral">not connected</StateChip>;+ if (status?.reason_code === "plan_unsupported") return "blocked";+ if (!status?.installed) return "missing";+ return descriptor.configured ? "ready" : "not_connected";}if (descriptor.auth_mode === "antigravity") {const status = descriptor.antigravity_status;- if (!status?.installed) return <StateChip tone="missing">missing</StateChip>;- if (status.connected) return <StateChip tone="ready">ready</StateChip>;- return <StateChip tone="neutral">not connected</StateChip>;+ if (!status?.installed) return "missing";+ return status.connected ? "ready" : "not_connected";}- if (descriptor.configured) return <StateChip tone="ready">ready</StateChip>;- return <StateChip tone="neutral">open</StateChip>;+ return descriptor.configured ? "ready" : "open";+}++export function StatusBadge({ descriptor }: { descriptor: ProviderDescriptor }) {+ const t = useT();+ const chip = PROVIDER_STATE_CHIPS[providerStateChip(descriptor)];+ return <StateChip tone={chip.tone}>{t(chip.key)}</StateChip>;}diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsxindex 23242af7b0..fff4f7433d 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx@@ -82,9 +82,16 @@ export function BrowserRealtimeControl() {const voiceState = useEventStore((store) => store.voiceState);const transcriptionFinal = useEventStore((store) => store.transcriptionFinal);const transcription = useEventStore((store) => store.transcription);+ const pushToast = useEventStore((store) => store.pushToast);const [state, setState] = useState<ConnectionState>("idle");const [effectiveProvider, setEffectiveProvider] = useState("");const [error, setError] = useState("");+ // A non-fatal note from the provider (a recoverable warning, an unusable+ // WebRTC answer). Distinct from `error`, which means the call is over.+ const [notice, setNotice] = useState("");+ // The last surface-spoken reply, kept so a browser that cannot synthesise+ // speech still SHOWS the answer instead of swallowing the whole turn.+ const [spokenText, setSpokenText] = useState("");// The microphone level lands in a ref, not in state: it arrives ~30 times a// second and only the animation loop consumes it. Routing it through// setState re-rendered this control (and everything it renders) at 30 Hz to@@ -118,6 +125,8 @@ export function BrowserRealtimeControl() {setState("idle");setEffectiveProvider("");setError("");+ setNotice("");+ setSpokenText("");levelRef.current = 0;clearVoiceInputLevel("browser");setBrowserVoiceInputOwnership(false);@@ -161,14 +170,53 @@ export function BrowserRealtimeControl() {},onStatus: (status, payload) => {if (!isCurrent()) return;+ // The backend authors one precise English sentence per failure —+ // "automatic usage-billed fallback is disabled for this provider",+ // the exact transport error, the socket close reason. Replacing all+ // of them with one generic line sent users to test a credential+ // that was never the problem.+ const backendDetail =+ (typeof payload.error === "string" ? payload.error.trim() : "") ||+ (typeof payload.reason === "string" ? payload.reason.trim() : "");if (status === "audio_ready") {const provider =typeof payload.provider === "string" ? payload.provider : "";if (provider) setEffectiveProvider(provider);setState("connected");+ setNotice("");setVoice("listening");} else if (status === "mode_fallback") {setEffectiveProvider(t("sidebar.realtime_pipeline_fallback"));+ } else if (status === "provider_fallback") {+ // The call just moved to a DIFFERENT provider family — which can+ // mean different billing. Saying nothing here is an AP-22+ // violation: the card would still name the provider that died.+ const from =+ typeof payload.provider === "string" ? payload.provider : "";+ pushToast(+ "warning",+ t("sidebar.realtime_provider_fallback")+ .replace("{0}", from || t("sidebar.realtime_provider_unknown"))+ .replace("{1}", backendDetail),+ );+ setNotice(+ t("sidebar.realtime_provider_fallback_short").replace(+ "{0}",+ from || t("sidebar.realtime_provider_unknown"),+ ),+ );+ } else if (status === "provider_warning") {+ // Recoverable: the session continues. A note, never an error.+ setNotice(backendDetail || t("sidebar.realtime_provider_warning"));+ } else if (status === "webrtc_transport_unavailable") {+ setNotice(t("sidebar.realtime_webrtc_degraded"));+ } else if (status === "error_spoken") {+ // The trusted reply the provider did not speak. Audio starts via+ // onAudio; keep the text so an engine without speech synthesis+ // still shows the answer rather than losing the turn.+ const text = typeof payload.text === "string" ? payload.text : "";+ if (text.trim()) setSpokenText(text.trim());+ setError("");} else if (status === "hangup") {// The session ended through a voice hang-up command or end_call.// Release the microphone and return to idle.@@ -189,7 +237,7 @@ export function BrowserRealtimeControl() {clientRef.current = null;void client.disconnect();setState("error");- setError(t("sidebar.realtime_error"));+ setError(backendDetail || t("sidebar.realtime_error"));levelRef.current = 0;clearVoiceInputLevel("browser");setVoice("error");@@ -219,6 +267,7 @@ export function BrowserRealtimeControl() {setVoice("error");}}, [+ pushToast,realtimeAvailable,requiresWebRtcOffer,setTranscription,@@ -316,6 +365,25 @@ export function BrowserRealtimeControl() {? [t(progressKey), effectiveProvider].filter(Boolean).join(" · "): t("sidebar.realtime_browser_hint"))}</div>+ {notice && !error && (+ <div+ data-testid="realtime-provider-notice"+ className="mt-1 text-[10px] leading-snug text-amber-600 dark:text-amber-400"+ aria-live="polite"+ >+ {notice}+ </div>+ )}+ {/* The surface-spoken reply, shown only when speech synthesis could not+ deliver it — otherwise the whole turn is silent AND invisible. */}+ {spokenText && error && (+ <div+ data-testid="realtime-spoken-text"+ className="mt-1 text-[10px] leading-snug text-foreground"+ >+ {spokenText}+ </div>+ )}</div>);}diff --git a/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.tsx b/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.tsxindex 0a2ad6b25d..26831f0400 100644--- a/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.tsx@@ -2,6 +2,10 @@ import { useEffect, useState } from "react";import { useVoiceMode } from "@/hooks/useVoiceMode";import { RealtimeTransportBroker } from "@/lib/realtimeTransportBroker";+import {+ REALTIME_TRANSPORT_PREPARE_EVENT,+ REALTIME_TRANSPORT_PREPARE_TTL_MS,+} from "@/lib/realtimeTransportIssue";import { hasEmbeddedDesktopBridge } from "./BrowserRealtimeControl";/** Authenticated, invisible WebRTC offer broker for native voice sessions. */@@ -10,6 +14,13 @@ export function SubscriptionRealtimeTransportBroker() {const [desktopCapabilityReady, setDesktopCapabilityReady] = useState(() => Boolean(window.__JARVIS_REALTIME_BROKER_TOKEN?.trim()),);+ // A pending "publish an offer now" request, plus the nonce that revives a+ // broker which already gave up. Both exist for the switch race: a provider+ // switch reconnects the LIVE call synchronously, while this client only+ // learns that the new transport needs an offer after a status round trip —+ // so the reopened session used to start with nothing registered.+ const [prepareUntil, setPrepareUntil] = useState(0);+ const [restartNonce, setRestartNonce] = useState(0);useEffect(() => {const refreshCapability = () => {@@ -22,11 +33,27 @@ export function SubscriptionRealtimeTransportBroker() {return () => window.removeEventListener("jarvis-token-ready", refreshCapability);}, []);+ useEffect(() => {+ const onPrepare = () => {+ setPrepareUntil(Date.now() + REALTIME_TRANSPORT_PREPARE_TTL_MS);+ setRestartNonce((value) => value + 1);+ };+ window.addEventListener(REALTIME_TRANSPORT_PREPARE_EVENT, onPrepare);+ return () =>+ window.removeEventListener(REALTIME_TRANSPORT_PREPARE_EVENT, onPrepare);+ }, []);++ const preparing = prepareUntil > Date.now();+useEffect(() => {if (mode !== "realtime" ||!realtimeAvailable ||- !requiresWebRtcOffer ||+ // `preparing` covers the window in which this client cannot yet know+ // whether the transport it is switching TO needs an offer. One that does+ // not simply lets the registration expire — this never branches on a+ // provider name (AP-21).+ !(requiresWebRtcOffer || preparing) ||!hasEmbeddedDesktopBridge() ||!desktopCapabilityReady) {@@ -35,6 +62,27 @@ export function SubscriptionRealtimeTransportBroker() {const broker = new RealtimeTransportBroker();broker.start();return () => broker.stop();- }, [desktopCapabilityReady, mode, realtimeAvailable, requiresWebRtcOffer]);+ }, [+ desktopCapabilityReady,+ mode,+ preparing,+ realtimeAvailable,+ requiresWebRtcOffer,+ restartNonce,+ ]);++ // Drop the prepare window once it elapses, so a broker kept alive only by it+ // is torn down instead of holding a peer connection open indefinitely.+ useEffect(() => {+ if (prepareUntil === 0) return;+ const remaining = prepareUntil - Date.now();+ if (remaining <= 0) {+ setPrepareUntil(0);+ return;+ }+ const timer = window.setTimeout(() => setPrepareUntil(0), remaining);+ return () => window.clearTimeout(timer);+ }, [prepareUntil]);+return null;}diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 930f5a19dc..2a76f0347c 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -72,6 +72,18 @@ export interface ProviderDescriptor {*/computer_use_active?: boolean;brain_switchable?: boolean;+ /**+ * Whether the provider's CLI is on this machine, as the BACKEND judges it.+ *+ * Deliberately not rendered by any card, and that is the decision rather+ * than an oversight: for a Codex-auth card the backend already answers this+ * inside `codex_status.installed`, and its one carve-out (during an+ * ownership window, answer from PATH instead of the owned profile) protects+ * exactly the states the card's install row suppresses anyway. Reading both+ * would give the same question two answers that can disagree. Kept in the+ * payload for `/api/providers` consumers outside this UI (the control CLI,+ * the setup report).+ */cli_installed: boolean | null;/** Plain-English "which key / subscription, and what for". */credential_help: string | null;diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.tsindex 157370e089..80ab7af378 100644--- a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts@@ -1,6 +1,12 @@-import { useEffect, useMemo, useRef } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";+import {+ REALTIME_TRANSPORT_ISSUE_EVENT,+ requestRealtimeTransportOffer,+ type RealtimeTransportIssue,+ type RealtimeTransportIssueDetail,+} from "@/lib/realtimeTransportIssue";import { useEventStore } from "@/store/events";type VoiceModeResp = {@@ -9,6 +15,17 @@ type VoiceModeResp = {requires_webrtc_offer: boolean;/** Longest handshake any eligible realtime provider declares it needs. */handshake_budget_s?: number;+ /**+ * Offer-requiring transports only: whether the embedded desktop currently has+ * a WebRTC offer registered, plus the backend's one-line diagnosis.+ *+ * Only the subscription transport sets `requires_webrtc_offer`, so this pair+ * is the ONLY honest explanation for "the call never starts" on that path.+ * The backend has always emitted it and nothing read it, which is how a call+ * stuck waiting for an offer rendered as "no voice session is active".+ */+ transport_offer_ready?: boolean;+ transport_offer_detail?: string | null;active_provider: string | null;// Sidebar-footer display fields: pretty provider name + the model an idle// realtime session would use (configured pin or catalog default).@@ -33,11 +50,63 @@ const REALTIME_DISCOVERY_RETRY_MAX_MS = 10_000;* the fixed 20 s used to report those legitimate negotiations as timeouts.*/const REALTIME_START_BUDGET_FLOOR_MS = 20_000;+/** How often this snapshot is re-read while a realtime start is in flight.+ *+ * A cold subscription transport spends 15-25 s spawning its app-server,+ * verifying the account and negotiating WebRTC, and NOTHING is published during+ * that window. Without this poll every status surface sat frozen on its last+ * value, so a call that was legitimately negotiating rendered as "no voice+ * session is active" for half a minute.+ */+const REALTIME_START_POLL_MS = 750;+/** Grace beyond the declared handshake budget before the poll gives up. */+const REALTIME_START_PENDING_SLACK_MS = 5_000;++/** Bus events that change the RUNTIME half of this snapshot.+ *+ * `RealtimeSessionStarting` is the start-of-handshake signal (emitter owned by+ * the realtime session): it makes the connecting state exact instead of+ * inferred. The polling below deliberately does not depend on it, so this+ * surface is already correct against a backend that does not publish it.+ */+const REALTIME_RUNTIME_EVENTS: ReadonlySet<string> = new Set([+ "VoiceSessionStarted",+ "RealtimeSessionStarting",+ "RealtimeSessionReady",+ "VoiceSessionEnded",+]);++/** How far into the (newest-first) event log the runtime-event probe looks.+ *+ * The log holds 500 entries and this scan ran on EVERY websocket frame. A+ * freshly pushed event sits at index 0, so a shallow bounded scan still sees+ * every arrival, including a small batch delivered in one render.+ */+const RUNTIME_EVENT_SCAN_DEPTH = 8;export function useVoiceMode() {const qc = useQueryClient();const events = useEventStore((state) => state.events);+ const voiceState = useEventStore((state) => state.voiceState);const realtimeDiscoveryStartedAt = useRef<number | null>(null);+ // Attempts inside the CURRENT discovery window. The query-lifetime+ // `dataUpdateCount` grows with every unrelated refetch, so after a dozen of+ // them a FRESH window's first re-check already waited the full cap — the+ // stale-counter trap (AP-19).+ const realtimeDiscoveryAttempts = useRef(0);+ // Wall-clock deadline until which a realtime start is believed in flight.+ // Held in STATE, not only a ref: `refetchInterval` stops polling the moment+ // the window closes, so a ref alone would leave the last render showing+ // "connecting" with nothing left to re-render it — a stuck indicator instead+ // of a stuck call, which is barely an improvement.+ const [startPendingUntil, setStartPendingUntil] = useState(0);+ const startPendingUntilRef = useRef(0);+ startPendingUntilRef.current = startPendingUntil;+ // The CLIENT side of "no WebRTC offer is available". The backend can only+ // report that none is registered; it cannot see a broker that never reached+ // the socket, which is exactly the failure that used to be invisible.+ const [transportIssue, setTransportIssue] =+ useState<RealtimeTransportIssue | null>(null);const q = useQuery<VoiceModeResp>({queryKey: ["voice-mode"],queryFn: async ({ signal }) =>@@ -49,13 +118,25 @@ export function useVoiceMode() {).json(),refetchInterval: (query) => {const data = query.state.data;+ const now = Date.now();++ // 1. A realtime START is in flight — either the backend says so+ // (`transitioning`), or this client asked for one / saw a voice+ // session open that this snapshot does not know about yet. The+ // accepted-session case is cleared by an effect below, so this stays+ // a pure read.+ if (data?.transitioning === true || now < startPendingUntilRef.current) {+ return REALTIME_START_POLL_MS;+ }++ // 2. Provider discovery is still pending (cold boot, login in flight).const discoveryPending =data?.mode === "realtime" && data.realtime_available === false;if (!discoveryPending) {realtimeDiscoveryStartedAt.current = null;+ realtimeDiscoveryAttempts.current = 0;return false;}- const now = Date.now();realtimeDiscoveryStartedAt.current ??= now;if (now - realtimeDiscoveryStartedAt.current >=@@ -66,11 +147,26 @@ export function useVoiceMode() {// Codex discovery can briefly report unavailable while its isolated// login/runtime probe is still in flight during cold boot. Retry quickly// once, then back off while a browser OAuth flow is still open.- const exponent = Math.max(0, query.state.dataUpdateCount - 1);+ const exponent = realtimeDiscoveryAttempts.current;+ realtimeDiscoveryAttempts.current += 1;return Math.min(1_000 * 2 ** exponent, REALTIME_DISCOVERY_RETRY_MAX_MS);},refetchIntervalInBackground: false,});++ /** Arm the connecting poll for one realtime start attempt. */+ const markRealtimeStartPending = useCallback(() => {+ const cached = qc.getQueryData<VoiceModeResp>(["voice-mode"]);+ const budgetMs = Math.max(+ REALTIME_START_BUDGET_FLOOR_MS,+ Math.round((cached?.handshake_budget_s ?? 0) * 1000),+ );+ setStartPendingUntil(Date.now() + budgetMs + REALTIME_START_PENDING_SLACK_MS);+ // Kick the query so react-query re-evaluates `refetchInterval` now instead+ // of whenever the previous schedule happened to land.+ void qc.invalidateQueries({ queryKey: ["voice-mode"] });+ }, [qc]);+const m = useMutation({mutationFn: async (mode: string) => {const r = await fetch("/api/settings/voice-mode", {@@ -90,10 +186,18 @@ export function useVoiceMode() {await qc.cancelQueries({ queryKey: ["voice-mode"] });const prev = qc.getQueryData<VoiceModeResp>(["voice-mode"]);if (prev) qc.setQueryData<VoiceModeResp>(["voice-mode"], { ...prev, mode });+ // Selecting realtime restarts an open call through the full provider+ // handshake — arm the connecting poll so the status rows follow it, and+ // ask the offer broker to publish BEFORE the reconnect lands.+ if (mode === "realtime") {+ requestRealtimeTransportOffer();+ markRealtimeStartPending();+ }return { prev };},onError: (_err, _mode, ctx) => {if (ctx?.prev) qc.setQueryData(["voice-mode"], ctx.prev);+ setStartPendingUntil(0);},onSettled: () => qc.invalidateQueries({ queryKey: ["voice-mode"] }),});@@ -101,40 +205,104 @@ export function useVoiceMode() {// A realtime provider card changes the provider, never `[voice].mode`.// Refresh because this response also carries the selected provider/model// shown in the runtime status; the engine mode itself remains user-controlled.+ // A switch also reconnects an open call, so the connecting poll is armed too.+ // The same event is dispatched when a subscription login connects or+ // disconnects, which is what makes `realtime_available` flip without waiting+ // out the discovery backoff.useEffect(() => {function onRealtimeSwitched() {- qc.invalidateQueries({ queryKey: ["voice-mode"] });+ markRealtimeStartPending();}window.addEventListener("jarvis:realtime-switched", onRealtimeSwitched);- return () => window.removeEventListener("jarvis:realtime-switched", onRealtimeSwitched);- }, [qc]);+ return () =>+ window.removeEventListener("jarvis:realtime-switched", onRealtimeSwitched);+ }, [markRealtimeStartPending]);++ useEffect(() => {+ function onTransportIssue(event: Event) {+ const detail = (event as CustomEvent<RealtimeTransportIssueDetail>).detail;+ setTransportIssue(detail?.issue ?? null);+ }+ window.addEventListener(REALTIME_TRANSPORT_ISSUE_EVENT, onTransportIssue);+ return () =>+ window.removeEventListener(REALTIME_TRANSPORT_ISSUE_EVENT, onTransportIssue);+ }, []);// 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],- );+ const lastRuntimeEvent = useMemo(() => {+ const depth = Math.min(events.length, RUNTIME_EVENT_SCAN_DEPTH);+ for (let index = 0; index < depth; index++) {+ if (REALTIME_RUNTIME_EVENTS.has(events[index].name)) return events[index];+ }+ return null;+ }, [events]);+ useEffect(() => {+ if (lastRuntimeEvent === null) return;+ if (lastRuntimeEvent.name === "RealtimeSessionStarting") {+ // Start of the handshake: arm the poll (which also refetches).+ markRealtimeStartPending();+ return;+ }+ qc.invalidateQueries({ queryKey: ["voice-mode"] });+ }, [lastRuntimeEvent, markRealtimeStartPending, qc]);++ const mode = q.data?.mode ?? "pipeline";+ const sessionActive = q.data?.session_active ?? false;++ // A voice session is audibly running (the pipeline left IDLE) while this+ // snapshot still reports no realtime session: that gap IS the handshake.+ // Derived from state the client already has, so the connecting indicator is+ // never blocked on a backend event landing first.+ useEffect(() => {+ if (mode !== "realtime" || voiceState === "idle" || sessionActive) return;+ markRealtimeStartPending();+ }, [markRealtimeStartPending, mode, sessionActive, voiceState]);++ const transitioning = q.data?.transitioning ?? false;+ const startPending = startPendingUntil > 0;++ // The handshake landed — drop the window instead of waiting it out.+ useEffect(() => {+ if (!startPending) return;+ if (sessionActive && q.data?.active_session_mode === "realtime" && !transitioning) {+ setStartPendingUntil(0);+ }+ }, [q.data?.active_session_mode, sessionActive, startPending, transitioning]);++ // …and if it never lands, close the window on a timer so the indicator+ // cannot outlive the budget it was given.useEffect(() => {- if (lastRuntimeEvent !== null) {- qc.invalidateQueries({ queryKey: ["voice-mode"] });+ if (startPendingUntil === 0) return;+ const remaining = startPendingUntil - Date.now();+ if (remaining <= 0) {+ setStartPendingUntil(0);+ return;}- }, [lastRuntimeEvent, qc]);+ const timer = window.setTimeout(() => setStartPendingUntil(0), remaining);+ return () => window.clearTimeout(timer);+ }, [startPendingUntil]);return {- mode: q.data?.mode ?? "pipeline",+ mode,realtimeAvailable: q.data?.realtime_available ?? false,requiresWebRtcOffer: q.data?.requires_webrtc_offer ?? false,startBudgetMs: Math.max(REALTIME_START_BUDGET_FLOOR_MS,Math.round((q.data?.handshake_budget_s ?? 0) * 1000),),+ /** A realtime call is negotiating right now — neither idle nor running. */+ connecting: (transitioning || startPending) && !sessionActive,+ /** Offer-requiring transports: is a browser offer registered right now?+ * A client-side broker failure counts as "no", because it IS the reason. */+ transportOfferReady:+ transportIssue !== null ? false : q.data?.transport_offer_ready ?? null,+ /** Backend one-liner naming WHY no offer is available. Rendered verbatim. */+ transportOfferDetail: (q.data?.transport_offer_detail ?? "") || "",+ /** Client-side blocker, translated by the renderer. `null` = the broker is+ * fine and the backend detail above is the whole story. */+ transportIssue,// Distinguishes "the server SAID no realtime key" from "we never heard// back" (timeout/loading). Without it a failed status fetch showed the// false claim "Realtime needs provider setup" and looked like a locked@@ -143,12 +311,12 @@ export function useVoiceMode() {activeProvider: q.data?.active_provider ?? null,activeProviderLabel: q.data?.active_provider_label ?? null,activeModel: q.data?.active_model_label ?? q.data?.active_model ?? null,- sessionActive: q.data?.session_active ?? false,+ sessionActive,activeSessionMode: q.data?.active_session_mode ?? null,activeSessionProvider: q.data?.active_session_provider ?? "",activeSessionModel:q.data?.active_session_model_label ?? q.data?.active_session_model ?? "",- transitioning: q.data?.transitioning ?? false,+ transitioning,setMode: m.mutate,isLoading: q.isLoading,isSaving: m.isPending,diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 8d8a03a65e..69b9026faa 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -10,6 +10,7 @@ import {import { clearVoiceInputLevel, setVoiceInputLevel } from "@/lib/voiceInputLevel";import {SECTION_LABELS,+ VOICE_STATES,isSectionId,useEventStore,type ChatMessage,@@ -242,11 +243,31 @@ export function useWebSocket(): void {if (env.event_name === "ErrorOccurred") {// Brain errors abort the wait cycle, otherwise the indicator hangs// until the 60s timeout. We ignore other layer errors here.- const p = env.payload as { layer?: string; source_layer?: string };+ const p = env.payload as {+ layer?: string;+ source_layer?: string;+ message?: string;+ recoverable?: boolean;+ };if (p.layer === "brain" || p.source_layer === "brain") {setChatThinking(false);console.log("[ChatThinking] brain-error → false");}+ // A realtime provider failed or crossed families mid-call. This is+ // the ONLY channel that reaches the desktop surface, where the+ // provider_warning / provider_fallback control frames never leave+ // the pipeline — so without it a call that silently moved to another+ // provider (and another billing path, AP-22) said nothing at all.+ const layer = p.layer ?? p.source_layer ?? "";+ if (layer.startsWith("realtime.")) {+ const detail = typeof p.message === "string" ? p.message.trim() : "";+ pushToast(+ p.recoverable === false ? "error" : "warning",+ detail || translate("use_web_socket.realtime_provider_issue"),+ );+ // The live provider/model may have changed with it.+ void queryClient.invalidateQueries({ queryKey: ["voice-mode"] });+ }}if (env.event_name === "TranscriptionUpdate") {@@ -418,6 +439,14 @@ export function useWebSocket(): void {if (keys.includes("ui.language")) void hydrateUiLanguage();if (keys.includes("brain.reply_language")) void hydrateReplyLanguage();if (keys.includes("ui.theme")) void hydrateUiTheme();+ // Relayed for cards that own a config value nothing else tracks (the+ // per-provider realtime model/voice pins). Each listener filters the+ // keys it cares about, so this stays one cheap fan-out.+ window.dispatchEvent(+ new CustomEvent("jarvis:config-reloaded", {+ detail: { changed_keys: keys },+ }),+ );}if (env.event_name === "ToastNotification") {@@ -503,5 +532,8 @@ export function useWebSocket(): void {}function isVoiceState(v: unknown): v is VoiceState {- return v === "idle" || v === "listening" || v === "thinking" || v === "speaking" || v === "error";+ // Derived from the union's own member list, never a second hand-kept literal+ // set: a supervisor state this guard rejects is dropped in silence and the+ // indicator freezes on whatever it showed before (BUG-008 class).+ return typeof v === "string" && (VOICE_STATES as readonly string[]).includes(v);}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex eeff3cb5ca..ab9c7a63f7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -388,7 +388,10 @@"starting": "Sprachmodul startet…","warming_title": "{name} fährt hoch","warming_hint": "Das Zuhören wird vorbereitet – einen Moment, gleich kannst du sprechen.",- "ready_title": "Bereit – du kannst jetzt sprechen"+ "ready_title": "Bereit – du kannst jetzt sprechen",+ "connecting": "Verbinde…",+ "paused": "Pausiert",+ "indicator_label": "Sprachstatus"},"sidebar": {"wake_hint": "Sag dein Wake-Word…",@@ -415,7 +418,15 @@"realtime_browser_tts_unavailable": "Dieser Browser hat keine nutzbare Systemstimme. Die Antwort bleibt als Text verfügbar; verbinde für Audio einen TTS-Anbieter.","realtime_pipeline_fallback": "Klassische Pipeline als Fallback","realtime_unavailable": "Realtime-Anbieter verbinden oder einrichten",- "realtime_error": "Die Sprachverbindung konnte nicht gestartet werden. Teste den aktiven Realtime-Anbieter unter API Keys und versuche es erneut."+ "realtime_error": "Die Sprachverbindung konnte nicht gestartet werden. Teste den aktiven Realtime-Anbieter unter API Keys und versuche es erneut.",+ "realtime_provider_fallback": "{0} war nicht mehr verfügbar, deshalb läuft das Gespräch jetzt über einen anderen Anbieter — die Abrechnung kann abweichen. {1}",+ "realtime_provider_fallback_short": "Das Gespräch hat {0} verlassen und läuft über einen anderen Anbieter.",+ "realtime_provider_warning": "Der Realtime-Anbieter meldet ein behebbares Problem; das Gespräch läuft weiter.",+ "realtime_provider_unknown": "der bisherige Anbieter",+ "realtime_webrtc_degraded": "Der WebRTC-Transport konnte nicht aufgebaut werden; der Ton läuft weiter über die Audio-Verbindung.",+ "realtime_transport_capability_missing": "Dieses Fenster hat die Desktop-Berechtigung für den Abo-Transport nicht erhalten. Starte die App neu.",+ "realtime_transport_offer_unsupported": "Dieses Fenster kann die WebRTC-Verbindung für den Abo-Transport nicht aufbauen. Nutze stattdessen einen API-Realtime-Anbieter.",+ "realtime_transport_socket_unreachable": "Der Kanal für den Abo-Transport war nicht erreichbar. Starte die App neu und versuche es erneut."},"provider_billing": {"api": "API, Abrechnung pro Token",@@ -1226,7 +1237,39 @@"reco_computer_use_why": "die schnellste Latenz für Tool-Aufrufe.","reco_subagents_pick": "ChatGPT- oder Claude-Max-Subscription","reco_subagents_why": "Flatrate für schwere Hintergrundarbeit.",- "mode_status_unknown": "Der Engine-Status ist noch nicht geladen - der Schalter wird frei, sobald das Backend antwortet. Bleibt das so, starte die App neu."+ "mode_status_unknown": "Der Engine-Status ist noch nicht geladen - der Schalter wird frei, sobald das Backend antwortet. Bleibt das so, starte die App neu.",+ "runtime_connecting": "Die Realtime-Sitzung wird verbunden — über einen Abo-Transport kann das bis zu einer Minute dauern.",+ "state_active": "aktiv",+ "state_ready": "bereit",+ "state_checking": "wird geprüft",+ "state_unavailable": "nicht verfügbar",+ "state_blocked": "blockiert",+ "state_missing": "fehlt",+ "state_not_connected": "nicht verbunden",+ "state_open": "offen",+ "activate_tooltip_active": "Dieser Anbieter ist aktiv",+ "activate_tooltip_activate": "Diesen Anbieter aktivieren",+ "activate_tooltip_blocked": "Anbieter kann nicht aktiviert werden",+ "auth_mode_api_key": "Anmeldung per API-Schlüssel",+ "auth_mode_codex": "ChatGPT-/Codex-Anmeldung",+ "auth_mode_antigravity": "Google-Abo-Anmeldung",+ "auth_mode_none": "Lokal — keine Anmeldung",+ "agents_only_short": "Nur für {0} verfügbar",+ "agents_only_toast": "{0} ist nur für {1} verfügbar.",+ "agents_only_note": "Nur {0}. Dieser Anbieter kann nicht als Haupt-Brain oder Computer-Use-Planer dienen, weil er keine Screenshots erhält.",+ "local_optional_key_hint": "Lokaler Anbieter — läuft ohne Zugangsdaten. Der Schlüssel unten ist optional und nur für Server nötig, die einen verlangen (z. B. vLLM --api-key).",+ "local_no_credentials_hint": "Lokaler Anbieter — keine Zugangsdaten nötig.",+ "polish_verify_failed": "{0} ist ausgewählt, hat aber nicht geantwortet: {1}",+ "switch_note_next_start": " (aktiv ab dem nächsten Sprachstart)",+ "switch_done_brain": "Brain → {0}",+ "switch_done_tts": "Sprachausgabe → {0}",+ "switch_done_stt": "Spracheingabe → {0}",+ "switch_done_computer_use": "Computer-Use → {0}",+ "switch_done_dictation": "Diktat-Formulierung → {0}",+ "switch_done_realtime": "Realtime → {0}",+ "experimental_note": "Dieser Anbieter nutzt ein instabiles Protokoll, das sich ohne Vorankündigung ändern kann. Wenn es nicht startet, endet das Gespräch.",+ "experimental_consent": "Bevor du das aktivierst: Dieser Anbieter nutzt eine experimentelle, instabile Route, die sich ohne Vorankündigung ändern kann. Wenn sie ausfällt, endet das Gespräch, statt von selbst auf einen anderen Anbieter zu wechseln. Fortfahren?",+ "trademark_notice": "Anbieter- und Dienstnamen sowie Logos sind Marken ihrer jeweiligen Inhaber und werden nur gezeigt, um die verbindbaren Integrationen zu benennen. Eine Verbindung oder Empfehlung ist damit nicht gemeint."},"apikeys_test": {"button": "Testen",@@ -2690,7 +2733,8 @@"jarvis_opened": "{name} öffnete","prompt_sent": "Prompt gesendet an","prompt_not_submitted": "der Prompt steht im Eingabefeld, abgeschickt wurde er nicht",- "dictation_nowhere": "Es war kein Textfeld aktiv, deshalb wurde das Diktat nicht eingefügt. Es steht in der Diktat-Historie."+ "dictation_nowhere": "Es war kein Textfeld aktiv, deshalb wurde das Diktat nicht eingefügt. Es steht in der Diktat-Historie.",+ "realtime_provider_issue": "Der Realtime-Anbieter meldet ein Problem."},"chat_thread": {"message_to": "Nachricht an",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex a7cb304b17..fed88bb6ca 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -388,7 +388,10 @@"starting": "Voice starting…","warming_title": "{name} is starting up","warming_hint": "Getting ready to listen – one moment, you'll be able to speak shortly.",- "ready_title": "Ready – you can speak now"+ "ready_title": "Ready – you can speak now",+ "connecting": "Connecting…",+ "paused": "Paused",+ "indicator_label": "Voice state"},"sidebar": {"wake_hint": "Say your wake word…",@@ -415,7 +418,15 @@"realtime_browser_tts_unavailable": "This browser has no usable system voice. The answer is still available as text; connect a TTS provider for audio.","realtime_pipeline_fallback": "Classic pipeline fallback","realtime_unavailable": "Connect or configure a Realtime provider",- "realtime_error": "Couldn’t start voice. Test the active Realtime provider under API Keys, then retry."+ "realtime_error": "Couldn’t start voice. Test the active Realtime provider under API Keys, then retry.",+ "realtime_provider_fallback": "{0} became unavailable, so the call moved to another provider — billing may differ. {1}",+ "realtime_provider_fallback_short": "The call moved off {0} to another provider.",+ "realtime_provider_warning": "The realtime provider reported a recoverable problem; the call continues.",+ "realtime_provider_unknown": "the previous provider",+ "realtime_webrtc_degraded": "The WebRTC transport could not be set up; audio continues over the audio socket.",+ "realtime_transport_capability_missing": "This window did not receive the desktop permission needed to open the subscription transport. Restart the app.",+ "realtime_transport_offer_unsupported": "This window cannot create the WebRTC connection the subscription transport needs. Use an API Realtime provider instead.",+ "realtime_transport_socket_unreachable": "The subscription transport channel could not be reached. Restart the app, then try again."},"provider_billing": {"api": "API, billed per token",@@ -1227,7 +1238,38 @@"reco_computer_use_why": "the snappiest tool latency.","reco_subagents_pick": "ChatGPT or Claude Max subscription","reco_subagents_why": "flat rate for heavy background work.",- "mode_status_unknown": "Engine status has not loaded yet - the switch unlocks as soon as the backend answers. If this persists, restart the app."+ "mode_status_unknown": "Engine status has not loaded yet - the switch unlocks as soon as the backend answers. If this persists, restart the app.",+ "runtime_connecting": "Connecting the Realtime session — this can take up to a minute on a subscription transport.",+ "state_active": "active",+ "state_ready": "ready",+ "state_checking": "checking",+ "state_unavailable": "unavailable",+ "state_blocked": "blocked",+ "state_missing": "missing",+ "state_not_connected": "not connected",+ "state_open": "open",+ "activate_tooltip_active": "This provider is active",+ "activate_tooltip_activate": "Activate this provider",+ "activate_tooltip_blocked": "Provider cannot be activated",+ "auth_mode_api_key": "API key auth",+ "auth_mode_codex": "ChatGPT / Codex login",+ "auth_mode_antigravity": "Google subscription login",+ "auth_mode_none": "Local — no auth",+ "agents_only_short": "Available for {0} only",+ "agents_only_toast": "{0} is only available for {1}.",+ "agents_only_note": "{0} only. This provider cannot be used as the main Brain or Computer-Use planner because it does not receive screenshots.",+ "local_optional_key_hint": "Local provider — runs without credentials. The key below is optional, only for servers that enforce one (e.g. vLLM --api-key).",+ "local_no_credentials_hint": "Local provider — no credentials needed.",+ "polish_verify_failed": "{0} is selected, but it did not answer: {1}",+ "switch_note_next_start": " (active from next voice start)",+ "switch_done_brain": "Brain → {0}",+ "switch_done_tts": "Voice output → {0}",+ "switch_done_stt": "Voice input → {0}",+ "switch_done_computer_use": "Computer-Use → {0}",+ "switch_done_dictation": "Dictation wording → {0}",+ "switch_done_realtime": "Realtime → {0}",+ "experimental_note": "This provider uses an unstable protocol that can change without notice. If it cannot start, the call stops.",+ "experimental_consent": "Before you turn this on: this provider uses an experimental, unstable route that can change without notice. If it breaks, the call stops instead of switching to another provider on its own. Continue?"},"apikeys_test": {"button": "Test",@@ -2691,7 +2733,8 @@"jarvis_opened": "{name} opened","prompt_sent": "Prompt sent to","prompt_not_submitted": "the prompt is in its input box, not sent",- "dictation_nowhere": "No text field had focus, so the dictation was not inserted. It is in the dictation history."+ "dictation_nowhere": "No text field had focus, so the dictation was not inserted. It is in the dictation history.",+ "realtime_provider_issue": "The realtime provider reported a problem."},"chat_thread": {"message_to": "Message to",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 51add471c1..aaa82f86c1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -388,7 +388,10 @@"starting": "Iniciando voz…","warming_title": "{name} se está iniciando","warming_hint": "Preparando la escucha – un momento, podrás hablar en breve.",- "ready_title": "Listo – ya puedes hablar"+ "ready_title": "Listo – ya puedes hablar",+ "connecting": "Conectando…",+ "paused": "En pausa",+ "indicator_label": "Estado de voz"},"sidebar": {"wake_hint": "Di tu palabra de activación…",@@ -415,7 +418,15 @@"realtime_browser_tts_unavailable": "Este navegador no tiene una voz del sistema utilizable. La respuesta sigue disponible como texto; conecta un proveedor de TTS para oírla.","realtime_pipeline_fallback": "Sistema de voz clásico como alternativa","realtime_unavailable": "Conecta o configura un proveedor de tiempo real",- "realtime_error": "No se pudo iniciar la voz. Prueba el proveedor activo en API Keys y vuelve a intentarlo."+ "realtime_error": "No se pudo iniciar la voz. Prueba el proveedor activo en API Keys y vuelve a intentarlo.",+ "realtime_provider_fallback": "{0} dejó de estar disponible, así que la llamada pasó a otro proveedor: la facturación puede cambiar. {1}",+ "realtime_provider_fallback_short": "La llamada dejó {0} y continúa con otro proveedor.",+ "realtime_provider_warning": "El proveedor Realtime informó de un problema recuperable; la llamada continúa.",+ "realtime_provider_unknown": "el proveedor anterior",+ "realtime_webrtc_degraded": "No se pudo establecer el transporte WebRTC; el audio continúa por la conexión de audio.",+ "realtime_transport_capability_missing": "Esta ventana no recibió el permiso de escritorio necesario para abrir el transporte de suscripción. Reinicia la aplicación.",+ "realtime_transport_offer_unsupported": "Esta ventana no puede crear la conexión WebRTC que necesita el transporte de suscripción. Usa un proveedor Realtime con API.",+ "realtime_transport_socket_unreachable": "No se pudo acceder al canal del transporte de suscripción. Reinicia la aplicación e inténtalo de nuevo."},"provider_billing": {"api": "API, facturación por token",@@ -1226,7 +1237,39 @@"reco_computer_use_why": "la latencia más rápida para herramientas.","reco_subagents_pick": "Suscripción de ChatGPT o Claude Max","reco_subagents_why": "tarifa plana para el trabajo pesado en segundo plano.",- "mode_status_unknown": "El estado del motor aún no se ha cargado: el selector se desbloquea en cuanto el backend responda. Si persiste, reinicia la aplicación."+ "mode_status_unknown": "El estado del motor aún no se ha cargado: el selector se desbloquea en cuanto el backend responda. Si persiste, reinicia la aplicación.",+ "runtime_connecting": "Conectando la sesión Realtime: con un transporte de suscripción puede tardar hasta un minuto.",+ "state_active": "activo",+ "state_ready": "listo",+ "state_checking": "comprobando",+ "state_unavailable": "no disponible",+ "state_blocked": "bloqueado",+ "state_missing": "falta",+ "state_not_connected": "sin conectar",+ "state_open": "pendiente",+ "activate_tooltip_active": "Este proveedor está activo",+ "activate_tooltip_activate": "Activar este proveedor",+ "activate_tooltip_blocked": "El proveedor no se puede activar",+ "auth_mode_api_key": "Autenticación con clave API",+ "auth_mode_codex": "Inicio de sesión de ChatGPT / Codex",+ "auth_mode_antigravity": "Inicio de sesión de suscripción de Google",+ "auth_mode_none": "Local: sin autenticación",+ "agents_only_short": "Solo disponible para {0}",+ "agents_only_toast": "{0} solo está disponible para {1}.",+ "agents_only_note": "Solo {0}. Este proveedor no puede ser el Brain principal ni el planificador de Computer-Use porque no recibe capturas de pantalla.",+ "local_optional_key_hint": "Proveedor local: funciona sin credenciales. La clave de abajo es opcional, solo para servidores que exigen una (por ejemplo vLLM --api-key).",+ "local_no_credentials_hint": "Proveedor local: no necesita credenciales.",+ "polish_verify_failed": "{0} está seleccionado, pero no respondió: {1}",+ "switch_note_next_start": " (activo desde el próximo inicio de voz)",+ "switch_done_brain": "Brain → {0}",+ "switch_done_tts": "Salida de voz → {0}",+ "switch_done_stt": "Entrada de voz → {0}",+ "switch_done_computer_use": "Computer-Use → {0}",+ "switch_done_dictation": "Redacción del dictado → {0}",+ "switch_done_realtime": "Realtime → {0}",+ "experimental_note": "Este proveedor usa un protocolo inestable que puede cambiar sin aviso. Si no puede iniciarse, la llamada se detiene.",+ "experimental_consent": "Antes de activarlo: este proveedor usa una ruta experimental e inestable que puede cambiar sin aviso. Si falla, la llamada se detiene en lugar de cambiar por su cuenta a otro proveedor. ¿Continuar?",+ "trademark_notice": "Los nombres y logotipos de proveedores y servicios son marcas de sus respectivos titulares y se muestran únicamente para identificar las integraciones que puedes conectar. No implican afiliación ni respaldo."},"apikeys_test": {"button": "Probar",@@ -2690,7 +2733,8 @@"jarvis_opened": "{name} abrió","prompt_sent": "Prompt enviado a","prompt_not_submitted": "el prompt está en su campo de entrada, no se envió",- "dictation_nowhere": "Ningún campo de texto tenía el foco, así que el dictado no se insertó. Está en el historial de dictados."+ "dictation_nowhere": "Ningún campo de texto tenía el foco, así que el dictado no se insertó. Está en el historial de dictados.",+ "realtime_provider_issue": "El proveedor Realtime informó de un problema."},"chat_thread": {"message_to": "Mensaje a",diff --git a/jarvis/ui/web/frontend/src/i18n/realtime-surface-parity.test.ts b/jarvis/ui/web/frontend/src/i18n/realtime-surface-parity.test.tsnew file mode 100644index 0000000000..32332da06d--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/realtime-surface-parity.test.ts@@ -0,0 +1,140 @@+/**+ * Five-layer parity for the values the realtime voice surface renders.+ *+ * Each block below pins ONE vocabulary across every layer it crosses, because+ * a value that exists in one layer and not another is the BUG-008 class: the+ * UI renders nothing, renders a raw key, or — worst — silently drops the+ * update and freezes on its previous state.+ *+ * 1. supervisor voice states Python enum -> TS union -> style maps -> i18n+ * 2. provider state chips UI mapping -> i18n (the card's own vocabulary)+ * 3. transport issues client union -> i18n+ *+ * Block 1 reads the Python enum from disk on purpose: a hand-copied member+ * list here would be the very drift it is supposed to catch.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { dirname, resolve } from "node:path";++import { describe, expect, it } from "vitest";++import { PROVIDER_STATE_CHIPS } from "@/components/providers/ProviderTierSection";+import { REALTIME_TRANSPORT_ISSUES, realtimeTransportIssueKey } from "@/lib/realtimeTransportIssue";+import { VOICE_STATES } from "@/store/events";+import en from "./locales/en.json";+import de from "./locales/de.json";+import es from "./locales/es.json";++type Loc = Record<string, unknown>;++const LOCALES = [+ ["en", en],+ ["de", de],+ ["es", es],+] as const;++function valueAt(locale: Loc, path: string): unknown {+ let current: unknown = locale;+ for (const part of path.split(".")) {+ if (current === null || typeof current !== "object") return undefined;+ current = (current as Loc)[part];+ }+ return current;+}++function expectTranslated(path: string): void {+ for (const [name, locale] of LOCALES) {+ const value = valueAt(locale as Loc, path);+ expect(typeof value, `${name}: ${path}`).toBe("string");+ expect((value as string).trim().length, `${name}: ${path}`).toBeGreaterThan(0);+ }+}++const HERE = dirname(fileURLToPath(import.meta.url));+// src/i18n -> src -> frontend -> web -> ui -> jarvis+const SUPERVISOR_PY = resolve(HERE, "../../../../../state/supervisor.py");++describe("voice state parity (supervisor enum <-> UI)", () => {+ const source = readFileSync(SUPERVISOR_PY, "utf8");+ const body = source.split("class SupervisorState")[1] ?? "";+ const pythonStates = [...body.matchAll(/^\s{4}[A-Z_]+ = "([A-Z_]+)"$/gm)].map(+ (match) => match[1].toLowerCase(),+ );++ it("finds the Python enum (guards the parser itself)", () => {+ expect(pythonStates.length).toBeGreaterThan(3);+ expect(pythonStates).toContain("idle");+ });++ it("the TS union covers every supervisor state", () => {+ // A state the union does not know is dropped by `isVoiceState` without a+ // word, and the only live indicator the desktop has stays on its last+ // value — which is indistinguishable from a hung call.+ const missing = pythonStates.filter(+ (state) => !(VOICE_STATES as readonly string[]).includes(state),+ );+ expect(missing).toEqual([]);+ });++ it("every voice state has a label in en/de/es", () => {+ for (const state of VOICE_STATES) expectTranslated(`voice_state.${state}`);+ });++ it("the surface-only states are translated too", () => {+ // Not supervisor states: the connecting phase of a realtime handshake and+ // the indicator's accessible name.+ expectTranslated("voice_state.connecting");+ expectTranslated("voice_state.indicator_label");+ });+});++describe("provider state chip parity", () => {+ it("defines a non-trivial chip vocabulary (guards the walker)", () => {+ expect(Object.keys(PROVIDER_STATE_CHIPS).length).toBeGreaterThan(4);+ });++ it("every chip has a label in en/de/es", () => {+ for (const chip of Object.values(PROVIDER_STATE_CHIPS)) {+ expectTranslated(chip.key);+ }+ });+});++describe("realtime transport issue parity", () => {+ it("every client-side transport blocker has a label in en/de/es", () => {+ for (const issue of REALTIME_TRANSPORT_ISSUES) {+ expectTranslated(realtimeTransportIssueKey(issue));+ }+ });+});++describe("realtime status copy", () => {+ // Strings the call surface renders for states the backend really emits.+ // Missing in one locale means an English sentence in a German UI.+ const KEYS = [+ "apikeys_view.runtime_connecting",+ "apikeys_view.trademark_notice",+ "apikeys_view.experimental_note",+ "apikeys_view.experimental_consent",+ "apikeys_view.switch_note_next_start",+ "apikeys_view.switch_done_realtime",+ "apikeys_view.activate_tooltip_active",+ "apikeys_view.activate_tooltip_activate",+ "apikeys_view.activate_tooltip_blocked",+ "apikeys_view.auth_mode_api_key",+ "apikeys_view.auth_mode_codex",+ "apikeys_view.auth_mode_antigravity",+ "apikeys_view.auth_mode_none",+ "sidebar.realtime_provider_fallback",+ "sidebar.realtime_provider_fallback_short",+ "sidebar.realtime_provider_warning",+ "sidebar.realtime_provider_unknown",+ "sidebar.realtime_webrtc_degraded",+ "use_web_socket.realtime_provider_issue",+ ] as const;++ for (const key of KEYS) {+ it(`${key} exists in en/de/es`, () => expectTranslated(key));+ }+});diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex b590c89687..10f0f04e51 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -170,6 +170,13 @@ export class BrowserSpeechFallback {: null,) {}+ /**+ * @param language BCP-47 tag resolved by the BACKEND's single turn-language+ * resolver. Empty means "the backend did not say", and the engine's own+ * default is then used — this layer must never invent one, because a+ * second language decision here is exactly the per-layer re-derivation the+ * output-language doctrine forbids.+ */speak(text: string,language: string,@@ -191,7 +198,7 @@ export class BrowserSpeechFallback {this.active = false;handlers.onFinish(outcome);};- utterance.lang = language || "en-US";+ if (language) utterance.lang = language;utterance.volume = Math.max(0, Math.min(1, Number.isFinite(volume) ? volume : 1));utterance.onstart = () => {if (generation === this.generation) handlers.onStart?.();@@ -507,6 +514,16 @@ export class RealtimeAudioClient {this.setOutputRate(message.sample_rate);} else if (type === "tts_browser_fallback") {this.handleBrowserSpeech(message);+ } else if (type === "error_spoken") {+ // The realtime session's surface-TTS path: the trusted, scrub-clean+ // reply the provider itself did not (or must not) speak. The desktop+ // pipeline has always rendered it; this client dropped it silently,+ // which made a cancelled turn look like a dead call — and it is the+ // ONLY message that carries the turn's resolved output language.+ this.handleBrowserSpeech({+ ...message,+ id: typeof message.id === "string" ? message.id : "error_spoken",+ });} else if (type === "thinking" || type === "turn_complete" || type === "tts_end") {this.playbackResampler?.reset();}@@ -595,7 +612,10 @@ export class RealtimeAudioClient {this.playbackResampler?.reset();this.playbackNode?.port.postMessage({ type: "flush" });- const language = typeof message.language === "string" ? message.language : "en-US";+ // Passed through verbatim from the backend's single turn-language+ // resolver. No default is substituted here: inventing one would be a+ // second language decision in a layer that has no business making it.+ const language = typeof message.language === "string" ? message.language : "";const volume = typeof message.volume === "number" ? message.volume : 1;this.browserSpeech.speak(text, language, volume, {onStart: () => this.cb.onAudio?.(),diff --git a/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.tsindex 9c729556f2..359890dd14 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts@@ -1,4 +1,8 @@import { RealtimeWebRtcTransport } from "./realtimeAudio";+import {+ publishRealtimeTransportIssue,+ type RealtimeTransportIssue,+} from "./realtimeTransportIssue";import { mintWsTicket } from "./ws";declare global {@@ -7,7 +11,18 @@ declare global {}}+/** First retry delay; each further failure doubles it up to the cap. */const RECONNECT_DELAY_MS = 1_500;+const RECONNECT_DELAY_MAX_MS = 30_000;+/**+ * Consecutive failures after which the broker stops and says so.+ *+ * A fixed 1.5 s loop against a socket that answers 4401/1008 is a spin, not a+ * retry: the backend refuses until `[voice].mode` is realtime, and a wrong+ * capability refuses forever. Backing off and then reporting an honest+ * terminal state beats hammering a socket that will never accept us.+ */+const RECONNECT_MAX_ATTEMPTS = 6;const WS_OPEN = 1;type OfferTransport = Pick<@@ -65,6 +80,7 @@ export class RealtimeTransportBroker {private reconnectTimer: ReturnType<typeof setTimeout> | null = null;private stopped = true;private generation = 0;+ private failures = 0;constructor(deps: Partial<BrokerDeps> = {}) {this.deps = { ...DEFAULT_DEPS, ...deps };@@ -73,6 +89,7 @@ export class RealtimeTransportBroker {start(): void {if (!this.stopped) return;this.stopped = false;+ this.failures = 0;void this.connect();}@@ -89,11 +106,30 @@ export class RealtimeTransportBroker {socket?.close();}+ /** Stop retrying and name the blocker on every status surface. */+ private fail(issue: RealtimeTransportIssue, detail: string): void {+ this.stopped = true;+ if (this.reconnectTimer !== null) {+ this.deps.cancelSchedule(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ console.warn(`Realtime transport broker unavailable (${issue}): ${detail}`);+ publishRealtimeTransportIssue(issue);+ }+private async connect(): Promise<void> {const generation = ++this.generation;try {const desktopCapability = this.deps.readDesktopCapability();- if (!desktopCapability) return;+ if (!desktopCapability) {+ // The native host injects this shortly after the first paint, so an+ // empty value early on is a race, not a verdict. Retrying (with+ // backoff) is what turns it back into a working call; the previous+ // bare `return` left the broker permanently dead and every later+ // subscription call hung with nothing logged and nothing shown.+ this.noteFailure("capability_missing", "desktop capability not injected yet");+ return;+ }const ticket = await this.deps.mintTicket();if (this.stopped || generation !== this.generation) return;const socket = this.deps.createSocket(buildRealtimeTransportSocketUrl(ticket));@@ -112,15 +148,22 @@ export class RealtimeTransportBroker {};socket.onmessage = (event) => this.handleMessage(socket, event);socket.onerror = () => socket.close();- socket.onclose = () => {+ socket.onclose = (event?: CloseEvent) => {if (this.socket !== socket) return;this.socket = null;this.releaseTransport();- this.scheduleReconnect();+ // `event` is optional on purpose: a close can also be synthesised by+ // the host (and by test doubles) without a CloseEvent, and reading+ // `.code` off nothing would turn a reconnect into a crash.+ const code = event?.code;+ const reason = event?.reason;+ this.noteFailure(+ "socket_unreachable",+ `broker socket closed (${code ?? "no code"}${reason ? `: ${reason}` : ""})`,+ );};} catch (error) {- console.info("Realtime transport broker could not connect.", error);- this.scheduleReconnect();+ this.noteFailure("socket_unreachable", `broker socket failed: ${String(error)}`);}}@@ -141,7 +184,6 @@ export class RealtimeTransportBroker {return;}if (!sdp) {- console.info("This browser cannot broker a WebRTC subscription transport.");socket.send(JSON.stringify({type: "unavailable",@@ -150,8 +192,8 @@ export class RealtimeTransportBroker {);// A missing RTCPeerConnection is a page capability failure, not a// transient socket failure. Report it once and stop the reconnect loop.- this.stopped = true;if (this.transport === transport) this.releaseTransport();+ this.fail("offer_unsupported", "this engine has no usable RTCPeerConnection");socket.close();return;}@@ -164,6 +206,10 @@ export class RealtimeTransportBroker {webrtc_offer_sdp: sdp,}),);+ // A published offer is the proof this broker works — clear any earlier+ // failure so a recovered client stops accusing itself on the status row.+ this.failures = 0;+ publishRealtimeTransportIssue(null);} catch (error) {console.info("Realtime transport broker could not create an offer.", error);if (this.transport === transport) this.releaseTransport();@@ -204,11 +250,31 @@ export class RealtimeTransportBroker {transport?.close();}+ /** Record one failed attempt: retry with backoff, or give up honestly. */+ private noteFailure(issue: RealtimeTransportIssue, detail: string): void {+ if (this.stopped) return;+ this.failures += 1;+ if (this.failures >= RECONNECT_MAX_ATTEMPTS) {+ this.fail(issue, detail);+ return;+ }+ console.info(+ `Realtime transport broker retry ${this.failures}/${RECONNECT_MAX_ATTEMPTS} (${issue}): ${detail}`,+ );+ this.scheduleReconnect();+ }+private scheduleReconnect(): void {if (this.stopped || this.reconnectTimer !== null) return;+ // Exponential, capped. A constant 1.5 s loop against a socket that answers+ // 4401/1008 is a spin against a backend that has already said no.+ const delay = Math.min(+ RECONNECT_DELAY_MS * 2 ** Math.max(0, this.failures - 1),+ RECONNECT_DELAY_MAX_MS,+ );this.reconnectTimer = this.deps.schedule(() => {this.reconnectTimer = null;void this.connect();- }, RECONNECT_DELAY_MS);+ }, delay);}}diff --git a/jarvis/ui/web/frontend/src/lib/realtimeTransportIssue.ts b/jarvis/ui/web/frontend/src/lib/realtimeTransportIssue.tsnew file mode 100644index 0000000000..3c337ee40e--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/realtimeTransportIssue.ts@@ -0,0 +1,83 @@+/**+ * Why the embedded desktop cannot supply the WebRTC offer a subscription+ * realtime transport needs.+ *+ * The backend reports the SERVER side of this ("no offer is registered", via+ * `transport_offer_detail`). It cannot report the client side, because a broker+ * that never reached the socket produced nothing for the backend to observe —+ * and that failure used to be a bare `return` with no log, no retry and no+ * surface, so the call simply hung with the UI claiming nothing was wrong.+ *+ * A closed union rather than free text: every member maps to one+ * `sidebar.realtime_transport_*` key in en/de/es, pinned by+ * `realtime-transport-issue-parity.test.ts`.+ */+export type RealtimeTransportIssue =+ /** The desktop process capability never arrived — the broker cannot authenticate. */+ | "capability_missing"+ /** This engine has no usable RTCPeerConnection, so no offer can be produced. */+ | "offer_unsupported"+ /** The broker socket kept failing; retries are exhausted. */+ | "socket_unreachable";++export const REALTIME_TRANSPORT_ISSUES: readonly RealtimeTransportIssue[] = [+ "capability_missing",+ "offer_unsupported",+ "socket_unreachable",+];++/** i18n key for one issue. Keep in step with the locale files. */+export function realtimeTransportIssueKey(issue: RealtimeTransportIssue): string {+ return `sidebar.realtime_transport_${issue}`;+}++/** Window event carrying the broker's current issue (`null` = healthy). */+export const REALTIME_TRANSPORT_ISSUE_EVENT = "jarvis:realtime-transport-issue";++/**+ * Asks any mounted broker to publish an offer NOW, before a switch reconnects+ * the live call.+ *+ * A provider switch tears the open call down and reopens it synchronously, but+ * the client only learns that the new transport needs an offer after a status+ * round trip — so the reopened session used to start with nothing registered.+ * Dispatched for EVERY realtime switch, never keyed on a provider name (AP-21):+ * a transport that does not need the offer simply lets it expire.+ */+export const REALTIME_TRANSPORT_PREPARE_EVENT = "jarvis:realtime-transport-prepare";++/** How long one prepare request keeps the broker mounted. */+export const REALTIME_TRANSPORT_PREPARE_TTL_MS = 60_000;++export interface RealtimeTransportIssueDetail {+ issue: RealtimeTransportIssue | null;+}++/** True when this host can fan an event out to listeners at all.+ *+ * Both helpers below are pure notifications: a host without an event target+ * (SSR, a worker, a test double that stubs only `window.location`) simply has+ * nobody to tell, and must not take the caller down for it. */+function canDispatch(): boolean {+ return (+ typeof window !== "undefined" && typeof window.dispatchEvent === "function"+ );+}++/** Announce the broker's health to whichever status surface is listening. */+export function publishRealtimeTransportIssue(+ issue: RealtimeTransportIssue | null,+): void {+ if (!canDispatch()) return;+ window.dispatchEvent(+ new CustomEvent<RealtimeTransportIssueDetail>(REALTIME_TRANSPORT_ISSUE_EVENT, {+ detail: { issue },+ }),+ );+}++/** Ask a mounted broker to publish a fresh offer before a switch lands. */+export function requestRealtimeTransportOffer(): void {+ if (!canDispatch()) return;+ window.dispatchEvent(new Event(REALTIME_TRANSPORT_PREPARE_EVENT));+}diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex 5717a230ef..557d8f2bf4 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -8,7 +8,32 @@ import {type ThinkingTraceSnapshot,} from "@/lib/thinkingSteps";-export type VoiceState = "idle" | "listening" | "thinking" | "speaking" | "error";+/**+ * Mirror of `jarvis/state/supervisor.py::SupervisorState`, lowercased.+ *+ * Every member must exist here, in `isVoiceState` (useWebSocket.ts), in both+ * style maps (Sidebar.tsx, VoiceIndicator.tsx) and as a `voice_state.*` key in+ * en/de/es — a value the backend can publish and this union does not know is+ * dropped silently, freezing the only live indicator the desktop has on its+ * previous state. Guarded by `voice-state-parity.test.ts`.+ */+export type VoiceState =+ | "idle"+ | "listening"+ | "thinking"+ | "speaking"+ | "paused"+ | "error";++/** The full lowercased supervisor vocabulary, in the order it is declared. */+export const VOICE_STATES: readonly VoiceState[] = [+ "idle",+ "listening",+ "thinking",+ "speaking",+ "paused",+ "error",+];export type SectionId =| "chats"diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex 8465d414fa..16b36798b7 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -84,6 +84,11 @@ export function ApiKeysView() {mode: liveMode,realtimeAvailable,statusKnown,+ connecting,+ requiresWebRtcOffer,+ transportOfferReady,+ transportOfferDetail,+ transportIssue,sessionActive,activeSessionMode,activeSessionProvider,@@ -147,6 +152,11 @@ export function ApiKeysView() {mode={engineMode}realtimeAvailable={realtimeAvailable}statusKnown={statusKnown}+ connecting={connecting}+ requiresWebRtcOffer={requiresWebRtcOffer}+ transportOfferReady={transportOfferReady}+ transportOfferDetail={transportOfferDetail}+ transportIssue={transportIssue}sessionActive={sessionActive}activeSessionMode={activeSessionMode}activeSessionProvider={activeSessionProvider}diff --git a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsxindex 066742c638..df10420669 100644--- a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx@@ -2,6 +2,7 @@ import { Radio } from "lucide-react";import { Switch } from "@/components/ui/switch";import { useVoiceMode } from "@/hooks/useVoiceMode";+import { realtimeTransportIssueKey } from "@/lib/realtimeTransportIssue";import { useT } from "@/i18n";/**@@ -18,6 +19,11 @@ export function RealtimeVoiceGroup() {const {mode,realtimeAvailable,+ connecting,+ requiresWebRtcOffer,+ transportOfferReady,+ transportOfferDetail,+ transportIssue,sessionActive,activeSessionMode,activeSessionProvider,@@ -31,15 +37,31 @@ export function RealtimeVoiceGroup() {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");+ // "Connecting" comes FIRST. A subscription transport spends 15-45 s spawning+ // its app-server, verifying the account and negotiating WebRTC; reporting+ // that window as "no voice session is active" is what made a working call+ // look frozen.+ const runtimeText = connecting+ ? t("apikeys_view.runtime_connecting")+ : 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");+ // The one honest explanation for a call that never starts on an+ // offer-requiring transport. Rendered verbatim: the backend one-liner names+ // the actual blocker, and paraphrasing it here would drop the diagnosis.+ const offerBlocked =+ on && requiresWebRtcOffer && transportOfferReady === false;+ const offerDetail = !offerBlocked+ ? ""+ : transportIssue+ ? t(realtimeTransportIssueKey(transportIssue))+ : transportOfferDetail;return (<div className="mt-2 rounded-lg border border-border bg-card/60 p-4"><div className="flex items-start gap-3">@@ -61,6 +83,15 @@ export function RealtimeVoiceGroup() {<p className="mt-1.5 text-[11px] text-muted-foreground" aria-live="polite">{runtimeText}</p>+ {offerDetail && (+ <p+ data-testid="realtime-transport-offer-detail"+ className="mt-1 text-[11px] leading-snug text-amber-600 dark:text-amber-400"+ aria-live="polite"+ >+ {offerDetail}+ </p>+ )}</div></div></div>diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex e12efab5d5..3defad0293 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -23,7 +23,7 @@ import loggingimport timefrom collections.abc import Mappingfrom types import SimpleNamespace-from typing import Any, Literal, get_args+from typing import Any, Final, Literal, get_argsfrom fastapi import APIRouter, HTTPException, Request, Responsefrom pydantic import BaseModel, Field@@ -882,6 +882,56 @@ def _codex_binary_path(request: Request | None = None) -> str | None:return getattr(getattr(cfg, "codex", None), "binary_path", "") or None+# Ceiling for the pre-switch wait on a browser WebRTC offer. Long enough to+# cover ICE gathering (~1.5 s) plus one socket round trip, short enough that a+# client which cannot produce one is not punished for it.+_REALTIME_OFFER_WAIT_S: Final = 3.0+_REALTIME_OFFER_POLL_S: Final = 0.1+++def _realtime_provider_requires_offer(provider_id: str) -> bool:+ """Whether ``provider_id``'s transport needs a browser WebRTC offer.++ A capability the adapter class declares, never a provider name (AP-21).+ """+ try:+ from jarvis.core.registry import load+ from jarvis.realtime.protocol import RealtimeProvider++ provider_cls = load("jarvis.realtime", provider_id, protocol=RealtimeProvider)+ except Exception as exc: # noqa: BLE001 — an unloadable adapter needs no wait+ log.debug("Realtime offer-capability probe skipped for %s: %s", provider_id, exc)+ return False+ return bool(getattr(provider_cls, "requires_webrtc_offer", False))+++async def _await_transport_offer(timeout_s: float) -> bool:+ """Wait (bounded) until the UI has registered a WebRTC offer.++ Polls the broker's non-consuming count: ``acquire`` would LEASE the offer+ and hand it to nobody, which is worse than not waiting at all.+ """+ try:+ from jarvis.realtime.offer_broker import (+ get_realtime_transport_offer_broker,+ )+ except ImportError: # Optional realtime support is absent on a minimal install.+ return False+ broker = get_realtime_transport_offer_broker()+ deadline = asyncio.get_running_loop().time() + max(0.0, timeout_s)+ while True:+ if await broker.pending_count() > 0:+ return True+ if asyncio.get_running_loop().time() >= deadline:+ log.info(+ "No browser WebRTC offer appeared within %.1fs; reopening the "+ "realtime session anyway",+ timeout_s,+ )+ return False+ await asyncio.sleep(_REALTIME_OFFER_POLL_S)++def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Any]:"""Lightweight status for the isolated voice-only Codex identity.@@ -3981,7 +4031,23 @@ 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+ from jarvis.ui.web.voice_runtime import reconnect_realtime, voice_engine_status++ # A switch REOPENS an open call immediately. A transport that needs a+ # browser WebRTC offer cannot start without one, and the client only learns+ # it must publish one from the status snapshot it fetches AFTER this+ # response — so the reopened session used to start with nothing registered+ # and hang for the whole handshake budget. The UI now asks for an offer+ # before this request; give it a bounded moment to land. Idle installs skip+ # the wait entirely (there is no call to reopen), and a client that cannot+ # produce an offer just spends the ceiling once rather than failing early+ # on a provider that might still work.+ if await asyncio.to_thread(_realtime_provider_requires_offer, body.provider):+ try:+ if bool(voice_engine_status(request).get("session_active", False)):+ await _await_transport_offer(_REALTIME_OFFER_WAIT_S)+ except Exception as exc: # noqa: BLE001 — never block a switch on this+ log.debug("Realtime offer pre-wait skipped: %s", exc)session_restarted = reconnect_realtime(request, reason=f"realtime_provider:{body.provider}"