Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(voice): persistent realtime sessions, voice-mode badge, scrub-gate + recorder updates
Ruben Lütkeecd48079290e
diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex 75e18d770d..0f89334b06 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -25,7 +25,7 @@ from jarvis.sessions.constants import (HANGUP_REALTIME_FALLBACK,HANGUP_WS_CLOSED,)-from jarvis.ui.web.missions_auth import validate_token+from jarvis.ui.web.surface_security import credentials_validlog = logging.getLogger("jarvis.browser_voice.route")@@ -62,15 +62,14 @@ def _resolve_language(cfg: Any) -> str:def _browser_voice_authorized(ws: WebSocket) -> bool:- """Apply the shared mission-token policy to the browser voice socket.+ """Apply the shared cookie/Bearer policy as route-level defense in depth.A peer address is not an authentication boundary: a hostile webpage canconnect directly to a localhost WebSocket and still appear loopback to theserver. Every client therefore needs a registered token before atool-capable voice session is constructed."""- token = str(ws.query_params.get("token", "") or "")- return validate_token(token)+ return credentials_valid(ws.scope)def _json_commits_semantic_turn(message: dict[str, Any]) -> bool:diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pyindex eb68ee81ce..748f5f21ab 100644--- a/jarvis/plugins/realtime/gemini_live.py+++ b/jarvis/plugins/realtime/gemini_live.py@@ -305,6 +305,7 @@ class GeminiLiveProvider:input_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATEcredential_candidates = (+ ("realtime_gemini_api_key", "JARVIS_REALTIME_GEMINI_API_KEY"),("gemini_api_key", "GEMINI_API_KEY"),("google_aistudio_api_key", "GOOGLE_AIStudio_API_KEY"),("google_api_key", "GOOGLE_API_KEY"),diff --git a/jarvis/plugins/realtime/grok_realtime.py b/jarvis/plugins/realtime/grok_realtime.pyindex 7370163a04..9e3d1d4535 100644--- a/jarvis/plugins/realtime/grok_realtime.py+++ b/jarvis/plugins/realtime/grok_realtime.py@@ -26,7 +26,7 @@ _OUTPUT_RATE = 24_000def _grok_session_payload(cfg: Any) -> dict[str, Any]:"""Return xAI's OpenAI-compatible realtime session configuration."""payload = _session_payload(cfg)- payload["audio"]["input"]["transcription"] = {"model": "grok-transcribe"}+ payload["audio"]["input"]["transcription"]["model"] = "grok-transcribe"return payload@@ -38,6 +38,7 @@ class GrokRealtimeProvider:input_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATEcredential_candidates = (+ ("realtime_grok_api_key", "JARVIS_REALTIME_GROK_API_KEY"),("grok_api_key", "GROK_API_KEY"),("xai_api_key", "XAI_API_KEY"),)@@ -94,4 +95,3 @@ class GrokRealtimeProvider:await session.close()raisereturn session-diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex f679cd7b66..4bbb01c1a0 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -106,6 +106,10 @@ def _session_payload(cfg: Any) -> dict[str, Any]:invalid. PCM input and output are both explicitly declared as 24 kHz."""transcription: dict[str, Any] = {"model": "gpt-4o-mini-transcribe"}+ input_language = str(getattr(cfg, "input_language", "auto") or "auto")+ input_language = input_language.strip().lower().replace("_", "-").split("-", 1)[0]+ if input_language in {"de", "en", "es"}:+ transcription["language"] = input_languageturn_detection = str(getattr(cfg, "turn_detection", "server_vad") or "server_vad")if turn_detection not in {"server_vad", "semantic_vad"}:@@ -525,7 +529,10 @@ class OpenAIRealtimeProvider:supports_realtime = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATE- credential_candidates = (("openai_api_key", "OPENAI_API_KEY"),)+ credential_candidates = (+ ("realtime_openai_api_key", "JARVIS_REALTIME_OPENAI_API_KEY"),+ ("openai_api_key", "OPENAI_API_KEY"),+ )def __init__(self, *, api_key: str | None = None) -> None:self._api_key = (api_key or "").strip()diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.pyindex 63054cb8e8..5babc834cb 100644--- a/jarvis/realtime/protocol.py+++ b/jarvis/realtime/protocol.py@@ -51,7 +51,8 @@ class RealtimeSessionConfig:"""Everything a provider needs to open one duplex session."""instructions: str = ""- language: str = "en" # bare de/en/es (resolved once, upstream)+ language: str = "en" # output: bare de/en/es, resolved upstream+ input_language: str = "auto" # recognition: auto or bare de/en/eslanguage_is_pinned: bool = False # explicit reply-language preferencemodel: str = "" # provider model id ("" -> the adapter's# hardcoded default; no regression)diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.pyindex 0c07b85860..9db8159120 100644--- a/jarvis/realtime/scrub_gate.py+++ b/jarvis/realtime/scrub_gate.py@@ -15,19 +15,31 @@ from jarvis.core.protocols import AudioChunk_HARD_LEAK_ACTIONS = frozenset({+ "removed_tool_json","replaced_stacktrace","replaced_raw_repr","replaced_shell_command",- "replaced_with_fallback_residue",})_RESIDUE_ACTION = "replaced_with_fallback_residue"-_STREAM_SAFE_RESIDUE_ACTIONS = frozenset(+_NON_BLOCKING_SCRUB_ACTIONS = frozenset({+ "removed_anrede_drift", # i18n-allow: established telemetry action-name identifier (ADR-0010), not prose+ "removed_background_action_narration","removed_em_dash","removed_engineering_jargon",+ "removed_filler_opener",+ "removed_self_reference",+ "removed_source_artifacts",+ "rephrased_echo",+ "spelled_out_numbers",+ "stripped_end_signal",+ "stripped_markdown",})+_KNOWN_SCRUB_ACTIONS = (+ _HARD_LEAK_ACTIONS | _NON_BLOCKING_SCRUB_ACTIONS | {_RESIDUE_ACTION}+)_TRANSCRIPT_TAIL_MAX_CHARS = 4_096@@ -97,6 +109,7 @@ class ScrubHoldGate:# utterance is not available yet, so this benign residue neither# authorizes buffered audio nor aborts the response. The next# meaningful delta decides.+ self._cleared = Falsereturn textself._cleared = Trueif _is_stream_safe_residue(result):@@ -210,12 +223,20 @@ def _is_stream_safe_residue(result: ScrubResult) -> bool:result.fallback_usedand _RESIDUE_ACTION in actionsand residue_sources- and residue_sources <= _STREAM_SAFE_RESIDUE_ACTIONS+ and residue_sources <= _NON_BLOCKING_SCRUB_ACTIONS)def _is_hard_scrub_result(result: ScrubResult) -> bool:- """Classify leaks without treating isolated streaming punctuation as data."""+ """Block only real or unclassified leaks, never presentation residue."""+ actions = set(result.actions)+ if actions - _KNOWN_SCRUB_ACTIONS:+ # Every new scrub action must be classified explicitly. This preserves+ # fail-closed security without conflating known style transforms with+ # machine-data leaks.+ return True+ if _HARD_LEAK_ACTIONS & actions:+ return Trueif _is_stream_safe_residue(result):return False- return bool(result.fallback_used or (_HARD_LEAK_ACTIONS & set(result.actions)))+ return bool(result.fallback_used)diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex f3f70d994d..2a3edc6d14 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -23,7 +23,7 @@ from jarvis.brain.output_filter import scrub_for_voicefrom jarvis.brain.turn_planner import TurnPlan, plan_turnfrom jarvis.core.protocols import AudioChunk, BrainMessagefrom jarvis.core.redact import safe_preview-from jarvis.core.turn_language import resolve_output_language+from jarvis.core.turn_language import normalize_language_tag, resolve_output_languagefrom jarvis.realtime.audio import StreamingPcm16Resamplerfrom jarvis.realtime.protocol import RealtimeSessionConfigfrom jarvis.realtime.scrub_gate import ScrubHoldGate@@ -343,6 +343,7 @@ _TOOL_ROLE_DIRECTIVE = (def _session_instructions(language: str,*,+ input_language: str = "auto",provider: str = "",model: str = "",language_is_pinned: bool = True,@@ -352,6 +353,19 @@ def _session_instructions(persona = load_effective_persona_prompt().strip()language_name = _LANGUAGE_NAMES.get(language, "the user's language")+ input_language_name = _LANGUAGE_NAMES.get(input_language)+ if input_language_name:+ input_directive = (+ f"Interpret the user's spoken audio as {input_language_name}. "+ "Do not infer a different input language from the persona, prior "+ "turns, or the reply language."+ )+ else:+ input_directive = (+ "Detect the language of every substantive spoken turn from its "+ "current audio. Do not assume the input language from the persona "+ "or from an earlier turn."+ )if language_is_pinned:language_directive = f"Reply only in {language_name} for this turn."else:@@ -364,6 +378,7 @@ def _session_instructions(persona,tool_directive,_REALTIME_SAFETY_APPENDIX,+ input_directive,("Runtime identity: this voice session is using the Realtime engine"+ (f", provider {provider}" if provider else "")@@ -446,6 +461,12 @@ class RealtimeVoiceSession:self._stt_language = getattr(getattr(self._config, "stt", None), "language", "unknown")+ normalized_input_language = normalize_language_tag(self._stt_language)+ self._input_language = (+ normalized_input_language+ if normalized_input_language in _LANGUAGE_NAMES+ else "auto"+ )self._language = self._resolve_lang(text="")self._brain = brainmode = str(@@ -671,12 +692,14 @@ class RealtimeVoiceSession:session_config = RealtimeSessionConfig(instructions=_session_instructions(self._language,+ input_language=self._input_language,provider=str(getattr(provider, "name", "") or ""),model=model,language_is_pinned=self._language_is_pinned,tool_directive=self._tool_directive(),),language=self._language,+ input_language=self._input_language,language_is_pinned=self._language_is_pinned,model=model,voice=voice,@@ -1001,6 +1024,7 @@ class RealtimeVoiceSession:update_kwargs: dict[str, Any] = {"instructions": _session_instructions(new_language,+ input_language=self._input_language,provider=self.active_provider,model=self._active_model,language_is_pinned=True,diff --git a/jarvis/sessions/constants.py b/jarvis/sessions/constants.pyindex 2235933edb..c6e6b0c812 100644--- a/jarvis/sessions/constants.py+++ b/jarvis/sessions/constants.py@@ -81,6 +81,26 @@ session row whose recorder has not finalized yet (still running). Orderis intentionally stable for tests that assert against``typing.get_args(HangupReason)``."""+# ----------------------------------------------------------------------+# Voice-session engine mode+# ----------------------------------------------------------------------++VOICE_MODE_UNKNOWN: Final[str] = "unknown"+"""No persisted runtime evidence identifies the session's voice engine."""++VOICE_MODE_PIPELINE: Final[str] = "pipeline"+"""Classic STT -> Brain -> TTS voice pipeline."""++VOICE_MODE_REALTIME: Final[str] = "realtime"+"""Duplex realtime-provider voice session."""++VOICE_MODES: Final[tuple[str, ...]] = (+ VOICE_MODE_UNKNOWN,+ VOICE_MODE_PIPELINE,+ VOICE_MODE_REALTIME,+)+"""Canonical voice-mode values. Persistence remains open to future strings."""+# ----------------------------------------------------------------------# Spoken-track kinds (SpeechSpoken.spoken_kind)# ----------------------------------------------------------------------@@ -191,4 +211,8 @@ __all__ = ["SPOKEN_KIND_UNAVAILABLE","SPOKEN_KIND_WITHHELD","SPOKEN_KINDS",+ "VOICE_MODES",+ "VOICE_MODE_PIPELINE",+ "VOICE_MODE_REALTIME",+ "VOICE_MODE_UNKNOWN",]diff --git a/jarvis/sessions/models.py b/jarvis/sessions/models.pyindex 485d771c7f..89f509394d 100644--- a/jarvis/sessions/models.py+++ b/jarvis/sessions/models.py@@ -19,7 +19,7 @@ from typing import TypeAliasfrom pydantic import BaseModel, ConfigDict, Field-from jarvis.sessions.constants import SPOKEN_KINDS+from jarvis.sessions.constants import SPOKEN_KINDS, VOICE_MODE_UNKNOWN, VOICE_MODES# BUG-008 (three episodes 2026-05-03 / -05 / -10): the Pydantic ``Literal``# broke the list-sessions API every time the pipeline introduced a new@@ -68,7 +68,14 @@ KNOWN_VOICE_TIERS: frozenset[str] = frozenset("""Routing tier as in CLAUDE.md `Brain-Routing` and `Router-Discipline`."""VoiceTier: TypeAlias = str-"""Deliberately ``str`` instead of ``Literal`` — see ``KNOWN_VOICE_TIERS``."""+"""Open string so a future routing tier cannot break session APIs."""+++KNOWN_VOICE_MODES: frozenset[str] = frozenset(VOICE_MODES)+"""Canonical session engine modes understood by the current UI."""++VoiceMode: TypeAlias = str+"""Open string so a future runtime value cannot break session APIs."""KNOWN_SPOKEN_KINDS: frozenset[str] = frozenset(SPOKEN_KINDS)@@ -141,6 +148,7 @@ class VoiceSessionRow(BaseModel):providers_used: list[str] = Field(default_factory=list)language: str = "de"wake_keyword: str = ""+ voice_mode: VoiceMode = VOICE_MODE_UNKNOWNclass SessionListItem(VoiceSessionRow):@@ -171,9 +179,11 @@ __all__ = ["KNOWN_HANGUP_REASONS","KNOWN_SPOKEN_KINDS","KNOWN_VOICE_TIERS",+ "KNOWN_VOICE_MODES","SessionDetail","SessionListItem","VoiceEventRow",+ "VoiceMode","VoiceSessionRow","VoiceTier","VoiceTurnRow",diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.pyindex 829b4b8286..6d9665bda6 100644--- a/jarvis/sessions/recorder.py+++ b/jarvis/sessions/recorder.py@@ -50,6 +50,7 @@ from jarvis.core.events import (JarvisAgentTaskCompleted,JarvisAgentTaskStarted,ListeningStarted,+ RealtimeSessionReady,ResponseGenerated,SpeechSpoken,SystemStateChanged,@@ -64,7 +65,12 @@ from jarvis.core.events import (WakeWordDetected,)-from .constants import SPOKEN_KIND_COMPLETION, SPOKEN_KIND_SUBAGENT+from .constants import (+ SPOKEN_KIND_COMPLETION,+ SPOKEN_KIND_SUBAGENT,+ VOICE_MODE_PIPELINE,+ VOICE_MODE_REALTIME,+)from .store import SessionStorelog = logging.getLogger(__name__)@@ -253,7 +259,18 @@ class SessionRecorder:elif isinstance(event, WakeWordDetected):# Wake in multi-turn mode — counts as a turn boundary.self._ensure_turn_open(event.timestamp_ns // 1_000_000)+ elif isinstance(event, RealtimeSessionReady):+ if event.session_id != self._state.session_id:+ return+ self._on_realtime_ready(event)elif isinstance(event, ListeningStarted):+ # This event is emitted only after the classic STT -> Brain -> TTS+ # path has actually begun listening. It therefore also captures a+ # fallback that follows a successful realtime handshake.+ self._store.update_session_voice_mode(+ session_id=self._state.session_id,+ voice_mode=VOICE_MODE_PIPELINE,+ )self._ensure_turn_open(event.timestamp_ns // 1_000_000)elif isinstance(event, TranscriptFinal):self._on_transcript_final(event)@@ -314,6 +331,15 @@ class SessionRecorder:)log.info("SessionRecorder: session started id=%s", event.session_id)+ def _on_realtime_ready(self, event: RealtimeSessionReady) -> None:+ """Record only an accepted provider handshake as Realtime evidence."""+ if self._state is None:+ return+ self._store.update_session_voice_mode(+ session_id=self._state.session_id,+ voice_mode=VOICE_MODE_REALTIME,+ )+def _on_session_ended(self, event: VoiceSessionEnded) -> None:if self._state is None:returndiff --git a/jarvis/sessions/schema.sql b/jarvis/sessions/schema.sqlindex 7a6c3b3824..1e6186a267 100644--- a/jarvis/sessions/schema.sql+++ b/jarvis/sessions/schema.sql@@ -20,7 +20,8 @@ CREATE TABLE IF NOT EXISTS voice_sessions (total_tokens_out INTEGER NOT NULL DEFAULT 0,providers_used TEXT NOT NULL DEFAULT '[]', -- JSON array of distinct provider nameslanguage TEXT NOT NULL DEFAULT 'de',- wake_keyword TEXT NOT NULL DEFAULT ''+ wake_keyword TEXT NOT NULL DEFAULT '',+ voice_mode TEXT NOT NULL DEFAULT 'unknown' -- unknown|pipeline|realtime; open string for forward compatibility);CREATE INDEX IF NOT EXISTS idx_sessions_started ON voice_sessions(started_ms DESC);diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.pyindex 70baf2cebe..eb0cb353ed 100644--- a/jarvis/sessions/store.py+++ b/jarvis/sessions/store.py@@ -28,6 +28,7 @@ from typing import Anyfrom pydantic import ValidationError+from .constants import VOICE_MODE_UNKNOWNfrom .models import SessionListItem, VoiceEventRow, VoiceSessionRow, VoiceTurnRowlog = logging.getLogger(__name__)@@ -77,6 +78,47 @@ class SessionStore:Pattern adopted from ``jarvis/missions/event_store.py``."""assert self._conn is not None+ session_columns = {+ str(row["name"])+ for row in self._conn.execute("PRAGMA table_info(voice_sessions)").fetchall()+ }+ if "voice_mode" not in session_columns:+ self._conn.execute(+ "ALTER TABLE voice_sessions "+ "ADD COLUMN voice_mode TEXT NOT NULL DEFAULT 'unknown'"+ )+ log.info("SessionStore migration: added voice_sessions.voice_mode")++ # Backfill only unresolved rows. The latest explicit runtime event wins,+ # which makes a ListeningStarted after a successful realtime handshake+ # a truthful classic-pipeline fallback. Older recorder versions did not+ # always persist RealtimeSessionReady, so a realtime turn tier is the+ # final evidence source. Everything else stays honestly unknown.+ self._conn.execute(+ """+ UPDATE voice_sessions AS s+ SET voice_mode = COALESCE(+ (+ SELECT CASE e.kind+ WHEN 'RealtimeSessionReady' THEN 'realtime'+ WHEN 'ListeningStarted' THEN 'pipeline'+ END+ FROM voice_events AS e+ WHERE e.session_id = s.id+ AND e.kind IN ('RealtimeSessionReady', 'ListeningStarted')+ ORDER BY e.seq DESC+ LIMIT 1+ ),+ CASE WHEN EXISTS (+ SELECT 1+ FROM voice_turns AS t+ WHERE t.session_id = s.id AND t.tier = 'realtime'+ ) THEN 'realtime' ELSE 'unknown' END+ )+ WHERE voice_mode IS NULL OR voice_mode IN ('', 'unknown')+ """+ )+cur = self._conn.execute("PRAGMA table_info(voice_turns)")existing = {str(row["name"]) for row in cur.fetchall()}if "think_ms" not in existing:@@ -117,23 +159,43 @@ class SessionStore:started_ms: int,wake_keyword: str = "",language: str = "de",+ voice_mode: str = VOICE_MODE_UNKNOWN,) -> None:"""Create, or (on a recorder re-init) idempotently re-upsert.- ON CONFLICT: ``started_ms`` is preserved (the first wake wins),- only ``wake_keyword``/``language`` may get overwritten.+ ON CONFLICT: ``started_ms`` is preserved (the first wake wins).+ Identity metadata may be refreshed, but an unresolved default mode+ never overwrites runtime evidence already recorded for the session."""with self._lock:self._c.execute("""INSERT INTO voice_sessions- (id, started_ms, wake_keyword, language)- VALUES (?, ?, ?, ?)+ (id, started_ms, wake_keyword, language, voice_mode)+ VALUES (?, ?, ?, ?, ?)ON CONFLICT(id) DO UPDATE SETwake_keyword = excluded.wake_keyword,- language = excluded.language+ language = excluded.language,+ voice_mode = CASE+ WHEN excluded.voice_mode != 'unknown'+ THEN excluded.voice_mode+ ELSE voice_sessions.voice_mode+ END""",- (session_id, started_ms, wake_keyword, language),+ (session_id, started_ms, wake_keyword, language, voice_mode),+ )++ def update_session_voice_mode(self, *, session_id: str, voice_mode: str) -> None:+ """Persist runtime evidence for the effective voice engine.++ The column deliberately accepts future strings. Current recorder callers+ use only the canonical values from ``jarvis.sessions.constants``.+ """+ normalized = str(voice_mode or VOICE_MODE_UNKNOWN)+ with self._lock:+ self._c.execute(+ "UPDATE voice_sessions SET voice_mode = ? WHERE id = ?",+ (normalized, session_id),)def finalize_session(@@ -288,7 +350,12 @@ class SessionStore:# --- Read-API ------------------------------------------------------ def list_sessions(self, *, limit: int = 100) -> list[SessionListItem]:+ def list_sessions(+ self,+ *,+ limit: int = 100,+ offset: int = 0,+ ) -> list[SessionListItem]:"""Sessions by started_ms desc — newest first.``preview`` is the first user utterance (the first turn row with@@ -306,9 +373,9 @@ class SessionStore:LIMIT 1) AS previewFROM voice_sessions sORDER BY s.started_ms DESC- LIMIT ?+ LIMIT ? OFFSET ?""",- (limit,),+ (limit, max(0, int(offset))),)rows = cur.fetchall()# Per-row validation in a try/except: a single invalid row (e.g.@@ -337,6 +404,7 @@ class SessionStore:providers_used=json.loads(r["providers_used"] or "[]"),language=r["language"],wake_keyword=r["wake_keyword"],+ voice_mode=r["voice_mode"] or VOICE_MODE_UNKNOWN,duration_s=duration_s,preview=_truncate(r["preview"] or "", 120),)@@ -570,6 +638,7 @@ def _row_to_session(r: sqlite3.Row) -> VoiceSessionRow:providers_used=json.loads(r["providers_used"] or "[]"),language=r["language"],wake_keyword=r["wake_keyword"],+ voice_mode=r["voice_mode"] or VOICE_MODE_UNKNOWN,)diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 94a9804d99..8e07f5174c 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -601,6 +601,7 @@ def _stt_retry_delay(exc: BaseException | None, attempt: int) -> float:_SESSION_START_BUFFER_MAX_BYTES = 16_000 * 2 * 30 # 30 s of mono PCM16+_REALTIME_POST_OUTPUT_ECHO_GUARD_S = 0.5def _feed_live_mic_level(chunk: AudioChunk) -> None:@@ -2703,6 +2704,17 @@ class SpeechPipeline:return "pause"return None+ def _capture_permission_allowed(self) -> bool:+ """Return the live local-capture gate without applying Jarvis mute."""+ gate = getattr(self, "_activation_gate", None)+ if gate is None:+ return True+ try:+ return bool(gate())+ except Exception as exc: # noqa: BLE001+ log.warning("Voice capture permission gate failed closed: %s", exc)+ return False+def _activation_allowed(self) -> bool:"""True when external UI/lifecycle state permits voice activation.@@ -2716,11 +2728,7 @@ class SpeechPipeline:"""if getattr(self, "_muted", False):return False- try:- return bool(self._activation_gate())- except Exception as exc: # noqa: BLE001- log.warning("Voice activation gate failed closed: %s", exc)- return False+ return self._capture_permission_allowed()@propertydef is_muted(self) -> bool:@@ -6080,8 +6088,21 @@ class SpeechPipeline:barge_detector = DesktopRealtimeBargeInDetector()turn_complete = asyncio.Event()speaking = False+ post_output_echo_guard_until = 0.0semantic_turn_committed = False+ def _close_output_segment(*, preserve_echo_tail: bool) -> None:+ """Keep half-duplex protection through physical speaker drain."""+ nonlocal post_output_echo_guard_until, speaking+ speaking = False+ if preserve_echo_tail:+ post_output_echo_guard_until = (+ time.monotonic() + _REALTIME_POST_OUTPUT_ECHO_GUARD_S+ )+ return+ post_output_echo_guard_until = 0.0+ barge_detector.stop_output()+async def _warm_barge_detector() -> None:try:await _run_voice_critical_thread(barge_detector.warmup)@@ -6097,9 +6118,11 @@ class SpeechPipeline:)async def _send_binary(pcm: bytes) -> None:+ nonlocal post_output_echo_guard_untilnonlocal semantic_turn_committed, speakingsemantic_turn_committed = Trueif not speaking:+ post_output_echo_guard_until = 0.0speaking = Truebarge_detector.start_output()await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)@@ -6143,25 +6166,25 @@ class SpeechPipeline:# delta starts a fresh SPEAKING segment through _send_binary.semantic_turn_committed = Trueawait playback.finish_turn()- speaking = False- barge_detector.stop_output()+ _close_output_segment(+ preserve_echo_tail=speaking,+ )await self._set_turn_state(TurnTakingState.PROCESSING)elif kind == "tts_cancel":- speaking = False- barge_detector.stop_output()+ _close_output_segment(preserve_echo_tail=False)await playback.cancel()await self._set_turn_state(TurnTakingState.LISTENING)elif kind == "hangup":semantic_turn_committed = True- speaking = False- barge_detector.stop_output()+ _close_output_segment(preserve_echo_tail=False)await playback.cancel()elif kind == "turn_complete":semantic_turn_committed = Trueawait playback.finish_turn()interrupted_during_drain = not speaking- speaking = False- barge_detector.stop_output()+ _close_output_segment(+ preserve_echo_tail=not interrupted_during_drain,+ )await self._set_turn_state(TurnTakingState.LISTENING)if (not self._continue_listening_after_response@@ -6205,8 +6228,9 @@ class SpeechPipeline:exc,)finally:- speaking = False- barge_detector.stop_output()+ _close_output_segment(+ preserve_echo_tail=speaking,+ )await self._set_turn_state(TurnTakingState.LISTENING)elif kind == "provider_error":log.warning("Realtime desktop status: %s", message)@@ -6233,7 +6257,7 @@ class SpeechPipeline:try:async with self._session_input_source(input_buffer) as input_chunks:async def _send_microphone() -> None:- nonlocal preroll_bytes+ nonlocal post_output_echo_guard_until, preroll_bytesasync for chunk in self._session_input_stream(input_chunks):if not provider_ready.is_set():if (@@ -6252,18 +6276,26 @@ class SpeechPipeline:buffered = preroll.popleft()preroll_bytes = max(0, preroll_bytes - len(buffered))await session.handle_audio_frame(buffered)- if speaking:+ echo_guard_active = bool(+ speaking+ or time.monotonic() < post_output_echo_guard_until+ )+ if echo_guard_active:interrupted_pcm = barge_detector.feed(chunk.pcm)if interrupted_pcm is None:# Provider half-duplex remains intact: speaker- # echo is inspected locally but never uploaded.+ # echo, including the hardware playback tail,+ # is inspected locally but never uploaded.continuelog.info("Realtime desktop barge-in confirmed by local CPU VAD")+ post_output_echo_guard_until = 0.0await session.handle_control({"type": "barge_in"})await session.handle_audio_frame(interrupted_pcm)continue+ if bool(getattr(barge_detector, "active", False)):+ barge_detector.stop_output()await session.handle_audio_frame(chunk.pcm)# A shared capture buffer already owns and meters production@@ -6609,7 +6641,11 @@ class SpeechPipeline:Lets the UI hide the mic button on a headless host with no capturedevice (cloud-first: a missing capability is a clean no-op, AD-OE6)."""- return self._utterance_stt is not None and self._input_device != "none"+ return (+ self._utterance_stt is not None+ and self._input_device != "none"+ and self._capture_permission_allowed()+ )def start_dictation(self) -> bool:"""Begin a transcribe-only dictation session (idempotent-safe).@@ -6622,6 +6658,9 @@ class SpeechPipeline:This NEVER routes to the brain: it spawns ``_dictation_session`` whichonly publishes ``DictationTranscript`` events."""+ if not self._capture_permission_allowed():+ log.info("start_dictation ignored: microphone access is not ready.")+ return Falseif self._utterance_stt is None:log.info("start_dictation ignored: no STT provider.")return Falsediff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.pyindex 21b9306f76..24a0555ad6 100644--- a/jarvis/trigger/backends/pynput.py+++ b/jarvis/trigger/backends/pynput.py@@ -41,6 +41,15 @@ import threadinglog = logging.getLogger(__name__)++def _macos_hotkey_permissions_granted() -> bool:+ """Probe both native grants required by a macOS keyboard event tap."""+ from jarvis.platform.permissions import ( # noqa: PLC0415+ get_system_permission_port,+ )++ return get_system_permission_port().runtime_feature_ready("global_hotkeys")+# global-hotkeys modifier token -> canonical pynput modifier name (the attribute# on ``pynput.keyboard.Key``). Anything not here is a literal key (e.g. "j") or# an F-key (e.g. "f1", which is also a ``Key`` attribute).@@ -97,6 +106,7 @@ class PynputBackend:self._incremented = False# The live set of canonical tokens currently held down.self._held: set[str] = set()+ self._permission_check = lambda: Truedef register(self, bindings, on_event=None) -> None:"""Stash binding rows as token-set combos. Never raises (AD-6).@@ -148,6 +158,14 @@ class PynputBackend:def _reconcile(self) -> None:"""Fire press/release handlers on chord down/up transitions."""+ if not self._permission_check():+ # A grant can be revoked while the listener thread is alive. Clear+ # every partial chord and refuse the callback before it can activate+ # voice; a later re-grant starts from a clean key state.+ self._held.clear()+ for combo in self._combos:+ combo["down"] = False+ returnfor combo in self._combos:is_down = combo["tokens"].issubset(self._held)if is_down and not combo["down"]:@@ -172,7 +190,7 @@ class PynputBackend:except Exception as exc: # noqa: BLE001 — optional [desktop] extralog.warning("pynput unavailable (%s) — hotkeys disabled; voice still works "- "via wake word. Install the [desktop] extra to enable global "+ "via wake word. Install the [full] profile to enable global ""hotkeys.",exc,)@@ -181,29 +199,26 @@ class PynputBackend:if sys.platform == "darwin":# pynput's darwin backend creates a Quartz event tap on its own- # internal thread; without the Accessibility grant that native+ # internal thread; without Accessibility and Input Monitoring that native# init is useless at best and a process-level abort at worst# (uncatchable, BUG-058 class). Preflight the non-prompting- # AXIsProcessTrusted probe and fail CLOSED (None = unverifiable- # -> treat as not granted) instead of touching pynput.- granted: bool | None = None+ # native preflights and fail CLOSED instead of touching pynput.+ granted = Falsetry:- from jarvis.platform.probes import ax_permission_granted-- granted = ax_permission_granted()+ granted = _macos_hotkey_permissions_granted()except Exception: # noqa: BLE001 — the probe must never crash the trigger- granted = None+ granted = Falseif granted is not True:log.warning("Global hotkeys disabled on macOS: the Accessibility "- "permission is %s. Grant it under System Settings > "- "Privacy & Security > Accessibility for the app you "- "launch Jarvis from, then restart Jarvis — voice still "+ "and Input Monitoring permissions are not both granted. "+ "Use Personal Jarvis > Settings > Permissions, then "+ "re-arm the shortcut or restart Jarvis — voice still ""works via the wake word.",- "not granted" if granted is False else "not verifiable",)self._listener = Nonereturn+ self._permission_check = _macos_hotkey_permissions_grantedtry:listener = keyboard.Listener(diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsxindex f3c6a7fbe8..c296f95c44 100644--- a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx@@ -32,10 +32,11 @@ import {usePreferredOpener,useSetPreferredOpener,} from "@/hooks/useOutputs";-import { useT } from "@/i18n";+import { useT, useUiLanguage } from "@/i18n";import { fetchSessionExport, openSessionWith, sessionExportUrl } from "./api";import { TurnCard } from "./TurnCard";+import { VoiceModeBadge } from "./VoiceModeBadge";import type {SessionDetail as SessionDetailModel,VoiceSpokenLine,@@ -57,6 +58,9 @@ interface Props {export function SessionDetail({ detail, loading, error }: Props) {const t = useT();+ const uiLanguage = useUiLanguage();+ const locale =+ uiLanguage === "de" ? "de-DE" : uiLanguage === "es" ? "es-ES" : "en-US";const pushToast = useEventStore((s) => s.pushToast);// Desktop shell? Then save straight to ~/Downloads (browser downloads are// silently dropped by pywebview); otherwise use the normal browser download.@@ -250,12 +254,15 @@ export function SessionDetail({ detail, loading, error }: Props) {<div className="shrink-0 border-b border-border bg-card/40 px-5 py-4 backdrop-blur"><div className="flex items-start justify-between gap-3"><div className="min-w-0">- <div className="font-display text-lg font-semibold">- {t("session_detail.title")}+ <div className="flex flex-wrap items-center gap-2.5">+ <div className="font-display text-lg font-semibold">+ {t("session_detail.title")}+ </div>+ <VoiceModeBadge mode={session.voice_mode} prominence="prominent" /></div><div className="font-mono text-xs text-muted-foreground">- {startedDt.toLocaleString("de")}- {endedDt && ` — ${endedDt.toLocaleTimeString("de")}`}+ {startedDt.toLocaleString(locale)}+ {endedDt && ` — ${endedDt.toLocaleTimeString(locale)}`}</div><div className="mt-2 flex flex-wrap items-center gap-1.5"><Badge variant="secondary">{session.turn_count} {t("session_detail.turns")}</Badge>diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsxindex c7962f5015..46bb82450e 100644--- a/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx@@ -15,6 +15,7 @@ import { translate, useT } from "@/i18n";import { cn } from "@/lib/utils";import type { SessionListItem } from "./types";+import { VoiceModeBadge } from "./VoiceModeBadge";interface Props {sessions: SessionListItem[];@@ -66,15 +67,18 @@ export function SessionList({ sessions, selectedId, onSelect, loading }: Props)<Mic className="h-3 w-3" />{formatRelative(s.started_ms)}</span>- {s.ended_ms === null ? (- <Badge variant="default" className="animate-pulse">- {t("sessions.running")}- </Badge>- ) : (- <Badge variant="secondary" className="text-[10px]">- {hangupLabel(s.hangup_reason)}- </Badge>- )}+ <span className="flex shrink-0 items-center gap-1">+ <VoiceModeBadge mode={s.voice_mode} />+ {s.ended_ms === null ? (+ <Badge variant="default" className="animate-pulse">+ {t("sessions.running")}+ </Badge>+ ) : (+ <Badge variant="secondary" className="text-[10px]">+ {hangupLabel(s.hangup_reason)}+ </Badge>+ )}+ </span></div><div className="line-clamp-2 text-foreground/90">{s.preview || (diff --git a/jarvis/ui/web/frontend/src/components/sessions/VoiceModeBadge.test.tsx b/jarvis/ui/web/frontend/src/components/sessions/VoiceModeBadge.test.tsxnew file mode 100644index 0000000000..a3ca0518d5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/sessions/VoiceModeBadge.test.tsx@@ -0,0 +1,142 @@+import { cleanup, render, screen, within } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { SessionDetail } from "./SessionDetail";+import { SessionList } from "./SessionList";+import type {+ SessionDetail as SessionDetailModel,+ SessionListItem,+ VoiceMode,+} from "./types";+import { VoiceModeBadge } from "./VoiceModeBadge";++const TRANSLATIONS: Record<string, string> = {+ "voice_mode.label": "Mode",+ "voice_mode.realtime": "Realtime",+ "voice_mode.pipeline": "Pipeline",+ "voice_mode.unknown": "Unknown",+ "session_detail.title": "Voice session",+ "session_detail.turns": "turns",+ "sessions.no_turns": "No turns",+ "session_detail.no_turns_suffix": " recorded.",+ "session_list.turns": "turns",+ "session_list.ago_prefix": "",+ "session_list.ago_suffix": "ago",+ "session_list.unit_sec": "s",+ "session_list.unit_min": "min",+ "session_list.unit_hour": "h",+ "session_list.hangup_hotkey": "Hotkey",+};++vi.mock("@/i18n", () => ({+ translate: (key: string) => TRANSLATIONS[key] ?? key,+ useT: () => (key: string) => TRANSLATIONS[key] ?? key,+ useUiLanguage: () => "en",+}));++vi.mock("@/hooks/useCapabilities", () => ({+ useCapabilities: () => ({+ data: { native_file_actions: false, platform: "linux" },+ }),+}));++vi.mock("@/hooks/useOutputs", () => ({+ useOpeners: () => ({ data: [], isLoading: false }),+ usePreferredOpener: () => ({ data: "" }),+ useSetPreferredOpener: () => ({ mutate: vi.fn() }),+}));++afterEach(cleanup);++function session(mode: VoiceMode, id = mode): SessionListItem {+ return {+ id,+ started_ms: Date.now() - 120_000,+ ended_ms: Date.now() - 60_000,+ hangup_reason: "hotkey",+ turn_count: 1,+ total_cost_usd: 0,+ total_tokens_in: 0,+ total_tokens_out: 0,+ providers_used: [],+ language: "en",+ wake_keyword: "Jarvis",+ voice_mode: mode,+ duration_s: 60,+ preview: `${mode} transcript`,+ };+}++function detail(mode: VoiceMode): SessionDetailModel {+ const { duration_s: _duration, preview: _preview, ...sessionRow } =+ session(mode);+ return { session: sessionRow, turns: [], events: [] };+}++describe("VoiceModeBadge", () => {+ it.each([+ ["realtime", "Realtime"],+ ["pipeline", "Pipeline"],+ ["unknown", "Unknown"],+ ] as const)("renders the %s mode with text and an icon", (mode, label) => {+ render(<VoiceModeBadge mode={mode} />);++ const badge = screen.getByLabelText(`Mode: ${label}`);+ expect(badge.getAttribute("data-voice-mode")).toBe(mode);+ expect(within(badge).getByText(label)).toBeTruthy();+ expect(badge.querySelector('svg[aria-hidden="true"]')).toBeTruthy();+ });++ it("degrades an unfamiliar API value to the neutral unknown presentation", () => {+ render(<VoiceModeBadge mode="future-mode" />);++ expect(screen.getByLabelText("Mode: Unknown").getAttribute("data-voice-mode")).toBe(+ "unknown",+ );+ });+});++describe("session mode locations", () => {+ it("shows a compact indicator in every session-list row", () => {+ render(+ <SessionList+ sessions={[+ session("realtime"),+ session("pipeline"),+ session("unknown"),+ ]}+ selectedId="realtime"+ onSelect={vi.fn()}+ loading={false}+ />,+ );++ for (const label of ["Realtime", "Pipeline", "Unknown"]) {+ const badge = screen.getByLabelText(`Mode: ${label}`);+ expect(badge.closest("button")).toBeTruthy();+ expect(within(badge).getByText(label)).toBeTruthy();+ }+ });++ it.each([+ ["realtime", "Realtime"],+ ["pipeline", "Pipeline"],+ ["unknown", "Unknown"],+ ] as const)(+ "shows a prominent labeled %s indicator in the detail header",+ (mode, label) => {+ render(+ <SessionDetail detail={detail(mode)} loading={false} error={null} />,+ );++ const titleRow = screen.getByText("Voice session").parentElement;+ expect(titleRow).toBeTruthy();+ const badge = within(titleRow as HTMLElement).getByLabelText(+ `Mode: ${label}`,+ );+ expect(within(badge).getByText("Mode")).toBeTruthy();+ expect(within(badge).getByText(label)).toBeTruthy();+ expect(badge.querySelector('svg[aria-hidden="true"]')).toBeTruthy();+ },+ );+});diff --git a/jarvis/ui/web/frontend/src/components/sessions/VoiceModeBadge.tsx b/jarvis/ui/web/frontend/src/components/sessions/VoiceModeBadge.tsxnew file mode 100644index 0000000000..ac5011c9f6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/sessions/VoiceModeBadge.tsx@@ -0,0 +1,68 @@+import { CircleHelp, Radio, Workflow } from "lucide-react";++import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++import type { KnownVoiceMode, VoiceMode } from "./types";++interface VoiceModeBadgeProps {+ mode: VoiceMode;+ prominence?: "compact" | "prominent";+ className?: string;+}++const MODE_STYLES: Record<KnownVoiceMode, string> = {+ realtime:+ "border-primary/70 bg-primary/20 text-primary shadow-[0_0_14px_hsl(var(--primary)/0.12)]",+ pipeline:+ "border-sky-500/50 bg-sky-500/15 text-sky-700 dark:text-sky-300",+ unknown: "border-border bg-muted/70 text-muted-foreground",+};++export function VoiceModeBadge({+ mode,+ prominence = "compact",+ className,+}: VoiceModeBadgeProps) {+ const t = useT();+ const knownMode: KnownVoiceMode =+ mode === "realtime"+ ? "realtime"+ : mode === "pipeline"+ ? "pipeline"+ : "unknown";+ const modeLabel = t(`voice_mode.${knownMode}`);+ const ModeIcon =+ knownMode === "realtime"+ ? Radio+ : knownMode === "pipeline"+ ? Workflow+ : CircleHelp;++ return (+ <span+ role="group"+ aria-label={`${t("voice_mode.label")}: ${modeLabel}`}+ data-voice-mode={knownMode}+ className={cn(+ "inline-flex shrink-0 items-center rounded-md border font-semibold",+ MODE_STYLES[knownMode],+ prominence === "prominent"+ ? "gap-2 px-2.5 py-1.5 text-xs"+ : "gap-1 px-1.5 py-0.5 text-[10px]",+ className,+ )}+ >+ {prominence === "prominent" && (+ <span className="text-[9px] font-bold uppercase tracking-[0.14em] opacity-75">+ {t("voice_mode.label")}+ </span>+ )}+ <ModeIcon+ aria-hidden="true"+ className={prominence === "prominent" ? "h-4 w-4" : "h-3 w-3"}+ />+ <span>{modeLabel}</span>+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/sessions/types.ts b/jarvis/ui/web/frontend/src/components/sessions/types.tsindex 3fddb1c6a4..50a99e86b1 100644--- a/jarvis/ui/web/frontend/src/components/sessions/types.ts+++ b/jarvis/ui/web/frontend/src/components/sessions/types.ts@@ -34,6 +34,11 @@ export const KNOWN_VOICE_TIERS = [export type VoiceTier = string;+export const KNOWN_VOICE_MODES = ["unknown", "pipeline", "realtime"] as const;++export type KnownVoiceMode = (typeof KNOWN_VOICE_MODES)[number];+export type VoiceMode = KnownVoiceMode | (string & Record<never, never>);+// Mirror of jarvis/sessions/constants.py SPOKEN_KINDS. Every phrase Jarvis// VOICES that is not the brain's normal reply is recorded as a SpeechSpoken// event tagged with one of these. Parity: tests/unit/sessions/@@ -119,6 +124,7 @@ export interface VoiceSessionRow {providers_used: string[];language: string;wake_keyword: string;+ voice_mode: VoiceMode;}export interface SessionListItem extends VoiceSessionRow {diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsindex 58a701722e..0f8cae89dd 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -3,7 +3,6 @@ import {BrowserSpeechFallback,browserRealtimeSupportIssue,buildAudioSocketUrl,- ensureAudioSocketToken,StreamingPcm16Resampler,} from "./realtimeAudio";@@ -17,39 +16,11 @@ describe("realtime audio client", () => {afterEach(() => vi.unstubAllGlobals());- it("builds a wss /ws/audio url with the token", () => {- expect(buildAudioSocketUrl()).toBe("wss://app.example/ws/audio?token=tok");+ it("builds a token-free wss /ws/audio URL", () => {+ expect(buildAudioSocketUrl()).toBe("wss://app.example/ws/audio");});- it("reuses an injected desktop token without fetching another", async () => {- const fetchToken = vi.fn();- vi.stubGlobal("fetch", fetchToken);-- await expect(ensureAudioSocketToken()).resolves.toBe("tok");- expect(fetchToken).not.toHaveBeenCalled();- });-- it("fetches and registers a canonical token for a remote browser", async () => {- (window as Window & { __JARVIS_TOKEN?: string }).__JARVIS_TOKEN = undefined;- const fetchToken = vi.fn().mockResolvedValue({- ok: true,- status: 200,- json: vi.fn().mockResolvedValue({ token: "remote-token" }),- });- vi.stubGlobal("fetch", fetchToken);-- await expect(ensureAudioSocketToken()).resolves.toBe("remote-token");-- expect(fetchToken).toHaveBeenCalledWith("/api/missions/auth/token", {- cache: "no-store",- credentials: "same-origin",- });- expect(buildAudioSocketUrl()).toBe(- "wss://app.example/ws/audio?token=remote-token",- );- });-- it("fails closed when localhost cannot obtain a token", async () => {+ it("builds a token-free localhost audio URL", () => {vi.stubGlobal("window", {location: {protocol: "http:",@@ -57,19 +28,9 @@ describe("realtime audio client", () => {hostname: "localhost",},});- vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("backend warming")));-- await expect(ensureAudioSocketToken()).rejects.toThrow("backend warming");expect(buildAudioSocketUrl()).toBe("ws://localhost:47821/ws/audio");});- it("fails closed when a remote browser cannot obtain a token", async () => {- (window as Window & { __JARVIS_TOKEN?: string }).__JARVIS_TOKEN = undefined;- vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("token unavailable")));-- await expect(ensureAudioSocketToken()).rejects.toThrow("token unavailable");- });-it("rejects browser microphone capture outside a secure context", () => {vi.stubGlobal("window", { isSecureContext: false });diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex 11d1e38304..b42c311d2b 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -4,43 +4,10 @@import { LevelMeter } from "./levelMeter";import pcmWorkletUrl from "./pcm-worklet.ts?worker&url";-type JarvisWindow = Window & { __JARVIS_TOKEN?: string };--function jarvisWindow(): JarvisWindow {- return window as JarvisWindow;-}-export function buildAudioSocketUrl(): string {const proto = window.location.protocol === "https:" ? "wss" : "ws";const host = window.location.host;- const token = jarvisWindow().__JARVIS_TOKEN;- const query = token ? `?token=${encodeURIComponent(token)}` : "";- return `${proto}://${host}/ws/audio${query}`;-}--/** Ensure a remote browser has the canonical token used by tool-capable sockets.- *- * Desktop WebViews inject this token before React starts. A normal headless- * browser does not, so obtain one from the same mission-token registry before- * opening `/ws/audio`. Tokenless localhost is deliberately rejected too: a- * hostile webpage can otherwise connect directly to the local WebSocket.- */-export async function ensureAudioSocketToken(): Promise<string> {- const existing = jarvisWindow().__JARVIS_TOKEN?.trim();- if (existing) return existing;-- const response = await fetch("/api/missions/auth/token", {- cache: "no-store",- credentials: "same-origin",- });- if (!response.ok) {- throw new Error(`Realtime voice authorization failed (${response.status})`);- }- const payload = (await response.json()) as { token?: unknown };- const token = typeof payload.token === "string" ? payload.token.trim() : "";- if (!token) throw new Error("Realtime voice authorization returned no token");- jarvisWindow().__JARVIS_TOKEN = token;- return token;+ return `${proto}://${host}/ws/audio`;}export type RealtimeStatusPayload = Record<string, unknown>;@@ -257,7 +224,6 @@ export class RealtimeAudioClient {try {const supportIssue = browserRealtimeSupportIssue();if (supportIssue) throw new RealtimeAudioSupportError(supportIssue);- await ensureAudioSocketToken();this.ctx = new AudioContext({ latencyHint: "interactive" });if (!this.ctx.audioWorklet) {throw new RealtimeAudioSupportError("audio_worklet_unavailable");diff --git a/tests/unit/browser_voice/test_route.py b/tests/unit/browser_voice/test_route.pyindex 734f641906..9316a1d7e7 100644--- a/tests/unit/browser_voice/test_route.py+++ b/tests/unit/browser_voice/test_route.py@@ -68,8 +68,13 @@ class _FakeWS:self.scope = {"app": SimpleNamespace(state=state),"client": (client_host, 50_000),+ "headers": (+ [(b"cookie", f"jarvis_session={token}".encode("ascii"))]+ if token+ else []+ ),}- self.query_params = {"token": token} if token else {}+ self.query_params = {}self.accepted = Falseself.sent_bytes: list[bytes] = []self.sent_json: list[dict] = []diff --git a/tests/unit/realtime/test_realtime_credential_aliases.py b/tests/unit/realtime/test_realtime_credential_aliases.pyindex 2c837bb42e..f61fc6af96 100644--- a/tests/unit/realtime/test_realtime_credential_aliases.py+++ b/tests/unit/realtime/test_realtime_credential_aliases.py@@ -17,16 +17,16 @@ from jarvis.ui.web.provider_spec import get_specdef test_gemini_live_adapter_credentials_match_canonical_family() -> None:assert GeminiLiveProvider.credential_candidates == PROVIDER_SECRET_CANDIDATES[- "gemini"+ "gemini-live"]- assert AUTH_PROVIDER_ALIASES["gemini-live"] == "gemini"+ assert AUTH_PROVIDER_ALIASES["gemini-live"] == "gemini-live"def test_grok_realtime_adapter_credentials_match_canonical_family() -> None:assert GrokRealtimeProvider.credential_candidates == PROVIDER_SECRET_CANDIDATES[- "grok"+ "grok-realtime"]- assert AUTH_PROVIDER_ALIASES["grok-realtime"] == "grok"+ assert AUTH_PROVIDER_ALIASES["grok-realtime"] == "grok-realtime"@pytest.mark.parametrize(diff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.pyindex 63f0ddffde..ff0fc1873a 100644--- a/tests/unit/realtime/test_scrub_gate.py+++ b/tests/unit/realtime/test_scrub_gate.py@@ -1,7 +1,10 @@import pytest+import jarvis.realtime.scrub_gate as scrub_gate_module+from jarvis.brain.output_filter import ScrubResultfrom jarvis.core.protocols import AudioChunkfrom jarvis.realtime.scrub_gate import ScrubHoldGate+from jarvis.speech.hangup import END_CALL_SIGNALdef _chunk(n: int) -> AudioChunk:@@ -62,6 +65,77 @@ async def test_leading_streaming_dash_waits_for_meaningful_transcript():assert gate.release_available() == [buffered]+async def test_split_filler_opener_can_complete_a_substantive_reply():+ """A temporary ``Let me think`` prefix must not abort streamed output."""+ gate = ScrubHoldGate(language="en")+ buffered = _chunk(8)++ display = [await gate.feed_transcript("Let me")]+ display.append(await gate.feed_transcript(" think"))+ assert gate.hard_leak_pending() is False+ assert await gate.push_audio(buffered) == []++ continuation = ", the benefits include stronger bones."+ display.append(await gate.feed_transcript(continuation))++ assert gate.hard_leak_pending() is False+ assert "".join(display) == f"Let me think{continuation}"+ assert gate.release_available() == [buffered]+++ "fragment",+ [+ pytest.param("**", id="markdown"),+ pytest.param("https://example.com", id="source-url"),+ pytest.param("As an AI.", id="self-reference"),+ pytest.param("I'm noting that down.", id="background-narration"),+ pytest.param(+ "If I understand correctly, yes.",+ id="echo-paraphrase",+ ),+ pytest.param("Great question.", id="filler-opener"),+ pytest.param("MCP", id="engineering-jargon"),+ pytest.param("Sir,", id="honorific"),+ pytest.param("\N{EM DASH}", id="dash"),+ ],+)+async def test_harmless_scrub_fragment_never_becomes_generic_error(+ fragment: str,+):+ gate = ScrubHoldGate(language="en")+ buffered = _chunk(8)++ assert await gate.feed_transcript(fragment) == fragment+ assert gate.hard_leak_pending() is False+ assert await gate.push_audio(buffered) == []++ continuation = " A substantive answer follows."+ assert await gate.feed_transcript(continuation) == continuation+ assert gate.hard_leak_pending() is False+ assert gate.release_available() == [buffered]+++ ("fragment", "expected_display"),+ [+ pytest.param(END_CALL_SIGNAL, "", id="end-call-control"),+ pytest.param("1", "one", id="number-spelling"),+ ],+)+async def test_other_non_blocking_scrub_actions_do_not_raise_generic_error(+ fragment: str,+ expected_display: str,+):+ gate = ScrubHoldGate(language="en")++ assert await gate.feed_transcript(fragment) == expected_display+ assert gate.hard_leak_pending() is False++@pytest.mark.asyncioasync def test_streamed_jargon_prefix_can_complete_a_user_facing_compound():"""A partial ``MCP-Server`` transcript must not abort a clean reply."""@@ -109,6 +183,50 @@ async def test_hard_leak_transcript_marks_leak_and_drops_audio():assert gate.fallback_phrase() == "An error occurred."+ ("transcript", "expected_action"),+ [+ pytest.param(+ "Traceback (most recent call last):\n File x\nValueError: y\n",+ "replaced_stacktrace",+ id="stacktrace",+ ),+ pytest.param("{'result': 'raw'}", "replaced_raw_repr", id="raw-repr"),+ pytest.param(+ "cmd /c start app",+ "replaced_shell_command",+ id="shell-command",+ ),+ pytest.param(+ 'Before <tool_call>{"name":"spawn_worker"}</tool_call> after.',+ "removed_tool_json",+ id="tool-payload-with-prose",+ ),+ ],+)+async def test_actual_machine_leak_still_blocks_output(+ transcript: str,+ expected_action: str,+):+ gate = ScrubHoldGate(language="en")++ await gate.feed_transcript(transcript)++ assert gate.hard_leak_pending() is True+ assert expected_action in gate.hard_leak_actions()+++def test_unclassified_scrub_action_fails_closed():+ result = ScrubResult(+ cleaned="Future output",+ actions=["future_unclassified_action"],+ fallback_used=False,+ )++ assert scrub_gate_module._is_hard_scrub_result(result) is True++@pytest.mark.asyncioasync def test_scrub_is_regex_only_no_llm(monkeypatch):# Guard AP-11: the gate must call scrub_for_voice and nothing that awaits a model.diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 94d5d86a1d..99120af153 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -909,6 +909,46 @@ async def test_isolated_dash_delta_keeps_realtime_audio_playing():assert not any(item.get("type") == "error_spoken" for item in jsons)+async def test_split_filler_opener_keeps_realtime_answer_playing():+ answer_audio = b"\x55\x66" * 8+ events = [+ RealtimeEvent(type="output_transcript_delta", text="Let me"),+ RealtimeEvent(type="output_transcript_delta", text=" think"),+ RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=answer_audio,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ ),+ RealtimeEvent(+ type="output_transcript_delta",+ text=", the benefits include stronger bones.",+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ binaries: list[bytes] = []+ jsons: list[dict] = []+ sess = RealtimeVoiceSession(+ session_id="streaming-filler-opener",+ send_binary=lambda data: binaries.append(data) or asyncio.sleep(0),+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),+ provider=FakeProvider(events),+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert binaries == [answer_audio]+ assert not any(item.get("type") == "tts_cancel" for item in jsons)+ assert not any(item.get("type") == "error_spoken" for item in jsons)++@pytest.mark.asyncioasync def test_later_segment_leak_audio_not_emitted():# Regression test for the T4 ScrubHoldGate one-chunk-boundary residual:diff --git a/tests/unit/sessions/test_models_resilience.py b/tests/unit/sessions/test_models_resilience.pyindex dcc3362dff..7e477754db 100644--- a/tests/unit/sessions/test_models_resilience.py+++ b/tests/unit/sessions/test_models_resilience.py@@ -16,13 +16,13 @@ import pytestfrom jarvis.sessions.models import (KNOWN_HANGUP_REASONS,+ KNOWN_VOICE_MODES,KNOWN_VOICE_TIERS,SessionListItem,VoiceSessionRow,VoiceTurnRow,)-# --- Layer 1: every known value validates -------------------------@@ -74,6 +74,21 @@ def test_unknown_tier_does_not_break_validation() -> None:assert turn.tier == "phase8_future_tier"[email protected]("voice_mode", sorted(KNOWN_VOICE_MODES))+def test_session_validates_every_known_voice_mode(voice_mode: str) -> None:+ item = VoiceSessionRow(id="s1", started_ms=0, voice_mode=voice_mode)+ assert item.voice_mode == voice_mode+++def test_unknown_voice_mode_does_not_break_validation() -> None:+ item = SessionListItem(+ id="s1",+ started_ms=0,+ voice_mode="future-duplex-v2",+ )+ assert item.voice_mode == "future-duplex-v2"++# --- Layer 3: live-DB drift detector --------------------------------diff --git a/tests/unit/sessions/test_recorder_realtime.py b/tests/unit/sessions/test_recorder_realtime.pyindex 8a487b8bcc..23f3183249 100644--- a/tests/unit/sessions/test_recorder_realtime.py+++ b/tests/unit/sessions/test_recorder_realtime.py@@ -94,6 +94,9 @@ async def test_realtime_provider_model_and_ready_event_are_recorded(tmp_path) ->assert turns[0].model == "live-model"assert turns[0].latency_total_ms == 120assert turns[0].tool_calls == ["safe-tool"]+ session = store.get_session("realtime-session")+ assert session is not None+ assert session.voice_mode == "realtime"ready = [eventfor event in store.get_events("realtime-session")diff --git a/tests/unit/sessions/test_voice_mode.py b/tests/unit/sessions/test_voice_mode.pynew file mode 100644index 0000000000..be834925ec--- /dev/null+++ b/tests/unit/sessions/test_voice_mode.py@@ -0,0 +1,207 @@+"""Durable runtime evidence for voice-session engine mode."""+from __future__ import annotations++import sqlite3++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.core.bus import EventBus+from jarvis.core.events import (+ ListeningStarted,+ RealtimeSessionReady,+ VoiceSessionEnded,+ VoiceSessionStarted,+)+from jarvis.sessions.recorder import SessionRecorder+from jarvis.sessions.store import _SCHEMA_PATH, SessionStore+from jarvis.ui.web import sessions_routes+++def _legacy_schema_without_voice_mode() -> str:+ schema = _SCHEMA_PATH.read_text(encoding="utf-8")+ return schema.replace(+ " wake_keyword TEXT NOT NULL DEFAULT '',\n"+ " voice_mode TEXT NOT NULL DEFAULT 'unknown' "+ "-- unknown|pipeline|realtime; open string for forward compatibility\n",+ " wake_keyword TEXT NOT NULL DEFAULT ''\n",+ )+++def test_migration_backfills_runtime_evidence_and_is_idempotent(tmp_path) -> None:+ db_path = tmp_path / "legacy-sessions.db"+ conn = sqlite3.connect(db_path)+ try:+ conn.executescript(_legacy_schema_without_voice_mode())+ conn.executemany(+ "INSERT INTO voice_sessions (id, started_ms) VALUES (?, ?)",+ [+ ("ready", 100),+ ("tier", 200),+ ("pipeline", 300),+ ("fallback", 400),+ ("unknown", 500),+ ],+ )+ conn.execute(+ "INSERT INTO voice_turns "+ "(id, session_id, idx, started_ms, tier) VALUES (?, ?, ?, ?, ?)",+ ("tier-turn", "tier", 0, 200, "realtime"),+ )+ conn.executemany(+ "INSERT INTO voice_events "+ "(session_id, ts_ms, kind, payload_json) VALUES (?, ?, ?, '{}')",+ [+ ("ready", 110, "RealtimeSessionReady"),+ ("pipeline", 310, "ListeningStarted"),+ ("fallback", 410, "RealtimeSessionReady"),+ ("fallback", 420, "ListeningStarted"),+ ],+ )+ conn.commit()+ finally:+ conn.close()++ for _ in range(2):+ store = SessionStore(db_path)+ store.open()+ try:+ modes = {item.id: item.voice_mode for item in store.list_sessions()}+ assert modes == {+ "ready": "realtime",+ "tier": "realtime",+ "pipeline": "pipeline",+ "fallback": "pipeline",+ "unknown": "unknown",+ }+ finally:+ store.close()+++async def _publish_session(+ bus: EventBus,+ *,+ session_id: str,+ evidence: tuple[str, ...],+) -> None:+ await bus.publish(+ VoiceSessionStarted(+ source_layer="speech.pipeline",+ session_id=session_id,+ wake_keyword="hotkey",+ language="en",+ )+ )+ for mode in evidence:+ if mode == "realtime":+ await bus.publish(+ RealtimeSessionReady(+ source_layer="realtime.test",+ session_id=session_id,+ provider="test-live",+ model="test-model",+ )+ )+ elif mode == "pipeline":+ await bus.publish(ListeningStarted(source_layer="speech"))+ await bus.publish(+ VoiceSessionEnded(+ source_layer="speech.pipeline",+ session_id=session_id,+ hangup_reason="turn_complete",+ )+ )+++async def test_recorder_persists_pipeline_fallback_and_unknown_modes(tmp_path) -> None:+ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ bus = EventBus()+ SessionRecorder(store).attach(bus)++ await _publish_session(bus, session_id="pipeline", evidence=("pipeline",))+ await _publish_session(+ bus,+ session_id="fallback",+ evidence=("realtime", "pipeline"),+ )+ await _publish_session(bus, session_id="unknown", evidence=())++ pipeline = store.get_session("pipeline")+ fallback = store.get_session("fallback")+ unknown = store.get_session("unknown")+ assert pipeline is not None and pipeline.voice_mode == "pipeline"+ assert fallback is not None and fallback.voice_mode == "pipeline"+ assert unknown is not None and unknown.voice_mode == "unknown"+ finally:+ store.close()+++async def test_realtime_ready_for_another_session_is_not_evidence(tmp_path) -> None:+ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ bus = EventBus()+ SessionRecorder(store).attach(bus)+ await bus.publish(+ VoiceSessionStarted(+ source_layer="speech.pipeline",+ session_id="current",+ language="en",+ )+ )+ await bus.publish(+ RealtimeSessionReady(+ source_layer="realtime.test",+ session_id="different",+ provider="test-live",+ model="test-model",+ )+ )+ await bus.publish(+ VoiceSessionEnded(+ source_layer="speech.pipeline",+ session_id="current",+ hangup_reason="turn_complete",+ )+ )++ session = store.get_session("current")+ assert session is not None+ assert session.voice_mode == "unknown"+ assert all(+ event.kind != "RealtimeSessionReady"+ for event in store.get_events("current")+ )+ finally:+ store.close()+++def test_list_and_detail_routes_serialize_open_voice_mode(tmp_path) -> None:+ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ store.upsert_session(+ session_id="future-mode",+ started_ms=1_000,+ language="en",+ voice_mode="future-duplex-v2",+ )+ app = FastAPI()+ app.include_router(sessions_routes.router)+ app.state.session_store = store++ with TestClient(app) as client:+ listed = client.get("/api/sessions")+ detail = client.get("/api/sessions/future-mode")++ assert listed.status_code == 200+ assert listed.json()[0]["voice_mode"] == "future-duplex-v2"+ assert detail.status_code == 200+ assert detail.json()["session"]["voice_mode"] == "future-duplex-v2"+ finally:+ store.close()diff --git a/tests/unit/sessions/test_voice_mode_parity.py b/tests/unit/sessions/test_voice_mode_parity.pynew file mode 100644index 0000000000..1afd4e3ba9--- /dev/null+++ b/tests/unit/sessions/test_voice_mode_parity.py@@ -0,0 +1,54 @@+"""Parity guard for the persisted voice-session mode vocabulary."""+from __future__ import annotations++import json+import re+from pathlib import Path++from jarvis.sessions.constants import VOICE_MODES+from jarvis.sessions.models import KNOWN_VOICE_MODES++REPO_ROOT = Path(__file__).resolve().parents[3]+TYPES_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/components/sessions/types.ts"+SCHEMA_SQL = REPO_ROOT / "jarvis/sessions/schema.sql"+LOCALES_DIR = REPO_ROOT / "jarvis/ui/web/frontend/src/i18n/locales"+++def _expected() -> set[str]:+ return set(VOICE_MODES)+++def test_models_known_set_matches_constants_tuple() -> None:+ assert set(KNOWN_VOICE_MODES) == _expected()+++def test_types_ts_known_set_matches_constants_tuple() -> None:+ text = TYPES_TS.read_text(encoding="utf-8")+ block = re.search(+ r"export\s+const\s+KNOWN_VOICE_MODES\s*=\s*\[([\s\S]+?)\]\s*as\s+const",+ text,+ )+ assert block is not None, "could not find KNOWN_VOICE_MODES in types.ts"+ found = set(re.findall(r'"([^"]+)"', block.group(1)))+ assert found == _expected()+++def test_schema_documents_every_known_mode() -> None:+ text = SCHEMA_SQL.read_text(encoding="utf-8")+ declaration = re.search(+ r"voice_mode\s+TEXT[^\n]*--\s*([^;\n]+)",+ text,+ )+ assert declaration is not None, "voice_mode schema vocabulary is missing"+ found = {value.strip() for value in declaration.group(1).split("|")}+ assert found == _expected()+++def test_every_locale_labels_every_known_mode() -> None:+ for locale in ("en", "de", "es"):+ document = json.loads(+ (LOCALES_DIR / f"{locale}.json").read_text(encoding="utf-8")+ )+ labels = document["voice_mode"]+ assert set(labels) - {"label"} == _expected(), f"{locale} locale drift"+ assert all(labels[mode].strip() for mode in _expected())diff --git a/tests/unit/speech/test_dictation_stale_hangup.py b/tests/unit/speech/test_dictation_stale_hangup.pyindex bf50df6682..b80eab22f8 100644--- a/tests/unit/speech/test_dictation_stale_hangup.py+++ b/tests/unit/speech/test_dictation_stale_hangup.py@@ -66,3 +66,13 @@ async def test_start_dictation_clears_stale_hangup() -> None:"start_dictation must clear a stale hangup so the session is not ""finalized on its first wait tick")+++async def test_start_dictation_does_not_spawn_when_capture_gate_is_closed() -> None:+ pipe = _make_idle_pipeline()+ pipe._activation_gate = lambda: False++ assert pipe.start_dictation() is False+ assert pipe._dictation_task is None+ assert pipe._hangup_event.is_set()diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.pyindex 53cdeac671..e7fc837414 100644--- a/tests/unit/speech/test_realtime_mode.py+++ b/tests/unit/speech/test_realtime_mode.py@@ -433,6 +433,116 @@ async def test_desktop_cpu_barge_in_cancels_and_forwards_user_preroll(assert built["half_duplex"] is True+async def test_post_output_echo_tail_stays_local_and_preserves_immediate_user(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Hardware playback tail must not become a phantom realtime turn."""+ pipe = _pipe()+ pipe._continue_listening_after_response = True+ output_finished = asyncio.Event()+ echo_pcm = b"\x01\x00" * 32+ user_pcm = b"\x02\x00" * 32+ forwarded = b"\x09\x00" * 32+ detector_inputs: list[bytes] = []++ class _Detector:+ def __init__(self) -> None:+ self.active = False++ def warmup(self) -> None:+ return None++ def start_output(self) -> None:+ self.active = True++ def stop_output(self) -> None:+ self.active = False++ def feed(self, pcm: bytes) -> bytes | None:+ detector_inputs.append(pcm)+ if pcm == user_pcm:+ self.active = False+ return forwarded+ return None++ class _Mic:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc: object) -> bool:+ return False++ async def stream(self):+ await output_finished.wait()+ # The capture task starts before the provider handshake. Let the+ # completed handshake open its provider_ready gate before yielding.+ await asyncio.sleep(0.05)+ yield AudioChunk(pcm=echo_pcm, sample_rate=16_000, timestamp_ns=0)+ await asyncio.sleep(0)+ yield AudioChunk(pcm=user_pcm, sample_rate=16_000, timestamp_ns=0)+ await asyncio.Event().wait()++ class _Session(_HandshakeOnlyRealtimeSession):+ def __init__(self, send_binary, send_json) -> None:+ super().__init__(send_binary, send_json)+ self.audio_frames: list[bytes] = []+ self.received = asyncio.Event()++ async def handle_control(self, message) -> None:+ self.controls.append(message)+ if message.get("type") == "audio_start":+ await self._send_json(+ {+ "type": "audio_ready",+ "provider": "fake-live",+ "input_sample_rate": 16_000,+ "output_sample_rate": 24_000,+ }+ )+ await self._send_json(+ {+ "type": "transcript",+ "role": "user",+ "text": "simple question",+ "is_final": True,+ }+ )+ await self._send_binary(b"\x03\x00" * 32)+ await self._send_json({"type": "turn_complete"})+ output_finished.set()+ elif message.get("type") == "barge_in":+ await self._send_json({"type": "tts_cancel"})++ async def handle_audio_frame(self, pcm: bytes) -> None:+ self.audio_frames.append(pcm)+ self.received.set()++ async def wait_finished(self) -> None:+ await self.received.wait()++ built: dict[str, object] = {}++ def _build(**kwargs):+ session = _Session(kwargs["send_binary"], kwargs["send_json"])+ built["session"] = session+ return session++ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)+ monkeypatch.setattr(+ "jarvis.realtime.desktop.DesktopRealtimeBargeInDetector", _Detector+ )+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _Mic())++ reason = await asyncio.wait_for(pipe._active_realtime_session(), timeout=2.0)++ session = built["session"]+ assert reason == HANGUP_ERROR+ assert detector_inputs == [echo_pcm, user_pcm]+ assert session.audio_frames == [forwarded]+ assert {"type": "barge_in"} in session.controls++@pytest.mark.asyncioasync def test_completed_startup_tasks_do_not_end_healthy_realtime_session(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/trigger/test_hotkey_backends.py b/tests/unit/trigger/test_hotkey_backends.pyindex 69b341c8ed..5b63bcf8e0 100644--- a/tests/unit/trigger/test_hotkey_backends.py+++ b/tests/unit/trigger/test_hotkey_backends.py@@ -414,13 +414,13 @@ def test_pynput_backend_darwin_without_ax_grant_degrades(monkeypatch, caplog):# thread; without the Accessibility grant that native init can abort the# whole process (uncatchable — BUG-058 class). The backend must preflight# AXIsProcessTrusted and degrade instead of touching pynput at all.- import jarvis.platform.probes as probes+ import jarvis.trigger.backends.pynput as pynput_backendfrom jarvis.trigger.backends.pynput import PynputBackendbuilt: list = []_install_fake_pynput(monkeypatch, built)monkeypatch.setattr("sys.platform", "darwin")- monkeypatch.setattr(probes, "ax_permission_granted", lambda: False)+ monkeypatch.setattr(pynput_backend, "_macos_hotkey_permissions_granted", lambda: False)backend = PynputBackend()with caplog.at_level(logging.WARNING):backend.start()@@ -430,13 +430,17 @@ def test_pynput_backend_darwin_without_ax_grant_degrades(monkeypatch, caplog):def test_pynput_backend_darwin_unverifiable_grant_degrades(monkeypatch, caplog):# pyobjc absent -> probe returns None -> fail closed on darwin.- import jarvis.platform.probes as probes+ import jarvis.trigger.backends.pynput as pynput_backendfrom jarvis.trigger.backends.pynput import PynputBackendbuilt: list = []_install_fake_pynput(monkeypatch, built)monkeypatch.setattr("sys.platform", "darwin")- monkeypatch.setattr(probes, "ax_permission_granted", lambda: None)+ monkeypatch.setattr(+ pynput_backend,+ "_macos_hotkey_permissions_granted",+ lambda: False,+ )backend = PynputBackend()with caplog.at_level(logging.WARNING):backend.start()@@ -444,13 +448,13 @@ def test_pynput_backend_darwin_unverifiable_grant_degrades(monkeypatch, caplog):def test_pynput_backend_darwin_with_grant_starts_listener(monkeypatch):- import jarvis.platform.probes as probes+ import jarvis.trigger.backends.pynput as pynput_backendfrom jarvis.trigger.backends.pynput import PynputBackendbuilt: list = []_install_fake_pynput(monkeypatch, built)monkeypatch.setattr("sys.platform", "darwin")- monkeypatch.setattr(probes, "ax_permission_granted", lambda: True)+ monkeypatch.setattr(pynput_backend, "_macos_hotkey_permissions_granted", lambda: True)backend = PynputBackend()backend.start()assert len(built) == 1 # grant present -> hotkeys arm normally@@ -458,7 +462,7 @@ def test_pynput_backend_darwin_with_grant_starts_listener(monkeypatch):def test_pynput_backend_off_darwin_needs_no_probe(monkeypatch):# AD-7: the preflight is darwin-only; Linux/Windows never consult it.- import jarvis.platform.probes as probes+ import jarvis.trigger.backends.pynput as pynput_backendfrom jarvis.trigger.backends.pynput import PynputBackendbuilt: list = []@@ -468,7 +472,33 @@ def test_pynput_backend_off_darwin_needs_no_probe(monkeypatch):def _boom() -> None:raise AssertionError("probe consulted off darwin")- monkeypatch.setattr(probes, "ax_permission_granted", _boom)+ monkeypatch.setattr(pynput_backend, "_macos_hotkey_permissions_granted", _boom)backend = PynputBackend()backend.start()assert len(built) == 1+++def test_pynput_backend_revoked_permission_suppresses_live_callback(monkeypatch):+ import jarvis.trigger.backends.pynput as pynput_backend+ from jarvis.trigger.backends.pynput import PynputBackend++ built: list = []+ allowed = {"value": True}+ _install_fake_pynput(monkeypatch, built)+ monkeypatch.setattr("sys.platform", "darwin")+ monkeypatch.setattr(+ pynput_backend,+ "_macos_hotkey_permissions_granted",+ lambda: allowed["value"],+ )+ fired: list[str] = []+ backend = PynputBackend()+ backend.register([["control + j", lambda: fired.append("call"), None]])+ backend.start()++ allowed["value"] = False+ backend._held.update({"ctrl", "j"})+ backend._reconcile()++ assert fired == []+ assert backend._held == set()diff --git a/tests/unit/web/test_mic_level_route.py b/tests/unit/web/test_mic_level_route.pyindex b798cda59a..368f55fade 100644--- a/tests/unit/web/test_mic_level_route.py+++ b/tests/unit/web/test_mic_level_route.py@@ -1,6 +1,8 @@"""GET /api/settings/wake-word/mic-level -- live mic dBFS for the onboardingwake step (Task 7). Never 500s; reports too_quiet / no_device honestly."""+from types import SimpleNamespace+import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -8,6 +10,14 @@ from fastapi.testclient import TestClientfrom jarvis.ui.web.settings_routes import router+class _PermissionPort:+ def __init__(self, allowed: bool) -> None:+ self.allowed = allowed++ def runtime_access_granted(self, _permission_id) -> bool:+ return self.allowed++@pytest.fixturedef client(monkeypatch):import jarvis.speech.diagnose as d@@ -85,3 +95,69 @@ def test_mic_level_never_500s_on_helper_error(monkeypatch):b = r.json()assert b["no_device"] is Trueassert b["too_quiet"] is False+++def test_macos_permission_block_never_opens_microphone(monkeypatch):+ import jarvis.speech.diagnose as d+ import jarvis.ui.web.settings_routes as settings_routes++ calls = 0++ async def forbidden_measure(duration_s=3.0):+ nonlocal calls+ calls += 1+ return -15.0++ monkeypatch.setattr(settings_routes.sys, "platform", "darwin")+ monkeypatch.setattr(d, "measure_mic_dbfs", forbidden_measure)+ app = FastAPI()+ app.state.system_permission_port = _PermissionPort(False)+ app.include_router(router)++ response = TestClient(app).get("/api/settings/wake-word/mic-level")++ assert response.status_code == 200+ assert response.json() == {+ "max_dbfs": -120.0,+ "no_device": False,+ "too_quiet": False,+ "permission_required": True,+ }+ assert calls == 0+++def test_macos_wake_self_test_does_not_bypass_permission_gate(monkeypatch):+ import jarvis.speech.diagnose as d+ import jarvis.ui.web.settings_routes as settings_routes++ calls = 0++ async def forbidden_measure(duration_s=3.0):+ nonlocal calls+ calls += 1+ return -15.0++ monkeypatch.setattr(settings_routes.sys, "platform", "darwin")+ monkeypatch.setattr(d, "measure_mic_dbfs", forbidden_measure)+ app = FastAPI()+ app.state.system_permission_port = _PermissionPort(False)+ app.state.config = SimpleNamespace(+ trigger=SimpleNamespace(+ wake_word=SimpleNamespace(+ phrase="Hey Nova",+ engine="auto",+ custom_model_path="",+ fuzzy_match_ratio=0.8,+ )+ ),+ stt=SimpleNamespace(language="en"),+ ui=SimpleNamespace(language="en"),+ )+ app.include_router(router)++ response = TestClient(app).post("/api/settings/wake-word/self-test")++ assert response.status_code == 200+ assert response.json()["permission_required"] is True+ assert response.json()["no_device"] is False+ assert calls == 0diff --git a/tests/unit/web/test_realtime_provider_category.py b/tests/unit/web/test_realtime_provider_category.pyindex 2d60aa9f02..06451f100c 100644--- a/tests/unit/web/test_realtime_provider_category.py+++ b/tests/unit/web/test_realtime_provider_category.py@@ -31,27 +31,27 @@ def _only_gemini_key(key: str, *_a, **_kw) -> str | None:# ----------------------------------------------------------------------------def test_openai_realtime_spec_is_realtime_tier_with_openai_key():+def test_openai_realtime_spec_owns_a_dedicated_key():spec = get_spec("openai-realtime")assert spec is not Noneassert spec.tier == "realtime"- assert "openai_api_key" in spec.secret_keys+ assert spec.secret_keys == ("realtime_openai_api_key",)def test_gemini_live_spec_present():spec = get_spec("gemini-live")assert spec is not Noneassert spec.tier == "realtime"- assert spec.secret_keys == ("gemini_api_key",)+ assert spec.secret_keys == ("realtime_gemini_api_key",)assert spec.alt_credential is None-def test_grok_realtime_spec_reuses_xai_key() -> None:+def test_grok_realtime_spec_owns_a_dedicated_key() -> None:spec = get_spec("grok-realtime")assert spec is not Noneassert spec.label == "xAI Grok Realtime"assert spec.tier == "realtime"- assert spec.secret_keys == ("grok_api_key",)+ assert spec.secret_keys == ("realtime_grok_api_key",)assert spec.dashboard_url == "https://console.x.ai/"