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(voice): fall back to browser system speech
Ruben Lütkeba78a4537800
diff --git a/jarvis/browser_voice/session.py b/jarvis/browser_voice/session.pyindex 5fd2b27627..1740914c5d 100644--- a/jarvis/browser_voice/session.py+++ b/jarvis/browser_voice/session.py@@ -30,6 +30,7 @@ import loggingimport timefrom collections.abc import Awaitable, Callablefrom typing import Any+from uuid import uuid4from jarvis.brain.output_filter import scrub_for_voicefrom jarvis.browser_voice.audio import (@@ -45,6 +46,12 @@ log = logging.getLogger("jarvis.browser_voice")SendBinary = Callable[[bytes], Awaitable[None]]SendJson = Callable[[dict[str, Any]], Awaitable[None]]+# Browser-native speech is the last-resort output path when a downloader has a+# usable STT/Brain credential but no matching server-side TTS family. The+# browser acknowledges completion so the session does not reopen the endpoint+# detector while its own voice is still audible through the microphone.+_BROWSER_TTS_ACK_TIMEOUT_S = 120.0+class BrowserVoiceSession:"""One browser microphone/speaker session over a ``/ws/audio`` socket.@@ -101,6 +108,8 @@ class BrowserVoiceSession:self._processing = Falseself._tts_task: asyncio.Task[None] | None = Noneself._turn_task: asyncio.Task[None] | None = None+ self._browser_tts_done: asyncio.Event | None = None+ self._browser_tts_id: str | None = Noneself._ended = False# -- public properties -------------------------------------------------@@ -155,6 +164,18 @@ class BrowserVoiceSession:await self._send_json({"type": "audio_ready"})elif kind == "barge_in":await self._barge_in()+ elif kind == "tts_browser_done":+ fallback_id = str(msg.get("id") or "")+ if fallback_id and fallback_id == self._browser_tts_id:+ outcome = str(msg.get("outcome") or "ended")+ if outcome != "ended":+ log.warning(+ "browser_voice[%s] browser TTS ended with outcome=%s",+ self.session_id,+ outcome,+ )+ if self._browser_tts_done is not None:+ self._browser_tts_done.set()elif kind == "audio_stop":await self.end(reason=HANGUP_CLIENT_STOP)@@ -232,22 +253,87 @@ class BrowserVoiceSession:self._speaking = Truesent = 0try:- await self._send_json({"type": "tts_start", "sample_rate": TTS_SAMPLE_RATE})- async for chunk in self._tts.synthesize(text, language_code=self.language_code):+ stream = self._tts.synthesize(text, language_code=self.language_code)+ iterator = stream.__aiter__()+ while True:+ try:+ chunk = await anext(iterator)+ except StopAsyncIteration:+ break+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - cross output family once+ if sent:+ log.warning(+ "browser_voice[%s] server TTS failed after audio started",+ self.session_id,+ exc_info=True,+ )+ await self._send_json({"type": "tts_end", "partial": True})+ raise+ log.warning(+ "browser_voice[%s] server TTS unavailable; using browser speech: %s",+ self.session_id,+ exc,+ )+ await self._speak_in_browser(text, volume=vol)+ return 0+pcm = getattr(chunk, "pcm", b"")rate = int(getattr(chunk, "sample_rate", TTS_SAMPLE_RATE) or TTS_SAMPLE_RATE)if not pcm:continue+ if sent == 0:+ await self._send_json(+ {"type": "tts_start", "sample_rate": TTS_SAMPLE_RATE}+ )if rate != TTS_SAMPLE_RATE:pcm = resample_pcm16(pcm, rate, TTS_SAMPLE_RATE)pcm = apply_output_gain_pcm16(pcm, vol)await self._send_binary(pcm)sent += 1++ if sent == 0:+ log.warning(+ "browser_voice[%s] server TTS produced no audio; using browser speech",+ self.session_id,+ )+ await self._speak_in_browser(text, volume=vol)+ return 0await self._send_json({"type": "tts_end"})finally:self._speaking = Falsereturn sent+ async def _speak_in_browser(self, text: str, *, volume: float) -> None:+ """Ask the connected browser to speak and wait for its completion ACK."""+ fallback_id = str(uuid4())+ done = asyncio.Event()+ self._browser_tts_id = fallback_id+ self._browser_tts_done = done+ try:+ await self._send_json(+ {+ "type": "tts_browser_fallback",+ "id": fallback_id,+ "text": text,+ "language": self.language_code,+ "volume": max(0.0, min(1.0, float(volume))),+ }+ )+ try:+ await asyncio.wait_for(done.wait(), timeout=_BROWSER_TTS_ACK_TIMEOUT_S)+ except TimeoutError:+ log.warning(+ "browser_voice[%s] browser TTS acknowledgement timed out",+ self.session_id,+ )+ await self._send_json({"type": "tts_end", "fallback": "browser"})+ finally:+ if self._browser_tts_id == fallback_id:+ self._browser_tts_id = None+ self._browser_tts_done = None+# -- barge-in / lifecycle ---------------------------------------------async def _barge_in(self) -> None:@@ -260,6 +346,8 @@ class BrowserVoiceSession:"""if self._tts_task is not None and not self._tts_task.done():self._tts_task.cancel()+ if self._browser_tts_done is not None:+ self._browser_tts_done.set()self._speaking = Falsetry:await self._send_json({"type": "tts_cancel"})@@ -273,6 +361,8 @@ class BrowserVoiceSession:self._ended = Trueif self._tts_task is not None and not self._tts_task.done():self._tts_task.cancel()+ if self._browser_tts_done is not None:+ self._browser_tts_done.set()if self._turn_task is not None and not self._turn_task.done():self._turn_task.cancel()log.info(diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 6765ffd1f1..3f2d40926d 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1048,12 +1048,23 @@ class VoiceBootStatus(Event):device, VAD, wake-word, TTS client) is live — *before* the backgroundconfirmation-audio pre-render finishes. The frontend listens for event_name``VoiceBootStatus`` and reads ``GET /api/voice/status`` on a late mount- (WS events are not persistent). ``detail`` carries a short phase label for- logs/diagnostics only.+ (WS events are not persistent).++ Two degraded recovery paths also set ``ready=True`` solely to release the+ web UI from a permanent loading screen. ``voice_usable`` is the stricter+ product contract for affordances that promise the user can speak now."""ready: bool = Falsedetail: str = ""+ @property+ def voice_usable(self) -> bool:+ """Whether this event truthfully confirms a usable local voice path."""+ return self.ready and self.detail not in {+ "voice_unavailable",+ "watchdog_timeout",+ }+@dataclass(frozen=True, slots=True)class VoiceSessionStarted(Event):diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 22d9fc2c4b..755c36b151 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -1902,7 +1902,9 @@ class DesktopApp:logger.opt(exception=exc).warning("Virtual mouse overlay not startable")self._virtual_cursor = None- def _build_overlay_surface(self, style: str):+ def _build_overlay_surface(+ self, style: str, *, gate_until_voice_ready: bool = False+ ):"""Construct (and start) the overlay surface for a display style.Returns a ``NullOverlay`` for ``"none"`` (no Tk window, no-op surface),@@ -1910,12 +1912,11 @@ class DesktopApp:mascot ``OrbOverlay`` for anything else. Shared by boot wiring and thelive ``swap_overlay`` path so the two never drift.- A persistent ``JarvisBarOverlay`` maps its window immediately, so the- bar is visible as soon as it is constructed — at boot AND on a live- ``swap_overlay``. Its boot visibility is deliberately decoupled from the- voice warm-up / wake path (the sidebar "Voice starting…" badge carries- readiness instead). A non-persistent bar / the mascot still starts- withdrawn and pops on a real session.+ ``gate_until_voice_ready=True`` is reserved for the desktop boot path.+ It lets the Jarvis Bar initialize and paint off-screen, but suppresses+ every reveal until ``OrbBusBridge`` receives the honest voice-usable+ signal. Runtime surfaces keep their immediate behavior. A non-persistent+ bar / the mascot still starts withdrawn and pops on a real session."""if style == "none":from jarvis.ui.jarvisbar import NullOverlay@@ -1924,12 +1925,12 @@ class DesktopApp:if style == "jarvis_bar":from jarvis.ui.jarvisbar import JarvisBarOverlay- # A persistent bar maps immediately. The non-persistent variant- # still starts withdrawn through its own ``persistent`` contract and- # appears on the first genuine voice session.+ # The startup gate is stronger than merely starting withdrawn: early+ # state/wake events cannot reveal the bar while voice is warming.surface = JarvisBarOverlay(persistent=self.cfg.ui.bar_persistent,accent=self.cfg.ui.bar_accent,+ startup_gated=gate_until_voice_ready,)else: # "mascot" (and any legacy style value)from ui.orb.overlay import OrbOverlay@@ -2218,9 +2219,13 @@ class DesktopApp:from ui.orb.bus_bridge import OrbBusBridge# NullOverlay for "none" still gets a bridge, so a live switch to- # bar/mascot works without a restart. A persistent bar maps now;- # voice readiness is reported separately by the desktop UI.- surface = self._build_overlay_surface(orb_style)+ # bar/mascot works without a restart. The boot-created Jarvis Bar+ # initializes withdrawn; the bridge releases its visibility gate+ # only on the genuine voice-usable signal.+ surface = self._build_overlay_surface(+ orb_style,+ gate_until_voice_ready=(orb_style == "jarvis_bar"),+ )hide_on_idle = ((not self.cfg.ui.bar_persistent)if orb_style == "jarvis_bar"@@ -2228,13 +2233,6 @@ class DesktopApp:)bridge = OrbBusBridge(bus=bus, orb=surface, hide_on_idle=hide_on_idle)bridge.attach()- # The persistent bar is already visible. Once the rest of the- # desktop and voice stack have mapped, re-assert its current- # mode/topmost state without changing visibility or turn state.- loop.create_task(- bridge.reassert_persistent_bar_when_voice_ready(),- name="overlay-boot-reassert",- )self._orb = surfaceself._bridge = bridge# Cache the boot surface so a later swap back to it reuses the@@ -2715,7 +2713,7 @@ class DesktopApp:_usable_printed = [False]async def _print_voice_usable(evt: _VBS) -> None:- if getattr(evt, "ready", False) and not _usable_printed[0]:+ if evt.voice_usable and not _usable_printed[0]:_usable_printed[0] = Trueprint("VOICE_USABLE_MS="diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.pyindex 387602daee..6dd45a58a9 100644--- a/jarvis/ui/jarvisbar/overlay.py+++ b/jarvis/ui/jarvisbar/overlay.py@@ -171,10 +171,18 @@ class JarvisBarOverlay:persistent: bool = True,accent: str = "#e7c46e",opacity: float = BAR_ALPHA,+ startup_gated: bool = False,) -> None:self._persistent = persistentself._accent = accentself._opacity = max(0.2, min(1.0, float(opacity))) # clamp to sane range+ # The desktop boot path constructs and paints the bar early, while it is+ # still withdrawn, then releases this gate on the honest voice-usable+ # signal. This is stronger than an initial ``withdraw``: every early+ # IDLE/wake/session ``show()`` is suppressed too, so no event can make the+ # bar advertise a voice stack that is still warming. Runtime-created+ # surfaces leave the opt-in gate off and retain their immediate behavior.+ self._startup_gated = bool(startup_gated)self._mode = "idle"self._ext_level = 0.0# perf_counter() of the last set_level() that carried real sound@@ -225,6 +233,12 @@ class JarvisBarOverlay:self._mode = modeif self._root is None:return+ # Keep accepting state updates while boot is warming so release can show+ # the latest correct mode, but never map the native window before the+ # voice-usable signal. This guard closes the historical bypass where a+ # wake candidate revealed a merely start-withdrawn bar.+ if getattr(self, "_startup_gated", False):+ returnif not self._persistent and mode == "idle":self._enqueue_ui(self._do_hide)else:@@ -249,8 +263,29 @@ class JarvisBarOverlay:"""if self._root is None:return+ if getattr(self, "_startup_gated", False):+ returnself._enqueue_ui(self._do_reassert_z_order)+ def release_startup_gate(self) -> bool:+ """Allow the boot-created bar to become visible exactly once.++ Returns ``True`` only when this call released an active gate. The latest+ mode has continued to track bus events while hidden, so a persistent bar+ is revealed in that mode rather than being reset to idle. A+ non-persistent bar remains withdrawn while idle and can pop normally on+ its next real session.+ """+ if not getattr(self, "_startup_gated", False):+ return False+ self._startup_gated = False+ if self._root is None:+ return True+ if not self._persistent and self._mode == "idle":+ return True+ self._enqueue_ui(self._do_show)+ return True+def set_level(self, level: float) -> None:# Direct atomic write (no enqueue) — matches OrbOverlay.set_level.lv = 0.0 if level < 0.0 else 1.0 if level > 1.0 else float(level)@@ -295,12 +330,13 @@ class JarvisBarOverlay:# Lifecycle ## ------------------------------------------------------------------ #def _should_start_withdrawn(self) -> bool:- """True only for the wake-triggered, non-persistent variant.+ """True while boot-gated or for the non-persistent variant.- A persistent bar is an always-visible desktop element and maps as soon- as its Tk window starts. Voice readiness must never gate its visibility.+ The boot-created persistent bar is fully configured and painted while+ withdrawn, then mapped by ``release_startup_gate`` once voice is usable.+ Other persistent bars keep their immediate-map behavior."""- return not self._persistent+ return (not self._persistent) or getattr(self, "_startup_gated", False)def start_in_thread(self, timeout: float = 3.0) -> None:def _run() -> None:diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsxindex 8e3cdc1c08..db8c6209a3 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx@@ -54,7 +54,10 @@ export function BrowserRealtimeControl() {if (role === "user") setTranscription(text, isFinal);if (role === "user" && isFinal) setVoice("thinking");},- onAudio: () => setVoice("speaking"),+ onAudio: () => {+ setError("");+ setVoice("speaking");+ },onInputLevel: setInputLevel,onStatus: (status, payload) => {if (status === "audio_ready") {@@ -72,6 +75,9 @@ export function BrowserRealtimeControl() {setVoice("listening");} else if (status === "tts_cancel") {setVoice("listening");+ } else if (status === "tts_browser_unavailable" || status === "tts_browser_error") {+ setError(t("sidebar.realtime_browser_tts_unavailable"));+ setVoice("listening");} else if (status === "provider_error" || status === "disconnected") {setState("error");setError(t("sidebar.realtime_error"));diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 266eeecce1..0962faeb17 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -215,6 +215,7 @@"realtime_connecting": "Verbindung wird hergestellt…","realtime_connected": "Verbunden über","realtime_browser_hint": "Auf diesem Gerät verwendet dein Browser das Mikrofon.",+ "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-API-Key einrichten","realtime_error": "Die Sprachverbindung konnte nicht gestartet werden. Teste den aktiven Realtime-Anbieter unter API Keys und versuche es erneut."diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 5cb91cbf55..1a2c178840 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -215,6 +215,7 @@"realtime_connecting": "Connecting…","realtime_connected": "Connected via","realtime_browser_hint": "Your browser owns the microphone on this device.",+ "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": "Configure a Realtime API Key","realtime_error": "Couldn’t start voice. Test the active Realtime provider under API Keys, then retry."diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 109ad91a8a..aa9ff6f88f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -215,6 +215,7 @@"realtime_connecting": "Conectando…","realtime_connected": "Conectado mediante","realtime_browser_hint": "Tu navegador controla el micrófono en este dispositivo.",+ "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": "Configura una clave API de tiempo real","realtime_error": "No se pudo iniciar la voz. Prueba el proveedor activo en API Keys y vuelve a intentarlo."diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsindex 5f91a9ab33..e5851d5dff 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -1,5 +1,9 @@-import { describe, it, expect, beforeEach } from "vitest";-import { buildAudioSocketUrl, StreamingPcm16Resampler } from "./realtimeAudio";+import { describe, it, expect, beforeEach, vi } from "vitest";+import {+ BrowserSpeechFallback,+ buildAudioSocketUrl,+ StreamingPcm16Resampler,+} from "./realtimeAudio";describe("realtime audio client", () => {beforeEach(() => {@@ -32,4 +36,58 @@ describe("realtime audio client", () => {expect([...first, ...second]).toEqual([...whole]);});++ it("speaks a server-approved fallback with language and volume", () => {+ const utterances: SpeechSynthesisUtterance[] = [];+ const synthesis = {+ cancel: vi.fn(),+ speak: vi.fn((utterance: SpeechSynthesisUtterance) => utterances.push(utterance)),+ };+ const createUtterance = (text: string) =>+ ({ text, lang: "", volume: 1, onstart: null, onend: null, onerror: null }) as unknown as+ SpeechSynthesisUtterance;+ const controller = new BrowserSpeechFallback(synthesis, createUtterance);+ const started = vi.fn();+ const finished = vi.fn();++ expect(controller.speak("Hola", "es-ES", 0.4, { onStart: started, onFinish: finished })).toBe(+ true,+ );+ expect(utterances[0].lang).toBe("es-ES");+ expect(utterances[0].volume).toBe(0.4);+ utterances[0].onstart?.(new Event("start") as SpeechSynthesisEvent);+ utterances[0].onend?.(new Event("end") as SpeechSynthesisEvent);+ expect(started).toHaveBeenCalledOnce();+ expect(finished).toHaveBeenCalledWith("ended");+ });++ it("fails honestly when the browser has no speech service", () => {+ const finished = vi.fn();+ const controller = new BrowserSpeechFallback(null, null);++ expect(controller.speak("Answer", "en-US", 1, { onFinish: finished })).toBe(false);+ expect(finished).toHaveBeenCalledWith("unavailable");+ });++ it("ignores a stale completion after a newer fallback starts", () => {+ const utterances: SpeechSynthesisUtterance[] = [];+ const synthesis = {+ cancel: vi.fn(),+ speak: (utterance: SpeechSynthesisUtterance) => utterances.push(utterance),+ };+ const createUtterance = (text: string) =>+ ({ text, lang: "", volume: 1, onstart: null, onend: null, onerror: null }) as unknown as+ SpeechSynthesisUtterance;+ const controller = new BrowserSpeechFallback(synthesis, createUtterance);+ const first = vi.fn();+ const second = vi.fn();++ controller.speak("First", "en-US", 1, { onFinish: first });+ controller.speak("Second", "en-US", 1, { onFinish: second });+ utterances[0].onend?.(new Event("end") as SpeechSynthesisEvent);+ utterances[1].onend?.(new Event("end") as SpeechSynthesisEvent);++ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledWith("ended");+ });});diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex 55faf08af5..587a1f3f5e 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -21,6 +21,86 @@ export type RealtimeCallbacks = {onInputLevel?: (level: number) => void;};+export type BrowserSpeechOutcome = "ended" | "error" | "unavailable";++type BrowserSpeechHandlers = {+ onStart?: () => void;+ onFinish: (outcome: BrowserSpeechOutcome) => void;+};++type SpeechSynthesisSurface = Pick<SpeechSynthesis, "cancel" | "speak">;++/** Keyless speech output for the headless/browser surface.+ *+ * The controller owns exactly one utterance. A new turn or barge-in invalidates+ * callbacks from the previous one, preventing a stale `onend` event from+ * acknowledging the wrong server turn.+ */+export class BrowserSpeechFallback {+ private generation = 0;+ private active = false;++ constructor(+ private readonly synthesis: SpeechSynthesisSurface | null =+ typeof window !== "undefined" && "speechSynthesis" in window+ ? window.speechSynthesis+ : null,+ private readonly createUtterance: ((text: string) => SpeechSynthesisUtterance) | null =+ typeof SpeechSynthesisUtterance === "function"+ ? (text) => new SpeechSynthesisUtterance(text)+ : null,+ ) {}++ speak(+ text: string,+ language: string,+ volume: number,+ handlers: BrowserSpeechHandlers,+ ): boolean {+ this.cancel();+ if (!this.synthesis || !this.createUtterance || !text.trim()) {+ handlers.onFinish("unavailable");+ return false;+ }++ const generation = ++this.generation;+ const utterance = this.createUtterance(text);+ let settled = false;+ const finish = (outcome: BrowserSpeechOutcome) => {+ if (settled || generation !== this.generation) return;+ settled = true;+ this.active = false;+ handlers.onFinish(outcome);+ };+ utterance.lang = language || "en-US";+ utterance.volume = Math.max(0, Math.min(1, Number.isFinite(volume) ? volume : 1));+ utterance.onstart = () => {+ if (generation === this.generation) handlers.onStart?.();+ };+ utterance.onend = () => finish("ended");+ utterance.onerror = () => finish("error");+ try {+ this.active = true;+ this.synthesis.speak(utterance);+ return true;+ } catch {+ finish("error");+ return false;+ }+ }++ cancel(): void {+ this.generation += 1;+ if (!this.active) return;+ this.active = false;+ try {+ this.synthesis?.cancel();+ } catch {+ // A browser may tear down its speech service during page navigation.+ }+ }+}+/** Stateful linear PCM16 resampler used for provider audio playback.** Realtime providers currently emit 24 kHz PCM, while AudioContext commonly@@ -98,6 +178,7 @@ export class RealtimeAudioClient {private ready = false;private intentionalClose = false;private inputMeter = new LevelMeter();+ private browserSpeech = new BrowserSpeechFallback();constructor(private cb: RealtimeCallbacks = {}) {}@@ -209,6 +290,7 @@ export class RealtimeAudioClient {typeof message.role === "string" ? message.role : "user",);} else if (type === "tts_cancel") {+ this.browserSpeech.cancel();this.playbackResampler?.reset();this.playbackNode?.port.postMessage({ type: "flush" });} else if (type === "audio_ready") {@@ -220,7 +302,10 @@ export class RealtimeAudioClient {resolve();}} else if (type === "tts_start") {+ this.browserSpeech.cancel();this.setOutputRate(message.sample_rate);+ } else if (type === "tts_browser_fallback") {+ this.handleBrowserSpeech(message);} else if (type === "turn_complete" || type === "tts_end") {this.playbackResampler?.reset();}@@ -236,6 +321,7 @@ export class RealtimeAudioClient {}private handleAudio(pcm: ArrayBuffer): void {+ this.browserSpeech.cancel();if (!this.playbackResampler) this.setOutputRate(24_000);const converted = this.playbackResampler?.process(pcm) ?? pcm;if (converted.byteLength === 0) return;@@ -243,6 +329,28 @@ export class RealtimeAudioClient {this.cb.onAudio?.();}+ private handleBrowserSpeech(message: RealtimeStatusPayload): void {+ const id = typeof message.id === "string" ? message.id : "";+ const text = typeof message.text === "string" ? message.text : "";+ if (!id || !text.trim()) return;++ this.playbackResampler?.reset();+ this.playbackNode?.port.postMessage({ type: "flush" });+ const language = typeof message.language === "string" ? message.language : "en-US";+ const volume = typeof message.volume === "number" ? message.volume : 1;+ this.browserSpeech.speak(text, language, volume, {+ onStart: () => this.cb.onAudio?.(),+ onFinish: (outcome) => {+ if (outcome !== "ended") {+ this.cb.onStatus?.(`tts_browser_${outcome}`, { ...message, outcome });+ }+ if (this.ws?.readyState === WebSocket.OPEN) {+ this.ws.send(JSON.stringify({ type: "tts_browser_done", id, outcome }));+ }+ },+ });+ }+async disconnect(): Promise<void> {this.intentionalClose = true;await this.teardown(true);@@ -260,6 +368,7 @@ export class RealtimeAudioClient {}}socket?.close();+ this.browserSpeech.cancel();this.captureNode?.disconnect();this.captureSink?.disconnect();this.playbackNode?.disconnect();diff --git a/tests/unit/browser_voice/test_session.py b/tests/unit/browser_voice/test_session.pyindex 834609893f..f41e01be03 100644--- a/tests/unit/browser_voice/test_session.py+++ b/tests/unit/browser_voice/test_session.py@@ -38,6 +38,19 @@ class _SlowTTS:yield AudioChunk(pcm=b"\x01\x00" * 240, sample_rate=24_000, timestamp_ns=0, channels=1)+class _EmptyTTS:+ async def synthesize(self, text, language_code="en-US", voice=None):+ if False:+ yield text, language_code, voice+++class _FailingTTS:+ async def synthesize(self, text, language_code="en-US", voice=None):+ if False:+ yield text, language_code, voice+ raise RuntimeError("server TTS is unavailable")++def _pcm16_frame(amp: int, ms: int = 20, rate: int = STT_SAMPLE_RATE, freq: int = 300) -> bytes:"""One raw int16 mono PCM frame at `rate` (what the browser AudioWorklet sends)."""n = rate * ms // 1000@@ -69,7 +82,10 @@ def _make_session(sink, *, stt=None, brain=None, tts=None, rate=STT_SAMPLE_RATE,session_id="bv1",send_binary=sink.send_binary,send_json=sink.send_json,- stt=stt or FakeSTT(["Wie spät ist es?"]), # i18n-allow: simulated German STT transcript under test+ stt=stt+ or FakeSTT(+ ["Wie spät ist es?"] # i18n-allow: simulated German STT transcript+ ),brain=brain or FakeBrain("Es ist vierzehn Uhr."),tts=tts or FakeTTS(ms_per_char=2),browser_sample_rate=rate,@@ -203,3 +219,65 @@ async def test_end_cancels_tasks():await asyncio.sleep(0)task = session._tts_taskassert task is None or task.cancelled() or task.done()+++async def _complete_browser_tts_fallback(session, sink, text="Portable answer"):+ task = asyncio.create_task(session._speak(text))+ for _ in range(100):+ await asyncio.sleep(0)+ messages = sink.json_of("tts_browser_fallback")+ if messages:+ break+ assert messages+ await session.handle_control(+ {"type": "tts_browser_done", "id": messages[0]["id"], "outcome": "ended"}+ )+ assert await task == 0+ return messages[0]+++async def test_empty_server_tts_uses_acknowledged_browser_voice_fallback():+ sink = _Sink()+ session = _make_session(sink, tts=_EmptyTTS(), language_code="es-ES")++ fallback = await _complete_browser_tts_fallback(session, sink)++ assert fallback["text"] == "Portable answer"+ assert fallback["language"] == "es-ES"+ assert fallback["volume"] == 1.0+ assert sink.binary == []+ assert sink.json_of("tts_start") == []+ assert sink.json_of("tts_end")[-1]["fallback"] == "browser"+++async def test_server_tts_failure_before_audio_uses_browser_voice_fallback():+ sink = _Sink()+ session = _make_session(sink, tts=_FailingTTS())++ await _complete_browser_tts_fallback(session, sink)++ assert sink.binary == []+ assert sink.json_of("tts_browser_fallback")+++async def test_browser_voice_fallback_ack_is_scoped_to_current_id():+ sink = _Sink()+ session = _make_session(sink, tts=_EmptyTTS())+ task = asyncio.create_task(session._speak("Scoped answer"))+ for _ in range(100):+ await asyncio.sleep(0)+ messages = sink.json_of("tts_browser_fallback")+ if messages:+ break+ assert messages++ await session.handle_control(+ {"type": "tts_browser_done", "id": "stale-turn", "outcome": "ended"}+ )+ await asyncio.sleep(0)+ assert not task.done()++ await session.handle_control(+ {"type": "tts_browser_done", "id": messages[0]["id"], "outcome": "ended"}+ )+ assert await task == 0diff --git a/tests/unit/core/test_voice_boot_status.py b/tests/unit/core/test_voice_boot_status.pynew file mode 100644index 0000000000..205b01426e--- /dev/null+++ b/tests/unit/core/test_voice_boot_status.py@@ -0,0 +1,22 @@+"""Strict voice usability must not be confused with a released loading UI."""+from __future__ import annotations++import pytest++from jarvis.core.events import VoiceBootStatus+++ ("event", "expected"),+ [+ (VoiceBootStatus(ready=False, detail="warmup_start"), False),+ (VoiceBootStatus(ready=True, detail="listening"), True),+ (VoiceBootStatus(ready=True), True),+ (VoiceBootStatus(ready=True, detail="voice_unavailable"), False),+ (VoiceBootStatus(ready=True, detail="watchdog_timeout"), False),+ ],+)+def test_voice_usable_excludes_degraded_ui_release_events(+ event: VoiceBootStatus, expected: bool+) -> None:+ assert event.voice_usable is expecteddiff --git a/tests/unit/ui/jarvisbar/test_boot_visibility.py b/tests/unit/ui/jarvisbar/test_boot_visibility.pyindex a56c674a2e..7567c30f84 100644--- a/tests/unit/ui/jarvisbar/test_boot_visibility.py+++ b/tests/unit/ui/jarvisbar/test_boot_visibility.py@@ -1,16 +1,16 @@-"""The persistent JarvisBar is visible immediately at boot.--Regression: the boot wiring used to build the persistent bar WITHDRAWN-(``start_hidden=True``) and reveal it only once voice was ready-(``VoiceBootStatus(ready=True)``). On the serve-first fast-boot path that reveal-was late and/or lost the topmost z-order, so the bar stayed hidden until the-first wake word incidentally re-showed it. The bar's boot visibility must be-decoupled from the voice/wake path: a persistent bar maps its window at boot,-always; a non-persistent bar still pops on a real session.+"""Desktop boot keeps the Jarvis Bar hidden until voice is usable.++Regression history: an earlier ready-gated implementation only withdrew the Tk+window initially. Its reveal could lose z-order, so the bar appeared only when a+wake event happened to show it again. The emergency fix then mapped persistent+bars immediately, which advertised voice while the app still said "starting".++The current contract separates initialization from visibility: boot creates a+fully painted, startup-gated bar; the bus bridge releases that gate directly on+the genuine ``VoiceBootStatus`` event. Runtime builds remain immediate."""from __future__ import annotations-import inspectfrom types import SimpleNamespacefrom jarvis.ui.desktop_app import DesktopApp@@ -30,28 +30,43 @@ def _app(*, bar_persistent: bool) -> DesktopApp:return app-def test_boot_persistent_bar_is_visible_not_withdrawn(monkeypatch) -> None:- # Don't spawn a real Tk window in the unit test.+def _disable_real_tk(monkeypatch) -> None:monkeypatch.setattr(JarvisBarOverlay, "start_in_thread", lambda self, timeout=3.0: None)- surface = _app(bar_persistent=True)._build_overlay_surface("jarvis_bar")+++def test_boot_persistent_bar_is_initialized_but_startup_gated(monkeypatch) -> None:+ _disable_real_tk(monkeypatch)++ surface = _app(bar_persistent=True)._build_overlay_surface(+ "jarvis_bar", gate_until_voice_ready=True+ )assert isinstance(surface, JarvisBarOverlay)assert surface._persistent is True- # Visible at boot — NOT gated behind VoiceBootStatus(ready=True) / a wake word.+ assert surface._startup_gated is True+ assert surface._should_start_withdrawn() is True+++def test_runtime_persistent_bar_keeps_immediate_visibility(monkeypatch) -> None:+ _disable_real_tk(monkeypatch)++ surface = _app(bar_persistent=True)._build_overlay_surface("jarvis_bar")++ assert surface._startup_gated is Falseassert surface._should_start_withdrawn() is False- assert "start_hidden" not in inspect.signature(JarvisBarOverlay).parameters- assert "start_hidden" not in inspect.signature(- DesktopApp._build_overlay_surface- ).parameters-def test_boot_non_persistent_bar_still_starts_withdrawn(monkeypatch) -> None:- monkeypatch.setattr(- JarvisBarOverlay, "start_in_thread", lambda self, timeout=3.0: None+def test_boot_non_persistent_bar_releases_to_normal_session_behavior(monkeypatch) -> None:+ _disable_real_tk(monkeypatch)++ surface = _app(bar_persistent=False)._build_overlay_surface(+ "jarvis_bar", gate_until_voice_ready=True)- surface = _app(bar_persistent=False)._build_overlay_surface("jarvis_bar")- # A non-persistent bar still pops on a real session (unchanged).+ assert surface._startup_gated is True+ assert surface._should_start_withdrawn() is True+ assert surface.release_startup_gate() is True+ # Non-persistent bars remain withdrawn while idle and pop on a real session.assert surface._should_start_withdrawn() is Truediff --git a/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.pyindex 0c5eb8f9da..93cb9a4251 100644--- a/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py+++ b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py@@ -2,10 +2,10 @@Forensic (2026-06-27): a withdrawn→deiconified ``overrideredirect`` window canlose its topmost z-order on Windows, so later desktop windows map above it until-the next wake re-shows it. The persistent bar now maps immediately at boot, and-the voice-ready maintenance pass explicitly re-pins topmost. ``_do_show``-re-asserts ``-topmost`` and lifts only when it maps a withdrawn window.-These tests pin that contract without a real Tk window.+the next wake re-shows it. The voice-ready startup-gate release now maps the+fully configured bar and explicitly re-pins topmost. ``_do_show`` re-asserts+``-topmost`` and lifts only when it maps a withdrawn window. These tests pin+that contract without a real Tk window.Forensic (2026-06-30): re-asserting ``-topmost`` is itself a Win32 stylemutation on this layered (color-key + alpha) window, and Windows can silentlydiff --git a/tests/unit/ui/jarvisbar/test_start_hidden.py b/tests/unit/ui/jarvisbar/test_start_hidden.pyindex 97bba975f6..432863a242 100644--- a/tests/unit/ui/jarvisbar/test_start_hidden.py+++ b/tests/unit/ui/jarvisbar/test_start_hidden.py@@ -1,12 +1,7 @@-"""The JarvisBar initial-visibility contract.--A persistent bar always maps when its Tk mainloop starts. Only the-non-persistent, wake-triggered variant starts withdrawn. There is deliberately-no voice-readiness override that can hide a persistent bar at boot.-"""+"""Jarvis Bar startup-visibility gate contract."""from __future__ import annotations-import inspect+from collections.abc import Callablefrom jarvis.ui.jarvisbar.overlay import JarvisBarOverlay, _create_hidden_tk_root@@ -27,18 +22,60 @@ class _FakeTk:return self.root-def test_persistent_bar_does_not_start_withdrawn() -> None:+def _capture_ui_calls(bar: JarvisBarOverlay) -> list[str]:+ queued: list[str] = []++ def _capture(fn: Callable[[], None]) -> None:+ queued.append(fn.__name__)++ bar._root = object() # noqa: SLF001 - a non-None headless root sentinel+ bar._enqueue_ui = _capture # type: ignore[method-assign]+ return queued+++def test_persistent_bar_maps_immediately_without_startup_gate() -> None:bar = JarvisBarOverlay(persistent=True)+assert bar._should_start_withdrawn() is False+def test_startup_gated_persistent_bar_starts_withdrawn() -> None:+ bar = JarvisBarOverlay(persistent=True, startup_gated=True)++ assert bar._should_start_withdrawn() is True++def test_non_persistent_bar_starts_withdrawn() -> None:bar = JarvisBarOverlay(persistent=False)+assert bar._should_start_withdrawn() is True-def test_start_hidden_override_is_not_part_of_the_surface_api() -> None:- assert "start_hidden" not in inspect.signature(JarvisBarOverlay).parameters+def test_early_show_updates_mode_without_bypassing_startup_gate() -> None:+ bar = JarvisBarOverlay(persistent=True, startup_gated=True)+ queued = _capture_ui_calls(bar)++ bar.show("listen")+ bar.reassert_z_order()++ assert bar._mode == "listen"+ assert queued == []++ assert bar.release_startup_gate() is True+ assert queued == ["_do_show"]+ assert bar.release_startup_gate() is False+ assert queued == ["_do_show"]+++def test_non_persistent_release_stays_hidden_until_real_session() -> None:+ bar = JarvisBarOverlay(persistent=False, startup_gated=True)+ queued = _capture_ui_calls(bar)++ assert bar.release_startup_gate() is True+ assert queued == []++ bar.show("listen")+ assert queued == ["_do_show"]def test_new_tk_root_is_withdrawn_before_configuration() -> None:diff --git a/tests/unit/ui/jarvisbar/test_surface_contract.py b/tests/unit/ui/jarvisbar/test_surface_contract.pyindex d6048cb367..d1089a4e8d 100644--- a/tests/unit/ui/jarvisbar/test_surface_contract.py+++ b/tests/unit/ui/jarvisbar/test_surface_contract.py@@ -8,6 +8,7 @@ from jarvis.ui.jarvisbar.overlay import JarvisBarOverlayREQUIRED = ["show","hide",+ "release_startup_gate","set_level","set_muted","play_animation",@@ -67,6 +68,7 @@ def test_methods_safe_without_tk_window():assert bar._muted is Falsebar.hide() # _root None → safe no-op+ assert bar.release_startup_gate() is Falsebar.play_animation("wave", x=1)bar.stop_animation("think")bar.show_listening_transcript("hi", 10)diff --git a/tests/unit/ui/test_orb_bus_bridge.py b/tests/unit/ui/test_orb_bus_bridge.pyindex 722ad9c7cd..2d98527169 100644--- a/tests/unit/ui/test_orb_bus_bridge.py+++ b/tests/unit/ui/test_orb_bus_bridge.py@@ -1,6 +1,5 @@from __future__ import annotations-import asyncioimport sysfrom pathlib import Path@@ -16,7 +15,7 @@ sys.modules.pop("ui", None)# `ui` lives as a top-level directory in the repo root (not under `jarvis/`).# Some pytest setups don't recognize this path via the discovery loader; in that# case the tests are skipped instead of blowing up test collection.-try: # noqa: SIM105 — bewusster Try-Import wegen Discovery-Quirk+try: # noqa: SIM105 — intentional try-import for the discovery quirkfrom ui.orb.bus_bridge import ( # type: ignore[import-not-found]THINKING_BUBBLE_TEXT,OrbBusBridge,@@ -101,6 +100,19 @@ class _FakeBarWithExplicitReassert(_FakeOrb):self.calls.append(("reassert_z_order", None))+class _FakeStartupGatedBar(_FakeBarWithExplicitReassert):+ def __init__(self) -> None:+ super().__init__()+ self.startup_gated = True++ def release_startup_gate(self) -> bool:+ self.calls.append(("release_startup_gate", None))+ if not self.startup_gated:+ return False+ self.startup_gated = False+ return True++async def test_orb_is_shown_again_for_thinking_after_external_hide() -> None:orb = _FakeOrb()bridge = OrbBusBridge(bus=_FakeBus(), orb=orb, idle_animations_enabled=False) # type: ignore[arg-type]@@ -585,94 +597,129 @@ async def test_reply_is_reset_between_turns() -> None:assert ("show_listening_transcript", "Antwort aus Turn 1.") not in orb.calls-# --- Boot z-order maintenance: visibility never waits for voice readiness.-# The persistent JarvisBar maps immediately. VoiceBootStatus(ready=True) only-# re-asserts its current mode/topmost state after later desktop windows map.+# --- Boot visibility: the Jarvis Bar is the "you can speak now" affordance.+# It stays gated through warm-up and degraded UI-only releases, then maps once+# the genuine VoiceBootStatus arrives. Existing ungated surfaces retain their+# z-order repair for compatibility.-async def test_persistent_bar_reasserts_current_mode_once_when_voice_ready() -> None:- orb = _FakeOrb()- orb._mode = "listen"+async def test_startup_gated_bar_releases_once_when_voice_is_usable() -> None:+ orb = _FakeStartupGatedBar()bridge = OrbBusBridge( # type: ignore[arg-type]bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False)- task = asyncio.create_task(- bridge.reassert_persistent_bar_when_voice_ready(timeout_s=5.0)+ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="listening")+ )+ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="listening"))- await asyncio.sleep(0.05)- # The bridge does not own initial visibility and has not changed the mode.- assert orb.calls == []- await bridge._on_voice_boot_status(VoiceBootStatus(ready=True)) # noqa: SLF001- await asyncio.wait_for(task, timeout=1.0)+ assert orb.calls.count(("release_startup_gate", None)) == 1+ assert not any(call[0] in {"show", "reassert_z_order"} for call in orb.calls)+ assert bridge._boot_visibility_released is True # noqa: SLF001- assert orb.calls.count(("show", "listen")) == 1--async def test_persistent_bar_uses_explicit_z_order_reassert_when_available() -> None:- orb = _FakeBarWithExplicitReassert()+ "event",+ [+ VoiceBootStatus(ready=False, detail="warmup_start"),+ VoiceBootStatus(ready=True, detail="voice_unavailable"),+ VoiceBootStatus(ready=True, detail="watchdog_timeout"),+ ],+)+async def test_non_usable_boot_status_does_not_release_bar(+ event: VoiceBootStatus,+) -> None:+ orb = _FakeStartupGatedBar()bridge = OrbBusBridge( # type: ignore[arg-type]bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False)- await bridge._on_voice_boot_status(VoiceBootStatus(ready=True)) # noqa: SLF001- await bridge.reassert_persistent_bar_when_voice_ready(timeout_s=1.0)+ await bridge._on_voice_boot_status(event) # noqa: SLF001- assert orb.calls.count(("reassert_z_order", None)) == 1- assert not any(call[0] == "show" for call in orb.calls)+ assert ("release_startup_gate", None) not in orb.calls+ assert bridge._boot_visibility_released is False # noqa: SLF001-async def test_voice_boot_status_not_ready_does_not_reassert_bar() -> None:- orb = _FakeOrb()+async def test_genuine_ready_can_release_after_degraded_ui_ready() -> None:+ orb = _FakeStartupGatedBar()bridge = OrbBusBridge( # type: ignore[arg-type]bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False)- # ready=False is emitted at warm-up start — it must not reveal the bar.- await bridge._on_voice_boot_status(VoiceBootStatus(ready=False)) # noqa: SLF001- assert ("show", "idle") not in orb.calls+ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="watchdog_timeout")+ )+ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="listening")+ )+ assert orb.calls.count(("release_startup_gate", None)) == 1-async def test_persistent_bar_reasserted_by_timeout_when_ready_never_comes() -> None:- """A voice-offline host still gets one bounded z-order reassert."""- orb = _FakeOrb()++async def test_cached_boot_bar_releases_when_reselected_after_ready() -> None:+ bar = _FakeStartupGatedBar()bridge = OrbBusBridge( # type: ignore[arg-type]- bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False+ bus=_FakeBus(), orb=bar, idle_animations_enabled=False, hide_on_idle=False)+ other_surface = _FakeOrb()- await bridge.reassert_persistent_bar_when_voice_ready(timeout_s=0.05)+ # The user hides the bar during warm-up. Ready therefore lands while another+ # surface is current and cannot release the cached boot bar yet.+ bridge.set_surface(other_surface)+ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="listening")+ )+ assert bar.startup_gated is True- assert ("show", "idle") in orb.calls+ bridge.set_surface(bar)+ assert bar.startup_gated is False+ assert bar.calls.count(("release_startup_gate", None)) == 1-async def test_non_persistent_surface_not_reasserted_on_voice_ready() -> None:- """A non-persistent bar / the mascot (hide_on_idle=True) is hidden at idle- by design — it pops on a real session. The boot reassert must leave it- untouched."""- orb = _FakeOrb()++async def test_non_persistent_bar_gate_releases_without_idle_show() -> None:+ orb = _FakeStartupGatedBar()bridge = OrbBusBridge( # type: ignore[arg-type]bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=True)- await bridge._on_voice_boot_status(VoiceBootStatus(ready=True)) # noqa: SLF001- await bridge.reassert_persistent_bar_when_voice_ready(timeout_s=0.05)+ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="listening")+ )- assert ("show", "idle") not in orb.calls+ assert ("release_startup_gate", None) in orb.calls+ assert not any(call[0] in {"show", "reassert_z_order"} for call in orb.calls)-async def test_boot_reassert_is_idempotent_across_ready_and_timeout() -> None:+async def test_ungated_persistent_bar_uses_explicit_z_order_reassert() -> None:+ orb = _FakeBarWithExplicitReassert()+ bridge = OrbBusBridge( # type: ignore[arg-type]+ bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False+ )++ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="listening")+ )++ assert orb.calls.count(("reassert_z_order", None)) == 1+ assert not any(call[0] == "show" for call in orb.calls)+++async def test_plain_legacy_persistent_surface_reasserts_current_mode() -> None:orb = _FakeOrb()+ orb._mode = "listen"bridge = OrbBusBridge( # type: ignore[arg-type]bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False)- await bridge._on_voice_boot_status(VoiceBootStatus(ready=True)) # noqa: SLF001- await bridge.reassert_persistent_bar_when_voice_ready(timeout_s=1.0)- # A second invocation (e.g. a stray late call) must not show the bar twice.- await bridge.reassert_persistent_bar_when_voice_ready(timeout_s=0.05)+ await bridge._on_voice_boot_status( # noqa: SLF001+ VoiceBootStatus(ready=True, detail="listening")+ )- assert orb.calls.count(("show", "idle")) == 1+ assert orb.calls.count(("show", "listen")) == 1@pytest.mark.parametrize("state", ["ERROR", "PAUSED"])diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.pyindex 5219d1d788..7705d6965a 100644--- a/ui/orb/bus_bridge.py+++ b/ui/orb/bus_bridge.py@@ -215,18 +215,12 @@ class OrbBusBridge:# drives _on_state without publishing VoiceSession events (and the# very first session before any end-event) behaves exactly as before.self._suppress_show_until_session: bool = False- # Boot z-order re-lift latch. The persistent bar is visible from- # boot (the overlay maps its window immediately — see- # DesktopApp._build_overlay_surface), so this is NO LONGER a visibility- # gate. Once voice is ready,- # ``reassert_persistent_bar_when_voice_ready`` re-asserts the bar's- # topmost after the main window + tray have finished mapping.- # ``_boot_reassert_done`` makes the re-lift idempotent across the ready- # signal and the fallback timeout. asyncio.Event() is loop-agnostic at- # construction (Py3.10+ dropped the loop param; project minimum is- # 3.11), so it is safe to build off the running loop.- self._voice_ready_event = asyncio.Event()- self._boot_reassert_done: bool = False+ # The boot-created Jarvis Bar is fully initialized but withdrawn. This+ # latch is released directly by the first genuine VoiceBootStatus ready+ # event; there is deliberately no timeout reveal because a visible bar is+ # the product's promise that the user can speak now.+ self._voice_usable: bool = False+ self._boot_visibility_released: bool = False# Backend asyncio loop the bridge's bus handlers run on. The Tk gesture# callbacks (_publish_mute_toggle / _publish_show_window /# _publish_visible_feedback) fire on the overlay's *Tk thread*, which has@@ -298,8 +292,8 @@ class OrbBusBridge:self._bus.subscribe(ResponseGenerated, self._on_response_generated)self._bus.subscribe(JarvisAgentBackgroundCompleted, self._on_background_completed)self._bus.subscribe(AudioOutFirst, self._on_audio_out_first)- # Boot z-order re-lift: once the speech pipeline signals voice is- # ready, re-assert the (already-visible) persistent bar's topmost.+ # Boot visibility gate: a genuine voice-ready signal releases the+ # hidden Jarvis Bar. Degraded UI-only ready signals do not.self._bus.subscribe(VoiceBootStatus, self._on_voice_boot_status)# Authoritative mute mirror: the pipeline owns the global voice-mute# flag and broadcasts VoiceMuteChanged whenever it flips (from this@@ -570,56 +564,46 @@ class OrbBusBridge:self._suppress_show_until_session = Trueasync def _on_voice_boot_status(self, event: VoiceBootStatus) -> None:- """Track the speech-pipeline boot readiness.+ """Release the Jarvis Bar only when voice is genuinely usable.- ``ready=True`` (emitted once Phase A of warm-up is live — audio + VAD +- wake + STT + TTS client) releases the latch so the persistent bar's- topmost z-order is re-asserted (the bar is already visible from boot).- ``ready=False`` (warm-up start) is ignored.+ The normal ``ready=True`` event is emitted after wake + VAD + TTS are+ initialized. ``voice_unavailable`` and ``watchdog_timeout`` are degraded+ web-UI escape hatches, not permission to advertise a working microphone.+ ``ready=False`` (warm-up start) leaves the gate closed."""- if event.ready:- self._voice_ready_event.set()-- async def reassert_persistent_bar_when_voice_ready(- self, *, timeout_s: float = 30.0- ) -> None:- """Re-assert the already-visible persistent bar after desktop boot.-- The bar maps immediately and does not wait for voice readiness. This- bounded task only re-pins its current mode/topmost state after later boot- windows have mapped. A non-persistent bar or mascot remains untouched.- """- reason = "timeout-fallback"- try:- await asyncio.wait_for(self._voice_ready_event.wait(), timeout_s)- reason = "voice-ready"- except TimeoutError:- pass- self._reassert_persistent_bar(reason)-- def _reassert_persistent_bar(self, reason: str) -> None:- """Re-pin the persistent bar's z-order exactly once."""- if self._boot_reassert_done:+ if not event.voice_usable:return- self._boot_reassert_done = True- if self._hide_on_idle:- # Non-persistent bar / mascot: stays hidden until a voice session.+ self._voice_usable = True+ self._release_bar_startup_gate(event.detail or "voice-ready")++ def _release_bar_startup_gate(self, reason: str) -> None:+ """Release a boot-gated bar and repair legacy visible surfaces once."""+ if self._boot_visibility_released:returntry:- reassert = getattr(self._orb, "reassert_z_order", None)- if callable(reassert):- reassert()- else:- # Compatibility floor for alternate and test surfaces. Only the- # Jarvis Bar owns the layered native window and implements the- # explicit style-safe z-order operation.- mode = str(getattr(self._orb, "_mode", "idle") or "idle")- self._orb.show(mode)+ release = getattr(self._orb, "release_startup_gate", None)+ was_gated = bool(release()) if callable(release) else False++ # A non-persistent bar needs its gate released too, but remains+ # withdrawn while idle. Mascot/Null surfaces expose no gate and stay+ # untouched. An already-visible legacy bar gets the existing safe+ # z-order repair instead.+ if not self._hide_on_idle and not was_gated:+ reassert = getattr(self._orb, "reassert_z_order", None)+ if callable(reassert):+ reassert()+ else:+ mode = str(getattr(self._orb, "_mode", "idle") or "idle")+ self._orb.show(mode)+ self._boot_visibility_released = Truelog.info(- "Persistent overlay z-order reasserted after boot (%s).", reason+ "Overlay startup visibility released after voice became usable (%s).",+ reason,)except Exception: # noqa: BLE001- log.debug("persistent bar boot reassert failed", exc_info=True)+ # Leave the latch open to a later genuine readiness event instead of+ # converting a transient surface error into a permanent hidden bar.+ log.debug("overlay startup visibility release failed", exc_info=True)async def _on_state(self, event: SystemStateChanged) -> None:# Lazily pin the backend loop (idempotent) so Tk-thread gestures can@@ -1025,6 +1009,11 @@ class OrbBusBridge:The caller tears the old surface down afterwards."""self._orb = surface+ # Visibility release is per surface, not merely per bridge. A user can+ # switch to "none" during warm-up and back to the cached boot bar after+ # ready; that original bar must then have its still-active gate released+ # without waiting for another VoiceBootStatus event.+ self._boot_visibility_released = Falsesetter = getattr(surface, "set_on_mute_toggle", None)if callable(setter):setter(self._publish_mute_toggle)@@ -1034,4 +1023,6 @@ class OrbBusBridge:show_window_setter = getattr(surface, "set_on_show_window", None)if callable(show_window_setter):show_window_setter(self._publish_show_window)+ if self._voice_usable:+ self._release_bar_startup_gate("voice-ready surface swap")log.info("OrbBridge surface swapped (last_state=%s)", self._last_state)