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(realtime): voice hang-up parity via HANGUP_RE and an end_call tool
Ruben Lütke5e1a0b323bb1
diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex a57f8768fd..6d2fe3a51d 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -245,4 +245,7 @@ async def browser_voice_ws(ws: WebSocket) -> None:if not await _switch_to_classic(str(exc)):breakfinally:- await session.end(reason="ws_closed")+ # A voice hang-up ends the session with its own reason; only a plain+ # socket teardown reports ws_closed.+ end_reason = str(getattr(session, "hangup_reason", "") or "") or "ws_closed"+ await session.end(reason=end_reason)diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex f8613da998..7779b36a1a 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -19,11 +19,30 @@ from jarvis.core.turn_language import resolve_output_languagefrom jarvis.realtime.audio import StreamingPcm16Resamplerfrom jarvis.realtime.protocol import RealtimeSessionConfigfrom jarvis.realtime.scrub_gate import ScrubHoldGate+from jarvis.sessions.constants import HANGUP_VOICE_PATTERN+from jarvis.speech.hangup import HANGUP_RElog = logging.getLogger(__name__)_TRANSCRIPT_LOOKAHEAD_S = 0.250_TOOL_TRANSCRIPT_WAIT_S = 3.0+# Grace window for the model to finish its goodbye after an end_call tool+# call; if the provider never sends turn_complete, hang up anyway.+_END_CALL_GRACE_S = 10.0+# Gemini emits is_final per transcript CHUNK, so hang-up matching runs on a+# per-turn accumulator; the tail-trim bounds it without losing recent words.+_HANGUP_BUFFER_MAX_CHARS = 300+# Declared to the realtime model alongside the bridge tools, but handled by+# the session itself: ending the call is surface lifecycle (like the hotkey),+# not a risk-tiered Jarvis tool, and must work even without a tool bridge.+_END_CALL_DECLARATION: dict[str, Any] = {+ "name": "end_call",+ "description": (+ "End the voice call. Call ONLY when the user explicitly says goodbye "+ "or clearly asks to end the conversation."+ ),+ "parameters": {"type": "object", "properties": {}},+}_REALTIME_SAFETY_APPENDIX = ("This is a realtime spoken conversation. Never read tool JSON, function-call ""arguments, source code, stack traces, file paths, base64, or raw URLs aloud. "@@ -148,6 +167,10 @@ class RealtimeVoiceSession:self._pending_tool_events: list[Any] = []self._tool_transcript_task: asyncio.Task[None] | None = Noneself._response_requested_for_turn = False+ self._hangup_reason = ""+ self._turn_final_text = ""+ self._end_after_turn = False+ self._end_call_timer: asyncio.Task[None] | None = Nonedef _resolve_lang(self, *, text: str) -> str:brain = getattr(self._config, "brain", None)@@ -229,9 +252,12 @@ class RealtimeVoiceSession:output_sample_rate=output_rate,modalities=("audio",),tools=(- self._tool_bridge.declarations- if self._tool_bridge is not None- else ()+ *(+ self._tool_bridge.declarations+ if self._tool_bridge is not None+ else ()+ ),+ _END_CALL_DECLARATION,),)try:@@ -353,6 +379,22 @@ class RealtimeVoiceSession:message,recoverable=True,)+ if transcript and event.is_final:+ # Per-turn accumulator: Gemini emits is_final per+ # transcript chunk, so "auflegen" may arrive split+ # across finals. The space-join reconstructs the+ # spoken sequence; turn_complete resets the buffer so+ # words never match across turn boundaries.+ self._turn_final_text = (+ f"{self._turn_final_text} {transcript}".strip()+ )[-_HANGUP_BUFFER_MAX_CHARS:]+ if HANGUP_RE.search(self._turn_final_text):+ log.info(+ "realtime[%s] voice hang-up phrase matched",+ self.session_id,+ )+ await self._finish_with_hangup()+ breakif event.is_final and self._pending_tool_events:self._cancel_tool_transcript_wait()pending = self._pending_tool_events@@ -404,7 +446,12 @@ class RealtimeVoiceSession:elif event.type in {"speech_started", "interrupted"}:await self._barge_in()elif event.type == "tool_call":- if not self._last_user_text:+ if str(getattr(event, "tool_name", "") or "") == "end_call":+ # Session lifecycle, not a bridge tool: works without+ # a tool bridge and must not be held back by the+ # missing-transcript guard below.+ await self._handle_end_call(event)+ elif not self._last_user_text:self._pending_tool_events.append(event)if self._tool_transcript_task is None:self._tool_transcript_task = asyncio.create_task(@@ -429,6 +476,12 @@ class RealtimeVoiceSession:self._output_active = Falseself._output_samples_sent = 0self._response_requested_for_turn = False+ self._turn_final_text = ""+ if self._end_after_turn:+ # end_call was acknowledged; the model has now spoken+ # its goodbye to the end — hang up.+ await self._finish_with_hangup()+ breakelif event.type == "error":message = safe_preview(event.error or "provider error", max_chars=800@@ -642,6 +695,55 @@ class RealtimeVoiceSession:self._executed_tool_names.add(original_name)await self._session.send_tool_result(call_id, wire_name, result)+ async def _handle_end_call(self, event: Any) -> None:+ if self._session is not None:+ try:+ await self._session.send_tool_result(+ str(getattr(event, "call_id", "") or ""),+ "end_call",+ {"success": True},+ )+ except Exception: # noqa: BLE001 — still hang up on a dead wire+ log.debug("end_call tool result send failed", exc_info=True)+ self._end_after_turn = True+ if self._end_call_timer is None or self._end_call_timer.done():+ self._end_call_timer = asyncio.create_task(+ self._finish_hangup_after_grace(),+ name=f"rt-end-call-{self.session_id}",+ )++ async def _finish_with_hangup(self) -> None:+ """Mark this session as ended by voice and notify the surface.++ The pump caller breaks right after; the surface (desktop loop or+ browser client) reads ``hangup_reason`` to end the call instead of+ falling back into the classic pipeline.+ """+ self._hangup_reason = HANGUP_VOICE_PATTERN+ try:+ await self._send_json(+ {"type": "hangup", "reason": HANGUP_VOICE_PATTERN}+ )+ except Exception: # noqa: BLE001, S110 — surface notify is best-effort+ pass++ async def _finish_hangup_after_grace(self) -> None:+ try:+ await asyncio.sleep(_END_CALL_GRACE_S)+ if self._ended or self._hangup_reason:+ return+ log.info(+ "realtime[%s] end_call grace expired without turn_complete",+ self.session_id,+ )+ await self._finish_with_hangup()+ if self._pump_task is not None and not self._pump_task.done():+ self._pump_task.cancel()+ except asyncio.CancelledError:+ raise+ finally:+ self._end_call_timer = None+async def _reject_untranscribed_tool_call(self, event: Any) -> None:if self._session is None:return@@ -717,6 +819,9 @@ class RealtimeVoiceSession:self._ended = Trueself._cancel_release_task()self._cancel_tool_transcript_wait()+ if self._end_call_timer is not None and not self._end_call_timer.done():+ self._end_call_timer.cancel()+ self._end_call_timer = Noneif self._pump_task is not None and not self._pump_task.done():self._pump_task.cancel()try:@@ -753,6 +858,11 @@ class RealtimeVoiceSession:def active_provider(self) -> str:return str(getattr(self._provider, "name", "") or "")+ @property+ def hangup_reason(self) -> str:+ """Non-empty once the user ended the call by voice (regex or end_call)."""+ return self._hangup_reason+@propertydef failed(self) -> bool:"""Whether the accepted duplex stream became unusable mid-session."""diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 6447bc4c70..a3e53e46d8 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -5181,6 +5181,9 @@ class SpeechPipeline:speaking = Falseawait playback.cancel()await self._set_turn_state(TurnTakingState.LISTENING)+ elif kind == "hangup":+ speaking = False+ await playback.cancel()elif kind == "turn_complete":await playback.finish_turn()speaking = False@@ -5240,6 +5243,15 @@ class SpeechPipeline:if hangup_task in done and self._hangup_event.is_set():reason = HANGUP_HOTKEYreturn HANGUP_HOTKEY+ # Voice hang-up ("auflegen" / end_call): the session ends its+ # own pump and reports the reason — end the call for real+ # instead of unwinding into the classic pipeline. Checked+ # before turn_complete: in single-turn mode both fire, and+ # voice_pattern is the more specific cause.+ session_hangup = str(getattr(session, "hangup_reason", "") or "")+ if session_hangup:+ reason = session_hangup+ return session_hangupif turn_complete.is_set():reason = HANGUP_TURN_COMPLETEreturn HANGUP_TURN_COMPLETEdiff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 8e6d066d13..66269dc35c 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -570,7 +570,10 @@ async def test_tool_call_waits_for_final_input_transcript_and_uses_bridge():await sess.wait_finished()await sess.end(reason="test")- assert provider.opened_with.tools == bridge.declarations+ # Bridge tools are declared unchanged; the session appends its own+ # end_call lifecycle declaration last.+ assert provider.opened_with.tools[: len(bridge.declarations)] == bridge.declarations+ assert provider.opened_with.tools[-1]["name"] == "end_call"assert bridge.transcripts == ["Open Calculator"]assert bridge.calls == [("open_app", {"app_name": "Calculator"})]assert provider.session.tool_results == [@@ -648,3 +651,173 @@ async def test_untranscribed_tool_call_times_out_and_unblocks_provider(monkeypatassert bridge.calls == []assert provider.session.tool_results[0][0] == "call-timeout"assert provider.session.tool_results[0][2]["success"] is False+++# --- Voice hang-up parity (regex + end_call tool) --------------------------+++def _hangup_jsons(jsons):+ return [m for m in jsons if m.get("type") == "hangup"]+++async def test_hangup_phrase_finishes_session_with_voice_pattern():+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="bitte auflegen", # i18n-allow: German hang-up phrase under test+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="hangup-regex",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason=sess.hangup_reason)++ assert sess.hangup_reason == "voice_pattern"+ assert _hangup_jsons(jsons)+ # The explicit closing command ends the call BEFORE any model response,+ # exactly like the classic pre-brain HANGUP_RE path.+ assert provider.session.response_requests == 0+++async def test_gemini_fragmented_final_chunks_accumulate_to_hangup():+ provider = FakeProvider(+ [+ RealtimeEvent(type="input_transcript", text="auf", is_final=True), # i18n-allow+ RealtimeEvent(type="input_transcript", text="legen", is_final=True), # i18n-allow+ ]+ )+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="hangup-fragments",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason=sess.hangup_reason)++ assert sess.hangup_reason == "voice_pattern"+ assert _hangup_jsons(jsons)+++async def test_hangup_accumulator_resets_at_turn_boundary():+ provider = FakeProvider(+ [+ RealtimeEvent(type="input_transcript", text="auf", is_final=True), # i18n-allow+ RealtimeEvent(type="turn_complete"),+ RealtimeEvent(+ type="input_transcript",+ text="legen wir los", # i18n-allow: must NOT join across turns+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="hangup-turn-boundary",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),+ provider=provider,+ 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 sess.hangup_reason == ""+ assert _hangup_jsons(jsons) == []+++async def test_end_call_tool_finishes_after_turn_complete():+ bridge = FakeToolBridge()+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="danke das war alles", # i18n-allow: polite closing under test+ is_final=True,+ ),+ RealtimeEvent(type="tool_call", call_id="c-end", tool_name="end_call"),+ RealtimeEvent(type="output_transcript_delta", text="Goodbye!"),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="hangup-end-call",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ tool_bridge=bridge,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason=sess.hangup_reason)++ # end_call is session lifecycle: acknowledged to the model, never routed+ # through the tool bridge, and the hang-up waits for the goodbye turn.+ assert ("c-end", "end_call", {"success": True}) in provider.session.tool_results+ assert bridge.calls == []+ assert sess.hangup_reason == "voice_pattern"+ hangups = _hangup_jsons(jsons)+ assert hangups+ turn_completes = [m for m in jsons if m.get("type") == "turn_complete"]+ assert turn_completes, "the model finishes its goodbye before the hang-up"+++async def test_ordinary_speech_does_not_hang_up():+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="wie ist das wetter heute", # i18n-allow: ordinary speech guard+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="hangup-guard",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda m: jsons.append(m) or asyncio.sleep(0),+ provider=provider,+ 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 sess.hangup_reason == ""+ assert _hangup_jsons(jsons) == []+ assert provider.session.response_requests == 1diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.pyindex 0c36e5177a..07e5d01c6f 100644--- a/tests/unit/speech/test_realtime_mode.py+++ b/tests/unit/speech/test_realtime_mode.py@@ -250,6 +250,48 @@ def test_runtime_status_never_confuses_configured_and_effective_mode() -> None:assert status["active_session_provider"] == ""+async def test_desktop_loop_returns_voice_pattern_on_session_hangup(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A voice hang-up ends the call for real — no classic-pipeline fallback."""++ class _HangupSession(_FakeRealtimeSession):+ hangup_reason = "voice_pattern"++ async def handle_control(self, message) -> None:+ self.controls.append(message)+ await self._send_json(+ {+ "type": "audio_ready",+ "provider": "fake-live",+ "input_sample_rate": 16_000,+ "output_sample_rate": 24_000,+ }+ )++ async def wait_finished(self) -> None:+ return None++ pipe = _pipe()+ built: dict[str, object] = {}++ def _build(**kwargs):+ session = _HangupSession(kwargs["send_binary"], kwargs["send_json"])+ built["session"] = session+ return session++ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)+ monkeypatch.setattr(+ pipeline_mod, "MicrophoneCapture", lambda **_kwargs: _SilentMic()+ )++ reason = await asyncio.wait_for(pipe._active_realtime_session(), timeout=2.0)++ assert reason == "voice_pattern"+ assert built["session"].end_reason == "voice_pattern"++async def _collect_stream(pipe: SpeechPipeline, chunks: list) -> list:async def _source():for chunk in chunks: