Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(realtime): say why a call ended, and stop stamping German on every language field
rubenluetke10-beep4746702801fc
diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 6fc1569073..5372fb972a 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -14,6 +14,16 @@ from typing import Any, Final, Literalfrom uuid import UUID, uuid4from .protocols import HarnessResult, HarnessTask, RiskTier, Transcript+from .turn_language import DEFAULT_LOCALE++# Every supported locale is equal (CLAUDE.md §1): a language field whose+# publisher omitted it must fall back to the SHARED default, never to one+# particular language. These defaults used to be the literal "de", so an event+# published without a language stamped German onto a Spanish or English turn —+# and the consumers that pick a TTS voice from it then spoke German back.+# ``turn_language`` is pure regex/set lookups with no jarvis imports, so this+# cannot introduce an import cycle.+_DEFAULT_EVENT_LANGUAGE: Final[str] = DEFAULT_LOCALEdef _now_ns() -> int:@@ -516,7 +526,7 @@ class SpeechSpoken(Event):wildcard subscriber and never touches the voice hot path (AP-9 / AD-OE2)."""text: str = ""- language: str = "de"+ language: str = _DEFAULT_EVENT_LANGUAGEspoken_kind: str = "other"# Optional technical diagnostic that was NOT spoken aloud — e.g. the raw# exit code + harness reason behind a failed Computer-Use action. The voice@@ -795,7 +805,7 @@ class AnnouncementRequested(Event):# ruff/UP037 suggests using "normal"/"interrupt" as bare names —# that is exactly wrong for `Literal[...]`; the strings ARE the values.priority: Literal["normal", "interrupt"] = "normal" # noqa: UP037- language: str = "de"+ language: str = _DEFAULT_EVENT_LANGUAGE# Discriminator for the new ack_brain Flash-Brain producer. None keeps# backwards compatibility with the existing MissionAnnouncer callers# that only pass text+priority+language. "progress" (2026-06-09, CU@@ -1487,7 +1497,7 @@ class VoiceSessionStarted(Event):"""Wake word detected — a new voice session is starting."""session_id: str = ""wake_keyword: str = ""- language: str = "de"+ language: str = _DEFAULT_EVENT_LANGUAGE@dataclass(frozen=True, slots=True)@@ -1522,9 +1532,9 @@ class VoiceTurnCompleted(Event):session_id: str = ""turn_id: str = ""user_text: str = ""- user_lang: str = "de"+ user_lang: str = _DEFAULT_EVENT_LANGUAGEjarvis_text: str = ""- jarvis_lang: str = "de"+ jarvis_lang: str = _DEFAULT_EVENT_LANGUAGEtier: str = ""provider: str = ""model: str = ""diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex c8675f1ef8..08ae6616da 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -592,6 +592,45 @@ _DELEGATE_BRIDGE_TEXTS: dict[str, tuple[str, ...]] = {}+#: Why the call is ending when NO voice engine could be opened. Carries every+#: supported locale, resolved through the session's one language resolver+#: (CLAUDE.md §1 runtime rule 3) — never a de/en-only table and never a+#: per-layer default. Deliberately two distinct causes rather than one generic+#: apology: "it did not come up in time" and "it could not be reached" send the+#: user to different places, and the whole point of speaking here is that the+#: call used to end after the full handshake budget with nothing said at all.+_HANDSHAKE_FAILURE_MESSAGES: dict[str, dict[str, str]] = {+ "timeout": {+ "de": (+ "Die Sprachverbindung kam nicht rechtzeitig zustande, " # i18n-allow: localized runtime voice output+ "deshalb habe ich abgebrochen."+ ),+ "en": (+ "The voice connection did not come up in time, so I stopped."+ ),+ "es": ( # i18n-allow: localized runtime voice output+ "La conexión de voz no se estableció a tiempo, así que lo detuve."+ ),+ },+ "unavailable": {+ "de": (+ "Ich konnte die Sprachverbindung gerade nicht aufbauen." # i18n-allow: localized runtime voice output+ ),+ "en": "I couldn't establish the voice connection just now.",+ "es": ( # i18n-allow: localized runtime voice output+ "No pude establecer la conexión de voz ahora mismo."+ ),+ },+}+++def _handshake_failure_message(cause: str, language: str) -> str:+ variants = _HANDSHAKE_FAILURE_MESSAGES.get(+ cause, _HANDSHAKE_FAILURE_MESSAGES["unavailable"]+ )+ return variants.get(language) or variants["en"]++def _delegate_bridge_texts(language: str) -> tuple[str, ...]:return _DELEGATE_BRIDGE_TEXTS.get(language, _DELEGATE_BRIDGE_TEXTS["en"])@@ -1856,8 +1895,55 @@ class RealtimeVoiceSession:summary = "; ".join(self._provider_errors) or "no provider could open a session"await self._publish_error("RealtimeHandshakeError", summary, recoverable=True)+ await self._announce_handshake_failure(summary)raise RuntimeError(f"No realtime provider could open a session: {summary}")+ async def _announce_handshake_failure(self, summary: str) -> None:+ """Say WHY the call is ending when no voice engine could be opened.++ A provider that refuses to cross into usage-billed voice is doing the+ right thing — that billing boundary must stay. But the surface turns+ the resulting handshake failure into ``reason=error``, so a+ subscription transport that spends its full declared budget and then+ fails ended the call after up to 45 s of total silence with nothing+ said at all. Refusing to spend the user's money is correct; refusing+ it SILENTLY is the defect.++ Deliberately quiet when the classic pipeline may still pick this call+ up: there the user gets a normal answer, and announcing a failure+ would be false.+ """+ if self.allow_classic_fallback:+ return+ lowered = summary.lower()+ cause = (+ "timeout"+ if (+ "timeouterror" in lowered+ or "budget" in lowered+ or "in time" in lowered+ )+ else "unavailable"+ )+ spoken = _handshake_failure_message(cause, self._language)+ log.warning(+ "realtime[%s] no voice engine could be opened and metered "+ "fallback is refused — ending the call with a spoken reason "+ "(cause=%s): %s",+ self.session_id,+ cause,+ summary,+ )+ try:+ # _surface_speech_message already registers the echo reference.+ await self._send_json(self._surface_speech_message(spoken))+ except Exception: # noqa: BLE001 — the handshake failure still propagates+ log.warning(+ "realtime[%s] could not voice the handshake failure notice",+ self.session_id,+ exc_info=True,+ )+def _start_pump(self) -> None:if self._pump_task is None or self._pump_task.done():self._loop_lag.start()@@ -3693,6 +3779,14 @@ class RealtimeVoiceSession:"type": "error_spoken","text": text,"language": self._language,+ # Which realtime engine this line belongs to. The desktop surface+ # resolves its realtime-scoped TTS from ambient state that is only+ # set once a handshake SUCCEEDED, so a notice about a handshake+ # that failed had no provider to resolve against and stayed+ # text-only — silent on exactly the path that needs to be heard.+ # Naming it here keeps strict mode separation intact (it is still+ # the realtime provider's own TTS family, never the pipeline's).+ "provider": self.active_provider,}if self._active_voice:message["voice"] = self._active_voicediff --git a/tests/unit/realtime/test_protocol.py b/tests/unit/realtime/test_protocol.pyindex 1775e39205..26709a93d6 100644--- a/tests/unit/realtime/test_protocol.py+++ b/tests/unit/realtime/test_protocol.py@@ -75,3 +75,49 @@ def test_event_can_mark_a_self_initiated_interruption():assert RealtimeEvent(type="interrupted").self_initiated is Falseassert RealtimeEvent(type="interrupted", self_initiated=True).self_initiated+++def test_no_event_language_field_defaults_to_one_particular_language():+ """CLAUDE.md §1: supported locales are equal, so a language field whose+ publisher omitted it must fall back to the SHARED default.++ These defaults were the literal "de", so any event published without a+ language stamped German onto a Spanish or English turn — and the consumers+ that pick a TTS voice from it then spoke German back at the user.+ """+ import dataclasses++ from jarvis.core import events as events_module+ from jarvis.core.turn_language import DEFAULT_LOCALE++ offenders = []+ for name in dir(events_module):+ candidate = getattr(events_module, name)+ if not dataclasses.is_dataclass(candidate):+ continue+ for field in dataclasses.fields(candidate):+ if "lang" not in field.name:+ continue+ default = field.default+ if isinstance(default, str) and default and default != DEFAULT_LOCALE:+ offenders.append(f"{name}.{field.name} = {default!r}")+ assert not offenders, (+ "language fields must default to DEFAULT_LOCALE, never to one "+ f"particular language: {offenders}"+ )+++def test_the_voice_language_fields_carry_the_shared_default():+ from jarvis.core.events import (+ AnnouncementRequested,+ SpeechSpoken,+ VoiceSessionStarted,+ VoiceTurnCompleted,+ )+ from jarvis.core.turn_language import DEFAULT_LOCALE++ assert VoiceSessionStarted().language == DEFAULT_LOCALE+ assert VoiceTurnCompleted().user_lang == DEFAULT_LOCALE+ assert VoiceTurnCompleted().jarvis_lang == DEFAULT_LOCALE+ assert SpeechSpoken().language == DEFAULT_LOCALE+ assert AnnouncementRequested().language == DEFAULT_LOCALEdiff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex fd4e57694a..5e8d7c9bda 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -1925,6 +1925,23 @@ class _StubExecutor:return ToolResult(success=True, output="opened")++def _spoke_surface_line(jsons, text, language="en"):+ """Whether the surface was asked to speak exactly this line.++ Field-wise on purpose: ``error_spoken`` is a growing message contract (it+ now also names the realtime provider so the desktop surface can resolve a+ realtime-scoped TTS for it), and whole-dict equality makes every future+ addition look like a regression in tests that only care about the words.+ """+ return any(+ item.get("type") == "error_spoken"+ and item.get("text") == text+ and item.get("language") == language+ for item in jsons+ )++def _delegate_cfg(tool_mode="delegate"):cfg = _cfg()if tool_mode is not None:@@ -3769,7 +3786,7 @@ async def test_text_only_provider_answer_uses_surface_tts_without_brain_retry():await sess.wait_finished()assert brain.calls == []- assert {"type": "error_spoken", "text": answer, "language": "en"} in jsons+ assert _spoke_surface_line(jsons, answer)completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]assert len(completed) == 1assert completed[0].jarvis_text == answer@@ -3803,7 +3820,7 @@ async def test_empty_provider_turn_without_brain_speaks_local_error():await sess.wait_finished()fallback = "An error occurred."- assert {"type": "error_spoken", "text": fallback, "language": "en"} in jsons+ assert _spoke_surface_line(jsons, fallback)completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]assert len(completed) == 1assert completed[0].jarvis_text == fallback@@ -3841,11 +3858,7 @@ async def test_empty_recovery_response_uses_surface_tts_without_rerunning_brain(await asyncio.wait_for(sess.wait_finished(), timeout=2)assert [call[0] for call in brain.calls] == [user_text]- assert {- "type": "error_spoken",- "text": recovered_reply,- "language": "en",- } in jsons+ assert _spoke_surface_line(jsons, recovered_reply)completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]assert len(completed) == 1assert completed[0].jarvis_text == recovered_reply@@ -4243,11 +4256,7 @@ async def test_direct_realtime_promise_without_tool_fails_closed_honestly():await sess.wait_finished()assert provider.session.interrupts == 1- assert {- "type": "error_spoken",- "text": action_not_started_phrase("en"),- "language": "en",- } in jsons+ assert _spoke_surface_line(jsons, action_not_started_phrase("en"))await sess.end(reason="test")@@ -4629,11 +4638,7 @@ async def test_delegate_empty_spoken_answer_uses_surface_tts_fallback():completed = next(event for event in bus.events if isinstance(event, VoiceTurnCompleted))assert [event.text for event in responses] == ["The action completed."]assert completed.jarvis_text == "The action completed."- assert {- "type": "error_spoken",- "text": "The action completed.",- "language": "en",- } in jsons+ assert _spoke_surface_line(jsons, "The action completed.")await sess.end(reason="test")@@ -6728,3 +6733,161 @@ async def test_a_self_initiated_interruption_is_not_read_as_user_speech():# The transport declares rebuild_on_transport_death, so ENDING the# stream would only make the pump reopen it. End the call instead.await sess.end(reason="test")+++class _UnreachableProvider(SubscriptionLikeProvider):+ """A provider whose handshake never succeeds."""++ def __init__(self, error):+ super().__init__([])+ self._error = error++ async def open_session(self, cfg):+ raise self._error+++def _no_metered_fallback_session(provider, *, jsons=None, language_cfg=None):+ """A subscription-shaped session that refuses usage-billed fallback."""+ cfg = _delegate_cfg("delegate")+ if language_cfg is not None:+ cfg.brain.reply_language = language_cfg+ return RealtimeVoiceSession(+ session_id="handshake-test",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=(+ (lambda m: jsons.append(m) or asyncio.sleep(0))+ if jsons is not None+ else (lambda _m: asyncio.sleep(0))+ ),+ provider=provider,+ config=cfg,+ half_duplex=True,+ surface="desktop",+ allow_classic_fallback=False,+ )+++async def test_an_exhausted_handshake_budget_says_why_before_it_gives_up():+ """ST-8: the call used to end after the full budget in total silence.++ A subscription transport declares a long handshake budget and refuses to+ cross into usage-billed voice. Both are correct. What was missing is the+ ending: the surface turns the handshake failure into reason=error, so the+ user waited up to 45 s and then the call simply stopped with nothing said.+ """+ provider = _UnreachableProvider(+ TimeoutError("realtime handshake exceeded 45.0s provider budget")+ )+ jsons = []+ sess = _no_metered_fallback_session(provider, jsons=jsons)++ with pytest.raises(RuntimeError):+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})++ spoken = [m for m in jsons if m.get("type") == "error_spoken"]+ assert spoken, "the user must be told why the call is ending"+ notice = spoken[0]+ assert notice["text"].strip(), "the notice must carry real words"+ assert notice["language"] == sess._language+ # The desktop surface resolves its realtime-scoped TTS from the provider;+ # on a failed handshake its ambient copy was never set, so the payload has+ # to name it or the notice stays text-only (mode separation stays intact).+ assert notice["provider"] == provider.name+ await sess.end(reason="test")+++async def test_the_handshake_notice_names_the_cause_it_actually_hit():+ """Cause-aware, not one generic apology.++ "It did not come up in time" and "it could not be reached" send the user+ to different places, so the two must not collapse into the same sentence.+ """+ timeout_jsons = []+ timeout_sess = _no_metered_fallback_session(+ _UnreachableProvider(+ TimeoutError("realtime handshake exceeded 45.0s provider budget")+ ),+ jsons=timeout_jsons,+ )+ with pytest.raises(RuntimeError):+ await timeout_sess.handle_control(+ {"type": "audio_start", "sample_rate": 16_000}+ )++ other_jsons = []+ other_sess = _no_metered_fallback_session(+ _UnreachableProvider(RuntimeError("the dedicated profile is logged out")),+ jsons=other_jsons,+ )+ with pytest.raises(RuntimeError):+ await other_sess.handle_control(+ {"type": "audio_start", "sample_rate": 16_000}+ )++ timeout_text = next(+ m for m in timeout_jsons if m.get("type") == "error_spoken"+ )["text"]+ other_text = next(+ m for m in other_jsons if m.get("type") == "error_spoken"+ )["text"]+ assert timeout_text != other_text, (+ "a timeout and an unreachable engine must not read identically"+ )+ await timeout_sess.end(reason="test")+ await other_sess.end(reason="test")+++async def test_the_handshake_notice_follows_the_pinned_reply_language():+ """One resolver decides, here as everywhere (CLAUDE.md §1 runtime rule 1).++ Every supported locale is equal: a Spanish-pinned user must not be told in+ English (or German) that the call is ending.+ """+ seen = {}+ for pin in ("de", "en", "es"):+ jsons = []+ sess = _no_metered_fallback_session(+ _UnreachableProvider(+ TimeoutError("realtime handshake exceeded 45.0s provider budget")+ ),+ jsons=jsons,+ language_cfg=pin,+ )+ with pytest.raises(RuntimeError):+ await sess.handle_control(+ {"type": "audio_start", "sample_rate": 16_000}+ )+ notice = next(m for m in jsons if m.get("type") == "error_spoken")+ assert notice["language"] == pin+ seen[pin] = notice["text"]+ await sess.end(reason="test")++ assert len(set(seen.values())) == 3, (+ f"each supported locale needs its own wording, got {seen}"+ )+++async def test_a_recoverable_handshake_failure_stays_silent():+ """Silence is correct when the classic pipeline still answers the user.++ The notice exists because the call ENDS. When usage-billed fallback is+ permitted the pipeline picks the same call up and the user gets a normal+ answer; announcing a failure there would be false.+ """+ provider = _UnreachableProvider(+ TimeoutError("realtime handshake exceeded 45.0s provider budget")+ )+ jsons = []+ sess = _session(provider, jsons=jsons) # allow_classic_fallback defaults True++ with pytest.raises(RuntimeError):+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})++ assert not [m for m in jsons if m.get("type") == "error_spoken"], (+ "the classic pipeline owns this call; nothing should be announced"+ )+ await sess.end(reason="test")