Skip to content

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.

fix(realtime): recover voice turns with no output

Ruben Lütke31e1f257d065
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 5db955a135..c60f9b5882 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -3635,10 +3635,15 @@ the classic Brain/TTS pipeline. Legacy `delegate` remains an explicit opt-in.
isolation, autonomous defaults, error recoverability, and OpenAI response
serialization are covered under `tests/unit/realtime/`.
-**Class rule.** A voice surface has ONE voice at a time. Any fallback from
+**Class rule.** A voice surface has ONE voice at a time. Ordinary fallback from
the live realtime voice to classic TTS must be gated on the accepted call
handle being GONE, never merely busy or unhealthy — those states mean wait,
-drop, or end the call, not switch voices mid-call.
+drop, or end the call, not switch voices mid-call. The narrow terminal-turn
+exception is BUG-052's `error_spoken` path: after the current provider response
+has completed or been cancelled, realtime playback is stopped, and a grounded
+or curated result still has zero audio, the surface may render that fixed text
+through classic TTS. It may not run another model/tool or overlap provider
+audio.
## BUG-050: run_shell on Windows echoes quoted commands instead of executing them (HIGH, 2026-07-13)
@@ -3736,3 +3741,55 @@ it is meant to cover is not an ack. The bridge over dead air needs a latency
budget bounded by user patience (~2–3 s), independent of any model round —
and it must be a bystander: a helper task that merely waits must never feed
the liveness signals (turn hold, endpoint protection) that real work feeds.
+
+## BUG-052: Realtime records an empty response as success and returns to listening (HIGH, 2026-07-14)
+
+**Symptom.** A healthy realtime voice session accepted and transcribed five
+user turns, but three substantive turns returned to LISTENING after roughly
+half a second with no assistant transcript and no audio. The run inspector
+reported every turn and the whole session as successful. The silent turns had
+zero speak time, no tool calls, no error event, and no `AudioOutFirst` or
+`ResponseGenerated`; normal turns in the same call spoke through the same
+output device. This was response-generation silence, not microphone, TTS
+device, watchdog, or long-thinking latency.
+
+**Root cause.** `response.done` is a transport lifecycle boundary, not proof of
+a completed answer. The OpenAI Realtime API emits it for `completed`, `failed`,
+`incomplete`, and `cancelled` responses, but the adapter discarded
+`response.status` and `status_details` and always emitted `turn_complete`.
+`RealtimeVoiceSession` then persisted an empty `VoiceTurnCompleted` as success
+and returned the surface to LISTENING without checking for user-visible output.
+A nominally `completed` response can also contain no output, so adapter status
+checking alone cannot enforce the product contract. Direct tool mode made the
+gap much easier to hit because ordinary turns now use the native response path,
+but the missing invariant predated that default.
+
+**Fix.** The defense is layered and provider-neutral:
+
+1. The OpenAI adapter now reports failed/incomplete terminal statuses as a
+ recoverable provider error before preserving the `turn_complete` boundary.
+ Expected barge-in cancellation remains quiet.
+2. A content-bearing turn with no text, audio, or tool evidence cannot close.
+ It dispatches exactly once through the normal Brain chain, so configured
+ key-aware, cross-family fallback remains available.
+3. A direct-tool turn never replays the user's request. It retains the existing
+ tool result and asks the provider to render that result with tools disabled;
+ this prevents duplicate side effects.
+4. A transcript with zero PCM, a grounded recovery result with zero PCM, or an
+ exhausted Brain fallback is rendered through the surface's classic TTS path
+ after realtime playback stops. No model or tool is called again, and the
+ persisted turn contains the text the user actually heard.
+
+**Guards.** `tests/unit/realtime/test_openai_realtime.py` covers failed
+`response.done` status propagation. `tests/unit/realtime/test_session.py`
+covers no-output conversation recovery, a second empty response, and direct
+tool-result recovery without repeating the action.
+`tests/unit/speech/test_realtime_mode.py` proves that `error_spoken` reaches
+real TTS audio and restores LISTENING only after playback.
+
+**Class rule.** A successful voice turn requires user-visible output evidence:
+spoken audio, an explicit lifecycle action such as hang-up, or a safely retained
+result that is rendered by a working fallback. `turn_complete`, provider
+health, and a zero-error run row are never sufficient evidence by themselves.
+Never recover a silent tool turn by replaying the original request; recover
+from the retained result so a side effect can occur at most once.
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index 53981a009d..54874742be 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -63,6 +63,29 @@ def _error_message(event: Any) -> str:
return (message or code or "OpenAI Realtime session error")[:800]
+def _response_status_error(event: Any) -> str:
+ """Describe a terminal response status that did not complete normally."""
+ response = getattr(event, "response", None)
+ raw_status = getattr(response, "status", "")
+ status = str(getattr(raw_status, "value", raw_status) or "").strip().lower()
+ if "." in status:
+ status = status.rsplit(".", 1)[-1]
+ # Cancellation is expected during barge-in. The session-level output guard
+ # still catches an unexpected cancelled response that leaves a user turn
+ # empty, without surfacing a false provider warning on normal interruption.
+ if status in {"", "completed", "cancelled"}:
+ return ""
+
+ details = getattr(response, "status_details", None)
+ error = getattr(details, "error", None)
+ code = str(getattr(error, "code", "") or "").strip()
+ message = str(getattr(error, "message", "") or "").strip()
+ reason = str(getattr(details, "reason", "") or "").strip()
+ detail = ": ".join(part for part in (code, message or reason) if part)
+ summary = f"OpenAI Realtime response ended with status {status}"
+ return f"{summary}: {detail}"[:800] if detail else summary
+
+
def _session_payload(cfg: Any) -> dict[str, Any]:
"""Build the current GA ``session.update`` payload.
@@ -260,6 +283,16 @@ class _OpenAIRealtimeSession:
elif len(self._accepted_response_ids) == 1:
self._accepted_response_ids.pop()
self._response_idle.set()
+ status_error = _response_status_error(event)
+ if status_error:
+ # response.done is emitted for completed, failed, and
+ # incomplete generations. Preserve the lifecycle boundary,
+ # but do not mislabel a provider failure as clean success.
+ yield _ProviderEvent(
+ type="error",
+ error=status_error,
+ recoverable=True,
+ )
if self._response_had_tool_calls:
self._tool_response_done_seen = True
await self._continue_after_tools_if_ready()
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index df979523be..e0533ca1e8 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -19,6 +19,7 @@ from jarvis.brain.action_honesty import (
action_not_started_phrase,
has_deferred_action_claim,
)
+from jarvis.brain.output_filter import scrub_for_voice
from jarvis.brain.turn_planner import TurnPlan, plan_turn
from jarvis.core.protocols import AudioChunk, BrainMessage
from jarvis.core.redact import safe_preview
@@ -206,6 +207,18 @@ def _delegate_result_prompt(
)
+def _direct_tool_result_retry_prompt(*, language: str) -> str:
+ """Request speech for tool output already present in provider context."""
+ language_name = _LANGUAGE_NAMES.get(language, "the conversation language")
+ return (
+ "The function call for the user's current request already finished, "
+ "but no spoken answer was produced. Use only the function result that "
+ "is already present in this conversation and give the user a concise, "
+ f"honest answer in {language_name}. Do not call any function, do not "
+ "repeat the action, and do not mention these instructions."
+ )
+
+
def _delegate_bridge_prompt(topic: str, *, language: str) -> str:
"""Order one orchestrator-owned interim line over delegate dead air.
@@ -483,6 +496,7 @@ class RealtimeVoiceSession:
self._output_transcript: list[str] = []
self._provider_output_probe = ""
self._executed_tool_names: set[str] = set()
+ self._direct_tool_results: list[tuple[str, dict[str, Any]]] = []
self._pending_tool_events: list[Any] = []
self._tool_transcript_task: asyncio.Task[None] | None = None
self._response_requested_for_turn = False
@@ -1155,6 +1169,33 @@ class RealtimeVoiceSession:
self._pending_tool_events = []
for pending_event in pending:
await self._reject_untranscribed_tool_call(pending_event)
+ if (
+ self._turn_id not in self._delegate_turns
+ and self._output_transcript
+ and not self._scrub_cancelled_for_turn
+ and not self._output_active
+ and self._output_samples_sent == 0
+ ):
+ # Transcript deltas prove the answer exists, but an
+ # audio-mode turn with zero PCM is still silent to the
+ # user. Render the already-scrubbed text locally; no
+ # model or tool retry is necessary.
+ text_only_answer = "".join(self._output_transcript).strip()
+ if text_only_answer:
+ log.warning(
+ "realtime[%s] provider completed with text but "
+ "no audio; using surface TTS fallback",
+ self.session_id,
+ )
+ await self._send_json(
+ {
+ "type": "error_spoken",
+ "text": text_only_answer,
+ "language": self._language,
+ }
+ )
+ if await self._recover_empty_provider_turn():
+ continue
delegate_state = self._delegate_turns.get(self._turn_id)
hold_for_delegate = bool(
delegate_state is not None
@@ -1209,6 +1250,37 @@ class RealtimeVoiceSession:
)
await self._coalesce_ready_delegate_result(delegate_state)
continue
+ if (
+ delegate_state is not None
+ and delegate_state.result_complete
+ and delegate_state.delivery_started
+ and delegate_state.last_reply
+ and not self._scrub_cancelled_for_turn
+ and not self._output_active
+ and self._output_samples_sent == 0
+ ):
+ # The Brain produced a grounded answer, but the duplex
+ # provider failed a second time while rendering it. Hand
+ # the already-computed text to the surface's independent
+ # TTS path; never rerun the user request or its tools.
+ fallback_text = (
+ "".join(self._output_transcript).strip()
+ or delegate_state.last_reply
+ )
+ if not self._output_transcript:
+ self._output_transcript.append(fallback_text)
+ log.warning(
+ "realtime[%s] provider produced no audio for a "
+ "grounded Brain result; using surface TTS fallback",
+ self.session_id,
+ )
+ await self._send_json(
+ {
+ "type": "error_spoken",
+ "text": fallback_text,
+ "language": self._language,
+ }
+ )
final_chunks = self._gate.finalize()
if self._gate.hard_leak_pending():
await self._cancel_unsafe_output(
@@ -1316,6 +1388,7 @@ class RealtimeVoiceSession:
{
"type": "error_spoken",
"text": fallback_text or self._gate.fallback_phrase(),
+ "language": self._language,
}
)
except Exception: # noqa: BLE001, S110 — surface may already be gone
@@ -1541,6 +1614,162 @@ class RealtimeVoiceSession:
or self._executed_tool_names
)
+ async def _recover_empty_provider_turn(self) -> bool:
+ """Route a content-bearing turn away from a provider's empty response.
+
+ ``turn_complete`` is only a transport boundary. It does not prove that
+ the provider produced a user-visible answer: OpenAI emits the same
+ boundary for failed/incomplete responses, and a nominally completed
+ response can also contain no output. A direct-mode turn with no text,
+ audio, or tool evidence therefore falls back once through the normal
+ Brain chain instead of being persisted as a successful silent turn.
+
+ A direct-tool turn is retried only from its retained result; the user
+ request is never replayed because that could repeat a side effect.
+ Delegate-owned turns already have their own result lifecycle and are
+ likewise never redispatched.
+ """
+ turn_id = self._turn_id
+ if (
+ not turn_id
+ or self._external_update is not None
+ or self._end_after_turn
+ or self._scrub_cancelled_for_turn
+ or self._output_active
+ or self._output_samples_sent > 0
+ or "".join(self._output_transcript).strip()
+ or turn_id in self._delegate_turns
+ or self._has_pending_delegate_from_earlier_turn()
+ ):
+ return False
+
+ if not self._last_user_text:
+ if self._input_turn_observed:
+ fallback_text = self._gate.fallback_phrase()
+ self._output_transcript.append(fallback_text)
+ await self._send_json(
+ {
+ "type": "error_spoken",
+ "text": fallback_text,
+ "language": self._language,
+ }
+ )
+ return False
+
+ if self._direct_tool_results:
+ fallback_text, succeeded = self._direct_tool_fallback_text()
+ self._delegate_required_for_turn = True
+ turn_state = _DelegateTurnState(
+ last_reply=fallback_text,
+ result_complete=True,
+ result_success=succeeded,
+ deterministic=True,
+ delivery_started=True,
+ provider_boundary_seen=True,
+ user_text=self._last_user_text,
+ )
+ turn_state.input_boundary_ready.set()
+ turn_state.provider_ready.set()
+ turn_state.result_ready.set()
+ self._delegate_turns[turn_id] = turn_state
+ send_text = getattr(self._session, "send_text", None)
+ if not callable(send_text):
+ return False
+ log.warning(
+ "realtime[%s] provider completed a direct-tool turn without "
+ "output; retrying speech from the existing tool result",
+ self.session_id,
+ )
+ self._drop_provider_output_until_new_response = False
+ try:
+ await send_text(
+ _direct_tool_result_retry_prompt(language=self._language)
+ )
+ except Exception: # noqa: BLE001 -- local TTS fallback runs below
+ log.warning(
+ "realtime[%s] direct-tool result speech retry failed",
+ self.session_id,
+ exc_info=True,
+ )
+ return False
+ return True
+
+ # A tool may have succeeded without a retained result only through a
+ # legacy/custom bridge. Never replay that side-effecting user request.
+ if self._executed_tool_names:
+ from jarvis.voice.action_phrases import action_phrase
+
+ fallback_text = action_phrase("cu_done", self._language)
+ self._output_transcript.append(fallback_text)
+ await self._send_json(
+ {
+ "type": "error_spoken",
+ "text": fallback_text,
+ "language": self._language,
+ }
+ )
+ return False
+ if self._brain is None:
+ fallback_text = self._gate.fallback_phrase()
+ self._output_transcript.append(fallback_text)
+ await self._send_json(
+ {
+ "type": "error_spoken",
+ "text": fallback_text,
+ "language": self._language,
+ }
+ )
+ return False
+
+ self._delegate_required_for_turn = True
+ turn_state = _DelegateTurnState(
+ deterministic=True,
+ provider_boundary_seen=True,
+ user_text=self._last_user_text,
+ )
+ # The empty response.done event is itself the input and provider
+ # boundary. Pre-setting both events lets automatic-response adapters
+ # use the same deterministic delegate machinery as manual providers.
+ turn_state.input_boundary_ready.set()
+ turn_state.provider_ready.set()
+ self._delegate_turns[turn_id] = turn_state
+ log.warning(
+ "realtime[%s] provider completed turn %s without text, audio, or "
+ "tool evidence; recovering through the Brain chain",
+ self.session_id,
+ turn_id,
+ )
+ self._start_deterministic_delegate(self._last_user_text)
+ return True
+
+ def _direct_tool_fallback_text(self) -> tuple[str, bool]:
+ """Return one speakable result without serializing raw tool payloads."""
+ from jarvis.voice.action_phrases import action_phrase
+
+ _name, result = self._direct_tool_results[-1]
+ succeeded = bool(result.get("success"))
+ output = result.get("output")
+ candidates = [
+ result.get("spoken_reply"),
+ ]
+ if result.get("confirmation_required"):
+ # This question is produced by the localized confirmation layer,
+ # not arbitrary tool output, and must remain actionable.
+ candidates.append(result.get("message"))
+ if isinstance(output, dict):
+ candidates.append(output.get("spoken_reply"))
+ for candidate in candidates:
+ if not isinstance(candidate, str) or not candidate.strip():
+ continue
+ cleaned = scrub_for_voice(
+ candidate,
+ language=self._language,
+ ).cleaned.strip()
+ if cleaned:
+ return cleaned, succeeded
+ phrase_key = "cu_done" if succeeded else "action_failed_generic"
+ return action_phrase(phrase_key, self._language), succeeded
+
async def _begin_user_speech_turn(self) -> None:
"""Close an interrupted reply before the next transcript opens a turn."""
self._drop_provider_output_until_new_response = True
@@ -1708,6 +1937,7 @@ class RealtimeVoiceSession:
self._output_transcript.clear()
self._provider_output_probe = ""
self._executed_tool_names.clear()
+ self._direct_tool_results.clear()
self._turn_final_text = ""
self._delegate_required_for_turn = False
self._deferred_provider_speech_start = False
@@ -2078,6 +2308,7 @@ class RealtimeVoiceSession:
}
if result.get("success"):
self._executed_tool_names.add(original_name)
+ self._direct_tool_results.append((original_name, dict(result)))
self._mark_latency_named(
"REALTIME_TOOL_COMPLETED",
detail=(
@@ -2389,7 +2620,11 @@ class RealtimeVoiceSession:
exc_info=True,
)
await self._send_json(
- {"type": "error_spoken", "text": turn_state.last_reply}
+ {
+ "type": "error_spoken",
+ "text": turn_state.last_reply,
+ "language": self._language,
+ }
)
def _start_delegate(
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index ab15d8c13c..a795bcd8bc 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -6165,9 +6165,45 @@ class SpeechPipeline:
and not interrupted_during_drain
):
turn_complete.set()
- elif kind in {"provider_error", "error_spoken"}:
- if kind == "error_spoken":
- semantic_turn_committed = True
+ elif kind == "error_spoken":
+ semantic_turn_committed = True
+ text = str(message.get("text", "") or "").strip()
+ language = _phrase_lang(
+ str(message.get("language", "") or "")
+ or self._output_language(None, text)
+ )
+ scrubbed = scrub_for_voice(text, language=language)
+ cleaned = scrubbed.cleaned.strip()
+ if cleaned and not getattr(self, "_muted", False):
+ # Realtime has already failed to render this grounded text.
+ # Use the configured classic TTS + the same AudioPlayer as
+ # an independent last mile. The existing mic pump and local
+ # barge detector remain active, so this does not open a
+ # second microphone or replay the user's request.
+ await playback.cancel()
+ speaking = True
+ barge_detector.start_output()
+ await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
+ try:
+ lang_code = self._bcp47(language)
+ try:
+ chunks = self._tts.synthesize(
+ cleaned,
+ language_code=lang_code,
+ )
+ except TypeError:
+ chunks = self._tts.synthesize(cleaned)
+ await self._player.play_chunks(chunks)
+ except Exception as exc: # noqa: BLE001 -- final voice fallback
+ log.warning(
+ "Realtime surface TTS fallback failed: %s",
+ exc,
+ )
+ finally:
+ speaking = False
+ barge_detector.stop_output()
+ await self._set_turn_state(TurnTakingState.LISTENING)
+ elif kind == "provider_error":
log.warning("Realtime desktop status: %s", message)
# Open the microphone BEFORE building the realtime session AND before
diff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.py
index 85c62b1918..d40a0bc80b 100644
--- a/tests/unit/realtime/test_openai_realtime.py
+++ b/tests/unit/realtime/test_openai_realtime.py
@@ -525,6 +525,55 @@ async def test_runtime_errors_preserve_provider_recoverability(
await session.close()
+async def test_failed_response_done_is_reported_before_turn_completion(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ holder = _patch_openai_client(monkeypatch)
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig()
+ )
+ conn = holder["client"].realtime.last_conn
+
+ await session.request_response()
+ marker = conn.response_create_payloads[0]["response"]["metadata"][
+ "jarvis_request_id"
+ ]
+ conn._events = iter(
+ [
+ SimpleNamespace(
+ type="response.created",
+ response=SimpleNamespace(
+ id="resp-failed",
+ metadata={"jarvis_request_id": marker},
+ ),
+ ),
+ SimpleNamespace(
+ type="response.done",
+ response=SimpleNamespace(
+ id="resp-failed",
+ status="failed",
+ status_details=SimpleNamespace(
+ error=SimpleNamespace(
+ code="server_error",
+ message="The response could not be generated.",
+ )
+ ),
+ ),
+ ),
+ ]
+ )
+ session._events = conn.__aiter__()
+
+ events = [event async for event in session.receive()]
+
+ assert [event.type for event in events] == ["error", "turn_complete"]
+ assert events[0].recoverable is True
+ assert "failed" in str(events[0].error)
+ assert "server_error" in str(events[0].error)
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_response_requests_wait_for_the_active_response_boundary(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index c5acf847f2..77705ae40e 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -2486,6 +2486,250 @@ async def test_direct_mode_builds_bridge_from_brain(wire_supervisor_gateway):
assert "jarvis_action" not in names
+async def test_direct_mode_recovers_provider_turn_that_has_no_output():
+ """A substantive user turn must never complete as successful silence."""
+ user_text = "I am bored. What could we do?"
+ recovered_reply = "We could build a tiny game together."
+ spoken_audio = AudioChunk(
+ pcm=b"\x01\x02" * 8,
+ sample_rate=24_000,
+ timestamp_ns=0,
+ )
+ brain = FakeBrain(replies=(recovered_reply,))
+ provider = AutomaticDelegateProvider(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text=user_text,
+ is_final=True,
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ],
+ [
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text=recovered_reply,
+ is_final=True,
+ ),
+ RealtimeEvent(type="audio_delta", audio=spoken_audio),
+ RealtimeEvent(type="turn_complete"),
+ ],
+ )
+ jsons: list[dict] = []
+ binaries: list[bytes] = []
+ bus = FakeBus()
+ sess = _session(
+ provider,
+ brain=brain,
+ tool_mode="direct",
+ jsons=jsons,
+ binaries=binaries,
+ bus=bus,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await asyncio.wait_for(sess.wait_finished(), timeout=2)
+
+ assert [call[0] for call in brain.calls] == [user_text]
+ assert len(provider.session.text_inputs) == 1
+ assert "<trusted_action_result>" in provider.session.text_inputs[0]
+ assert binaries == [spoken_audio.pcm]
+ assert sum(item.get("type") == "turn_complete" for item in jsons) == 1
+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]
+ assert len(completed) == 1
+ assert completed[0].jarvis_text == recovered_reply
+ await sess.end(reason="test")
+
+
+async def test_text_only_provider_answer_uses_surface_tts_without_brain_retry():
+ """An audio-mode response with text but zero PCM is not treated as spoken."""
+ answer = "Here is something useful for you."
+ brain = FakeBrain()
+ provider = FakeProvider(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="Tell me something useful.",
+ is_final=True,
+ ),
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text=answer,
+ is_final=True,
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ jsons: list[dict] = []
+ bus = FakeBus()
+ sess = _session(
+ provider,
+ brain=brain,
+ tool_mode="direct",
+ jsons=jsons,
+ bus=bus,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+
+ assert brain.calls == []
+ assert {"type": "error_spoken", "text": answer, "language": "en"} in jsons
+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]
+ assert len(completed) == 1
+ assert completed[0].jarvis_text == answer
+ await sess.end(reason="test")
+
+
+async def test_empty_provider_turn_without_brain_speaks_local_error():
+ """A keyless fallback chain still closes the turn honestly, never silently."""
+ provider = FakeProvider(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="Tell me something useful.",
+ is_final=True,
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ jsons: list[dict] = []
+ bus = FakeBus()
+ sess = _session(
+ provider,
+ brain=None,
+ tool_mode="direct",
+ jsons=jsons,
+ bus=bus,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+
+ fallback = "An error occurred."
+ assert {"type": "error_spoken", "text": fallback, "language": "en"} in jsons
+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]
+ assert len(completed) == 1
+ assert completed[0].jarvis_text == fallback
+ await sess.end(reason="test")
+
+
+async def test_empty_recovery_response_uses_surface_tts_without_rerunning_brain():
+ """A second provider failure speaks the grounded result through local TTS."""
+ user_text = "I am bored. What could we do?"
+ recovered_reply = "We could build a tiny game together."
+ brain = FakeBrain(replies=(recovered_reply,))
+ provider = AutomaticDelegateProvider(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text=user_text,
+ is_final=True,
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ],
+ [RealtimeEvent(type="turn_complete")],
+ )
+ jsons: list[dict] = []
+ bus = FakeBus()
+ sess = _session(
+ provider,
+ brain=brain,
+ tool_mode="direct",
+ jsons=jsons,
+ bus=bus,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ 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
+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]
+ assert len(completed) == 1
+ assert completed[0].jarvis_text == recovered_reply
+ await sess.end(reason="test")
+
+
+async def test_direct_tool_empty_response_reuses_result_without_repeating_action():
+ """A completed tool is rendered again; the user request is never replayed."""
+ spoken_audio = AudioChunk(
+ pcm=b"\x03\x04" * 8,
+ sample_rate=24_000,
+ timestamp_ns=0,
+ )
+ tool_result_sent = asyncio.Event()
+ retry_sent = asyncio.Event()
+
+ class _DirectToolRecoverySession(FakeSession):
+ async def receive(self):
+ yield RealtimeEvent(
+ type="input_transcript",
+ text="Open the calculator.",
+ is_final=True,
+ )
+ yield RealtimeEvent(
+ type="tool_call",
+ call_id="direct-empty-1",
+ tool_name="open_app",
+ tool_args={"app_name": "Calculator"},
+ )
+ await tool_result_sent.wait()
+ yield RealtimeEvent(type="turn_complete")
+ await retry_sent.wait()
+ yield RealtimeEvent(
+ type="output_transcript_delta",
+ text="The calculator is open.",
+ )
+ yield RealtimeEvent(type="audio_delta", audio=spoken_audio)
+ yield RealtimeEvent(type="turn_complete")
+
+ async def send_tool_result(self, call_id, name, result):
+ await super().send_tool_result(call_id, name, result)
+ tool_result_sent.set()
+
+ async def send_text(self, text):
+ await super().send_text(text)
+ retry_sent.set()
+
+ class _DirectToolRecoveryProvider(FakeProvider):
+ async def open_session(self, cfg):
+ self.opened_with = cfg
+ self.session = _DirectToolRecoverySession([])
+ return self.session
+
+ brain = FakeBrain()
+ tool_bridge = FakeToolBridge()
+ provider = _DirectToolRecoveryProvider([])
+ binaries: list[bytes] = []
+ sess = _session(
+ provider,
+ brain=brain,
+ tool_bridge=tool_bridge,
+ tool_mode="direct",
+ binaries=binaries,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await asyncio.wait_for(sess.wait_finished(), timeout=2)
+
+ assert tool_bridge.calls == [("open_app", {"app_name": "Calculator"})]
+ assert brain.calls == []
+ assert len(provider.session.text_inputs) == 1
+ assert "do not repeat the action" in provider.session.text_inputs[0]
+ assert binaries == [spoken_audio.pcm]
+ await sess.end(reason="test")
+
+
@pytest.mark.asyncio
async def test_direct_mode_pushes_live_brain_tool_replacements_to_provider(
wire_supervisor_gateway,
@@ -2697,7 +2941,11 @@ 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")} in jsons
+ assert {
+ "type": "error_spoken",
+ "text": action_not_started_phrase("en"),
+ "language": "en",
+ } in jsons
await sess.end(reason="test")
@@ -3049,9 +3297,10 @@ async def test_delegate_timeout_cancels_brain_and_cannot_publish_late(monkeypatc
@pytest.mark.asyncio
-async def test_delegate_empty_spoken_answer_uses_one_internal_reply_fallback():
+async def test_delegate_empty_spoken_answer_uses_surface_tts_fallback():
bus = FakeBus()
brain = FakeBrain(replies=("The action completed.",), bus=bus)
+ jsons: list[dict] = []
provider = ToolResultGatedProvider(
[
RealtimeEvent(type="input_transcript", text="do it", is_final=True),
@@ -3064,7 +3313,7 @@ async def test_delegate_empty_spoken_answer_uses_one_internal_reply_fallback():
],
[RealtimeEvent(type="turn_complete")],
)
- sess = _session(provider, brain=brain, bus=bus)
+ sess = _session(provider, brain=brain, bus=bus, jsons=jsons)
await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
await sess.wait_finished()
@@ -3072,7 +3321,12 @@ async def test_delegate_empty_spoken_answer_uses_one_internal_reply_fallback():
responses = [event for event in bus.events if isinstance(event, ResponseGenerated)]
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 == ""
+ assert completed.jarvis_text == "The action completed."
+ assert {
+ "type": "error_spoken",
+ "text": "The action completed.",
+ "language": "en",
+ } in jsons
await sess.end(reason="test")
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index dfbf5bce64..53cdeac671 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -33,6 +33,20 @@ class _FakePlayer:
self.stopped += 1
+class _FakeTTS:
+ def __init__(self, pcm: bytes) -> None:
+ self.pcm = pcm
+ self.calls: list[tuple[str, str | None]] = []
+
+ def synthesize(self, text: str, *, language_code: str | None = None):
+ self.calls.append((text, language_code))
+
+ async def _chunks():
+ yield AudioChunk(pcm=self.pcm, sample_rate=24_000, timestamp_ns=0)
+
+ return _chunks()
+
+
class _SilentMic:
async def __aenter__(self):
return self
@@ -281,6 +295,8 @@ async def test_unsafe_output_cancel_stops_playback_and_returns_to_listening(
monkeypatch: pytest.MonkeyPatch,
) -> None:
pipe = _pipe()
+ fallback_pcm = b"\x06\x00" * 32
+ pipe._tts = _FakeTTS(fallback_pcm)
cancel_delivered = asyncio.Event()
built: dict[str, object] = {}
@@ -313,6 +329,8 @@ async def test_unsafe_output_cancel_stops_playback_and_returns_to_listening(
await asyncio.sleep(0)
assert pipe._player.stopped >= 1
+ assert fallback_pcm in pipe._player.pcm
+ assert pipe._tts.calls == [("An error occurred.", "en-US")]
assert pipe._test_states[-2:] == [
pipeline_mod.TurnTakingState.JARVIS_SPEAKING,
pipeline_mod.TurnTakingState.LISTENING,