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): keep the next answer alive after a response is retired

rubenluetke10-beep3118ec33491d
diff --git a/tests/unit/realtime/test_session_response_identity_recovery.py b/tests/unit/realtime/test_session_response_identity_recovery.py
new file mode 100644
index 0000000000..da430c08b3
--- /dev/null
+++ b/tests/unit/realtime/test_session_response_identity_recovery.py
@@ -0,0 +1,260 @@
+"""Response-identity recovery: a superseded response never kills the next one.
+
+Two pinned regressions around ``_active_provider_response_id``:
+
+* ``_reset_output_state`` retires the active provider response on every path
+ that ends one — including the half-duplex emergency release, where no
+ provider boundary ever arrived and the scrub gate is still bound
+ fail-closed to the dead response. Leaving that binding standing made the
+ NEXT response's ``begin_response`` read as a ``response_identity_mismatch``
+ hard leak, cancelling the real answer into the generic fallback phrase.
+
+* In ``_accept_provider_response_event``'s identity-mismatch path,
+ ``_cancel_unsafe_output`` armed ``_drop_provider_output_until_new_response``
+ for the STALE identity, and on adapters without
+ ``isolates_response_generations`` nothing ever cleared it: the superseding
+ response's own audio and transcript were withheld, contradicting the
+ branch's clean-start promise. Only events of the CANCELLED id may stay
+ dropped (via the completed-ids ledger).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.core.protocols import AudioChunk
+from jarvis.realtime.protocol import RealtimeEvent
+from jarvis.realtime.session import RealtimeVoiceSession
+
+TIMEOUT_S = 5.0
+RATE = 24_000
+A_PCM = b"\x01\x02" * 160 # int16 peak 513, above the silence floor
+A_LATE_PCM = b"\x05\x06" * 160 # late audio of the cancelled identity
+B_PCM = b"\x03\x04" * 160 # the superseding response's audio
+
+
+class _ScriptedWire:
+ session_id = "identity-recovery-wire"
+ supports_tool_updates = True
+ creates_responses_automatically = False
+ # Deliberately False: the withhold-release contract must hold on EVERY
+ # adapter, not only ones that isolate response generations.
+ isolates_response_generations = False
+
+ def __init__(self, events: list[RealtimeEvent]) -> None:
+ self._events = events
+
+ async def receive(self): # noqa: ANN201 - async generator, protocol shape
+ for event in self._events:
+ yield event
+ await asyncio.sleep(0)
+
+ async def send_audio(self, chunk: Any) -> None:
+ del chunk
+
+ async def update_session(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def request_response(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def send_text(self, text: str) -> None:
+ del text
+
+ async def truncate(self, audio_end_ms: int) -> None:
+ del audio_end_ms
+
+ async def interrupt(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def send_tool_result(self, *args: Any) -> None:
+ del args
+
+ async def close(self) -> None:
+ return None
+
+
+class _Provider:
+ name = "scripted"
+ supports_realtime = True
+ input_sample_rate = RATE
+ output_sample_rate = RATE
+
+ def __init__(self, events: list[RealtimeEvent]) -> None:
+ self._events = events
+
+ async def can_open_duplex_session(self) -> bool:
+ return True
+
+ async def open_session(self, config: Any) -> _ScriptedWire:
+ del config
+ return _ScriptedWire(self._events)
+
+
+class _RecordingGate:
+ """Fake scrub gate recording its lifecycle calls (fakes, not mocks)."""
+
+ def __init__(self, response_id: str = "") -> None:
+ self.response_id = response_id
+ self.calls: list[Any] = []
+
+ def drain(self) -> None:
+ self.calls.append("drain")
+ self.response_id = ""
+
+ def begin_response(self, response_id: str = "") -> bool:
+ self.calls.append(("begin", response_id))
+ return True
+
+
+def _config() -> SimpleNamespace:
+ return SimpleNamespace(
+ brain=SimpleNamespace(reply_language="en", providers={}),
+ stt=SimpleNamespace(language="auto"),
+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),
+ latency=SimpleNamespace(enabled=False),
+ )
+
+
+def _session(
+ events: list[RealtimeEvent] | None = None,
+ binaries: list[bytes] | None = None,
+ messages: list[dict[str, Any]] | None = None,
+) -> RealtimeVoiceSession:
+ async def _collect_binary(data: bytes) -> None:
+ if binaries is not None:
+ binaries.append(bytes(data))
+
+ async def _collect_json(message: dict[str, Any]) -> None:
+ if messages is not None:
+ messages.append(dict(message))
+
+ return RealtimeVoiceSession(
+ session_id="identity-recovery",
+ send_binary=_collect_binary,
+ send_json=_collect_json,
+ providers=[_Provider(events or [])],
+ config=_config(),
+ bus=None,
+ surface="desktop",
+ half_duplex=True,
+ browser_sample_rate=RATE,
+ )
+
+
+def _audio_event(response_id: str, pcm: bytes = A_PCM) -> RealtimeEvent:
+ return RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(pcm=pcm, sample_rate=RATE, timestamp_ns=0),
+ provider_turn_id=response_id,
+ )
+
+
+async def test_output_reset_unbinds_the_gate_from_the_retired_response() -> (
+ None
+):
+ """Mute release with no boundary: the next response must start clean."""
+ session = _session()
+ assert await session._accept_provider_response_event(
+ _audio_event("resp-a")
+ )
+ assert session._gate.response_id == "resp-a"
+
+ # No provider boundary ever arrives; the half-duplex emergency release
+ # (or any other end-of-response path) resets the output state.
+ session._reset_output_state(reason="half-duplex mute outlived its turn")
+
+ assert session._gate.response_id == "", (
+ "the retired response may not keep owning the scrub gate"
+ )
+ assert await session._accept_provider_response_event(
+ _audio_event("resp-b")
+ ), "the next response must be accepted, not read as an identity leak"
+ assert not session._gate.hard_leak_pending()
+ assert session._response_identity_drops == 0
+ assert session._scrub_cancelled_for_turn is False
+
+
+def test_output_reset_drains_only_a_bound_gate() -> None:
+ session = _session()
+
+ bound = _RecordingGate("resp-a")
+ session._gate = bound # type: ignore[assignment]
+ session._active_provider_response_id = "resp-a"
+ session._reset_output_state(reason="test: bound gate")
+ assert "drain" in bound.calls
+ assert bound.response_id == ""
+
+ unbound = _RecordingGate("")
+ session._gate = unbound # type: ignore[assignment]
+ session._reset_output_state(reason="test: unbound gate")
+ assert unbound.calls == [], (
+ "an unbound gate keeps its state (direct-speech clearance and all); "
+ "reset has nothing to end there"
+ )
+
+
+async def test_a_superseding_response_flows_after_the_stale_one_is_cancelled() -> ( # noqa: E501
+ None
+):
+ """Response B supersedes A without a boundary: B's audio must play."""
+ binaries: list[bytes] = []
+ messages: list[dict[str, Any]] = []
+ events = [
+ RealtimeEvent(
+ type="input_transcript",
+ text="Hello how are you",
+ is_final=True,
+ item_id="turn-1",
+ ),
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="Answer A.",
+ provider_turn_id="resp-a",
+ ),
+ _audio_event("resp-a", A_PCM),
+ # Identity changes with no boundary for resp-a: this first mismatched
+ # event is dropped and resp-a is cancelled once.
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="Answer B instead.",
+ provider_turn_id="resp-b",
+ ),
+ # Late audio of the CANCELLED identity stays dropped.
+ _audio_event("resp-a", A_LATE_PCM),
+ # The superseding response's own audio and transcript must flow.
+ _audio_event("resp-b", B_PCM),
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="Answer B instead.",
+ provider_turn_id="resp-b",
+ ),
+ RealtimeEvent(type="turn_complete", provider_turn_id="resp-b"),
+ ]
+ session = _session(events, binaries, messages)
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": RATE}),
+ TIMEOUT_S,
+ )
+ await asyncio.wait_for(session.wait_finished(), TIMEOUT_S)
+ await asyncio.wait_for(session.end(reason="test"), TIMEOUT_S)
+
+ assert B_PCM in binaries, (
+ "the superseding response's audio was withheld — the drop armed for "
+ "the cancelled identity must not silence the new one"
+ )
+ assert A_LATE_PCM not in binaries, (
+ "late audio of the cancelled identity must stay dropped"
+ )
+ assert any(
+ message.get("type") == "transcript"
+ and message.get("role") == "assistant"
+ and "Answer B" in str(message.get("text") or "")
+ for message in messages
+ ), "the superseding response's transcript must reach the surface"
+ cancels = [m for m in messages if m.get("type") == "tts_cancel"]
+ assert len(cancels) == 1, (
+ "exactly one cancel: the stale identity, never the superseding one"
+ )
diff --git a/tests/unit/realtime/test_session_toolless_vocab_resolution.py b/tests/unit/realtime/test_session_toolless_vocab_resolution.py
new file mode 100644
index 0000000000..f1be9d748d
--- /dev/null
+++ b/tests/unit/realtime/test_session_toolless_vocab_resolution.py
@@ -0,0 +1,70 @@
+"""The tool-less delegation tie-break degrades instead of killing the pump.
+
+``_toolless_ambiguous_action`` reuses FIVE private names from
+``jarvis.brain.turn_planner`` (``_normalize`` plus four suppressor regexes) so
+no second, drifting copy of that vocabulary lives in the session. Private
+names are another module's internals: a rename there used to raise
+``AttributeError`` at import time — or, once resolved lazily, inside the event
+pump at the first user final, which kills the live call.
+
+Pinned here: the names are resolved defensively per call, a missing one
+disables the tie-break (ambiguous finals stay on the plain planner path) and
+warns exactly ONCE, and the fully-present vocabulary still decides as before.
+"""
+
+from __future__ import annotations
+
+import logging
+
+import pytest
+
+from jarvis.realtime import session as session_module
+
+# A tasking phrase whose verb sits OUTSIDE the planner's action vocabulary —
+# exactly the shape the tie-break exists to delegate.
+AMBIGUOUS_ACTION = "Can you take care of that for me"
+
+
[email protected](autouse=True)
+def _reset_vocab_warning() -> None:
+ """The one-shot warning latch is module state — unlatch it per test."""
+ session_module._toolless_vocab_warning_emitted = False
+ yield
+ session_module._toolless_vocab_warning_emitted = False
+
+
+def test_the_full_vocabulary_still_decides() -> None:
+ assert session_module._toolless_ambiguous_action(AMBIGUOUS_ACTION) is True
+ assert session_module._resolve_toolless_vocab() is not None
+
+
[email protected]("missing", session_module._TOOLLESS_VOCAB_NAMES)
+def test_a_missing_planner_name_degrades_to_the_planner_path(
+ missing: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Any renamed private name: no raise, no delegation, plain path."""
+ monkeypatch.delattr(session_module._planner_vocab, missing)
+
+ assert session_module._resolve_toolless_vocab() is None
+ assert session_module._toolless_ambiguous_action(AMBIGUOUS_ACTION) is False
+
+
+def test_the_missing_name_warning_is_emitted_once(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.delattr(session_module._planner_vocab, "_OPINION_RE")
+
+ with caplog.at_level(logging.WARNING, logger=session_module.log.name):
+ for _ in range(3):
+ assert (
+ session_module._toolless_ambiguous_action(AMBIGUOUS_ACTION)
+ is False
+ )
+
+ warnings = [
+ record
+ for record in caplog.records
+ if "turn_planner no longer exposes" in record.getMessage()
+ ]
+ assert len(warnings) == 1, "the degradation notice must not spam the log"
+ assert "_OPINION_RE" in warnings[0].getMessage()