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): seed the call transcript into rebuilt provider transports (BUG-088)

Ruben Lütke20f7092a8594
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 965900f01e..58b4d9d348 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -6013,3 +6013,57 @@ is already stable. (3) Pipeline the surface-TTS chunk synthesis ahead of
playback (prefetch N+1 while N plays) so playback can never starve.
(4) Keep the Live transport's keepalive fed during long surface-TTS
playback so the session does not die underneath a healthy call.
+
+## BUG-088: Realtime voice answers follow-ups with total amnesia after an in-place transport rebuild — the fresh provider session starts with an empty conversation (HIGH, FIXED 2026-07-18)
+
+**Symptom.** Mid-call, the realtime voice suddenly stops understanding
+conversational context: a follow-up that plainly depends on earlier turns is
+answered as if the call had just started. Live case (2026-07-18, the same
+session as BUG-086/087): turn 4 discussed the "best and hardest programming
+language to learn"; at 17:14:07 the idle Live websocket died (`1006`,
+keepalive ping timeout) and the BUG-071 in-place rebuild recovered the
+transport in ~2 s; the next user turn — "what is the hardest language in the
+world?" — was answered with natural languages, because for the model the
+question WAS the first turn of a brand-new conversation. The maintainer's
+verdict "he just doesn't get the context, Gemini Live by itself wouldn't do
+this" is literally accurate: raw Gemini Live keeps context per connection —
+it was OUR rebuild that silently replaced the connection.
+
+**Root cause.** Realtime providers hold the conversation server-side, scoped
+to one WebSocket connection. The BUG-064/071/085 transport-rebuild stack
+(deliberately) reopens a fresh connection mid-call — Gemini's Live sessions
+die routinely (GoAway session limits, 1008, idle 1006; four rebuilds in the
+2026-07-18 desktop log alone), so mid-call context loss was not an edge
+case but the EXPECTED cost of every rebuild ("In-provider conversation
+history is lost" was documented as acceptable). The orchestrator-side
+bounded call transcript (`_delegate_history`) survived every rebuild — it
+just was never given to the fresh provider session.
+
+**Fix (provider-neutral seed, capability-gated — AP-21).**
+`RealtimeSessionConfig.history` now carries the bounded call transcript
+(oldest-first `{"role", "text"}` mappings, derived from the same
+`_delegate_history` that grounds delegated Brain turns, so the native model
+and the delegate see ONE consistent view of the call). `_open()` fills it on
+every open: empty at call start, populated at every mid-call reopen
+(in-place rebuild AND cross-family fallback). Adapters restore it through
+their native channel:
+
+- **gemini-live** replays it right after connect via
+ `send_client_content(turns=…, turn_complete=False)` — Gemini's documented
+ initial-history channel; no response generation is triggered.
+- **openai-realtime** recreates it as `conversation.item.create` messages
+ after the handshake, and its provider-internal BUG-064 rebuild replays the
+ orchestrator's LATEST snapshot, kept current after every completed turn
+ through the optional `set_history_snapshot` capability (probed with
+ `getattr`, never required — third-party adapters are untouched).
+
+All seeding fails OPEN: a seeding error degrades to exactly the pre-fix
+amnesiac-but-alive session, never a dead call.
+
+**Guards.**
+`tests/unit/realtime/test_session.py::test_transport_rebuild_seeds_the_call_history_into_the_fresh_session`
+(+ `…::test_completed_turns_refresh_the_session_history_snapshot`),
+`tests/unit/realtime/test_gemini_live.py::test_open_session_seeds_prior_call_history`
+(+ no-history / seeding-failure cases),
+`tests/unit/realtime/test_openai_realtime.py::test_open_session_seeds_prior_call_history`
+(+ `…::test_transport_rebuild_replays_the_current_history_snapshot`).
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.py
index 9bbe4d562a..b890e447b2 100644
--- a/jarvis/plugins/realtime/gemini_live.py
+++ b/jarvis/plugins/realtime/gemini_live.py
@@ -271,6 +271,49 @@ class _GeminiLiveSession:
log.debug("gemini-live: client close raised", exc_info=True)
+async def _seed_history(session: Any, history: tuple[dict[str, str], ...]) -> None:
+ """Restore the call transcript into a freshly connected Live session.
+
+ Gemini fixes conversation state per connection: a mid-call transport
+ rebuild (session limit GoAway, 1006 abnormal closure) used to start the
+ fresh session with total amnesia, so follow-up questions lost their
+ grounding (BUG-088). ``send_client_content`` with ``turn_complete=False``
+ is Gemini's documented initial-history channel — it appends context
+ without triggering a response generation. Seeding fails open: a session
+ without history is exactly today's behavior and strictly better than no
+ session at all.
+ """
+ if not history:
+ return
+ from google.genai import types # lazy (AP-26)
+
+ turns = []
+ for message in history:
+ if not isinstance(message, dict):
+ continue
+ role = str(message.get("role", "") or "")
+ text = str(message.get("text", "") or "").strip()
+ if not text or role not in {"user", "assistant"}:
+ continue
+ turns.append(
+ types.Content(
+ role="user" if role == "user" else "model",
+ parts=[types.Part(text=text)],
+ )
+ )
+ if not turns:
+ return
+ try:
+ await session.send_client_content(turns=turns, turn_complete=False)
+ except Exception: # noqa: BLE001 — an amnesiac session beats a dead call
+ log.warning(
+ "gemini-live: seeding %d prior turns into the fresh session "
+ "failed; the conversation continues without in-call context",
+ len(turns),
+ exc_info=True,
+ )
+
+
# Gemini function_declarations accept only an OpenAPI-style schema subset.
# Standard JSON-schema keys like additionalProperties, $ref/$defs, or
# oneOf/anyOf/allOf make the handshake fail — which silently drops the whole
@@ -415,6 +458,7 @@ class GeminiLiveProvider:
if hasattr(result, "__await__"):
await result
raise
+ await _seed_history(session, tuple(getattr(cfg, "history", ()) or ()))
return _GeminiLiveSession(
session=session,
connection_cm=connection_cm,
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index 29eaccb3bd..deedcd3a2f 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -119,6 +119,19 @@ def _error_code(event: Any) -> str:
return str(getattr(error, "code", "") or "").strip()
+def _normalize_history(history: Any) -> tuple[dict[str, str], ...]:
+ """Keep only well-formed user/assistant text turns from a history seed."""
+ normalized: list[dict[str, str]] = []
+ for message in tuple(history or ()):
+ if not isinstance(message, dict):
+ continue
+ role = str(message.get("role", "") or "")
+ text = str(message.get("text", "") or "").strip()
+ if text and role in {"user", "assistant"}:
+ normalized.append({"role": role, "text": text})
+ return tuple(normalized)
+
+
def _error_message(event: Any) -> str:
error = getattr(event, "error", None)
code = _error_code(event)
@@ -232,6 +245,7 @@ class _OpenAIRealtimeSession:
session_id: str,
session_payload: dict[str, Any] | None = None,
connect_model: str = "",
+ history_seed: tuple[dict[str, str], ...] = (),
) -> None:
self._conn = connection
self._connection_cm = connection_cm
@@ -241,6 +255,12 @@ class _OpenAIRealtimeSession:
# Model the transport was opened with — required to rebuild the
# connection in place when the server goes deaf (BUG-064 escalation).
self._connect_model = str(connect_model or "")
+ # Bounded call transcript for context restoration (BUG-088). Seeded
+ # from the open-time config and kept current by the orchestrator via
+ # set_history_snapshot after every completed turn, so a BUG-064
+ # transport rebuild can hand the fresh connection the conversation
+ # it would otherwise lose entirely.
+ self._history_seed = _normalize_history(history_seed)
self._last_transcript_at = float("-inf")
self._transcript_deadline: float | None = None
self._rebuild_task: asyncio.Task[None] | None = None
@@ -475,6 +495,43 @@ class _OpenAIRealtimeSession:
recoverable=_error_is_recoverable(event),
)
+ def set_history_snapshot(self, history: tuple[dict[str, str], ...]) -> None:
+ """Refresh the transcript a transport rebuild would restore (BUG-088).
+
+ Local state only — never a wire call. The orchestrator pushes the
+ bounded call transcript here after every completed turn.
+ """
+ self._history_seed = _normalize_history(history)
+
+ async def _seed_conversation_history(self, connection: Any) -> None:
+ """Recreate the call transcript as conversation items on a connection.
+
+ Used when a fresh transport replaces one that held the conversation
+ server-side (open with a mid-call seed after a cross-family fallback,
+ or the BUG-064 in-place rebuild). Fails open: an amnesiac session is
+ exactly the pre-BUG-088 behavior and strictly better than no session.
+ """
+ for message in self._history_seed:
+ role = message["role"]
+ content_type = "input_text" if role == "user" else "text"
+ try:
+ await connection.conversation.item.create(
+ item={
+ "type": "message",
+ "role": role,
+ "content": [
+ {"type": content_type, "text": message["text"]}
+ ],
+ }
+ )
+ except Exception: # noqa: BLE001 — degrade to an amnesiac session
+ log.warning(
+ "OpenAI Realtime history seeding failed part-way; the "
+ "session continues with partial in-call context",
+ exc_info=True,
+ )
+ return
+
async def update_session(
self,
*,
@@ -903,6 +960,10 @@ class _OpenAIRealtimeSession:
)
await self.close()
return
+ # Restore the call transcript before any new turn flows (BUG-088):
+ # the dead transport held the conversation server-side, and without
+ # this seed the rebuilt session answers follow-ups with amnesia.
+ await self._seed_conversation_history(connection)
# Swap fully initialized state first; only then retire the old
# transport so send_audio and the receive() hop never observe a
# half-built connection.
@@ -1019,6 +1080,7 @@ class OpenAIRealtimeProvider:
session_id=str(uuid4()),
session_payload=payload,
connect_model=connect_model,
+ history_seed=tuple(getattr(cfg, "history", ()) or ()),
)
try:
await connection.session.update(session=payload)
@@ -1026,4 +1088,8 @@ class OpenAIRealtimeProvider:
except BaseException:
await session.close()
raise
+ # A mid-call open (cross-family fallback after another provider's
+ # transport died) carries the call transcript; restore it so the
+ # conversation survives the provider crossing (BUG-088).
+ await session._seed_conversation_history(connection)
return session
diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.py
index 5babc834cb..53b82fbfdb 100644
--- a/jarvis/realtime/protocol.py
+++ b/jarvis/realtime/protocol.py
@@ -68,11 +68,27 @@ class RealtimeSessionConfig:
# user's turn, so a natural pause cannot start model reasoning early.
silence_duration_ms: int = 1500
tools: tuple[dict[str, Any], ...] = ()
+ # Bounded transcript of the call so far, oldest first, as
+ # ``{"role": "user" | "assistant", "text": ...}`` mappings. A fresh
+ # transport opened MID-CALL (in-place rebuild after a provider disconnect,
+ # or a cross-family fallback) starts with an empty server-side
+ # conversation; seeding this history restores the context the model
+ # needs to understand follow-up turns (BUG-088). Empty at the first open
+ # of a call. Providers that cannot inject history ignore it.
+ history: tuple[dict[str, str], ...] = ()
@runtime_checkable
class RealtimeSession(Protocol):
- """A live duplex handle (one connection)."""
+ """A live duplex handle (one connection).
+
+ Optional capability (probed with ``getattr``, never required): a session
+ that can seed conversation history into a rebuilt transport may expose
+ ``set_history_snapshot(history: tuple[dict[str, str], ...]) -> None``.
+ The orchestrator calls it with the current bounded call transcript after
+ every completed turn so a provider-internal transport rebuild (e.g. the
+ openai_realtime BUG-064 stack) can restore context without a wire call.
+ """
session_id: str
creates_responses_automatically: bool
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 2f98dd5e03..34f8090e12 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -957,6 +957,11 @@ class RealtimeVoiceSession:
modalities=("audio",),
silence_duration_ms=_configured_thinking_pause_ms(self._config),
tools=self._declared_tools(),
+ # Empty at the first open of a call; after an in-place
+ # transport rebuild (or a mid-call cross-family fallback) it
+ # carries the bounded call transcript so the fresh provider
+ # session keeps understanding follow-up turns (BUG-088).
+ history=self._history_seed(),
)
try:
providers_left = len(self._providers) - index
@@ -2747,6 +2752,32 @@ class RealtimeVoiceSession:
self._delegate_history = self._delegate_history[
-_DELEGATE_HISTORY_MAX_MESSAGES:
]
+ # Keep the provider session's rebuild seed current (BUG-088): an
+ # adapter that self-heals its transport internally (openai_realtime's
+ # BUG-064 stack) restores this snapshot into the fresh connection so
+ # the model keeps the call context. Optional capability, probed —
+ # never a wire call, never required (AP-21).
+ session = self._session
+ set_snapshot = getattr(session, "set_history_snapshot", None)
+ if callable(set_snapshot):
+ try:
+ set_snapshot(self._history_seed())
+ except Exception: # noqa: BLE001, S110 — snapshot is best-effort
+ pass
+
+ def _history_seed(self) -> tuple[dict[str, str], ...]:
+ """The bounded call transcript in provider-neutral seed form.
+
+ Derived from the same ``_delegate_history`` that grounds delegated
+ Brain turns, so both the native voice model (after a transport
+ rebuild) and the delegate see one consistent view of the call.
+ """
+ return tuple(
+ {"role": message.role, "text": str(message.content or "").strip()}
+ for message in self._delegate_history
+ if message.role in {"user", "assistant"}
+ and str(message.content or "").strip()
+ )
def _reset_turn_tracking(self) -> None:
self._turn_id = ""
diff --git a/tests/unit/realtime/test_gemini_live.py b/tests/unit/realtime/test_gemini_live.py
index 490d1ccebc..840ae0fc64 100644
--- a/tests/unit/realtime/test_gemini_live.py
+++ b/tests/unit/realtime/test_gemini_live.py
@@ -478,6 +478,140 @@ async def test_tool_call_suppresses_intermediate_turn_complete() -> None:
assert receive_calls == 3
+# --- BUG-088: conversation-history seeding into a fresh session -------------
+
+
+class _SeedableConnectCM:
+ """Connect CM whose session records send_client_content calls."""
+
+ def __init__(self) -> None:
+ self.exited = False
+ self.client_content_calls: list[dict] = []
+
+ async def _send_client_content(*, turns=None, turn_complete=True):
+ self.client_content_calls.append(
+ {"turns": turns, "turn_complete": turn_complete}
+ )
+
+ self.session = SimpleNamespace(send_client_content=_send_client_content)
+
+ async def __aenter__(self):
+ return self.session
+
+ async def __aexit__(self, *_args):
+ self.exited = True
+
+
+def _patch_seedable_genai_client(monkeypatch: pytest.MonkeyPatch) -> dict:
+ holder: dict = {}
+
+ class _SeedableLiveAPI:
+ def __init__(self) -> None:
+ self.last_cm: _SeedableConnectCM | None = None
+
+ def connect(self, *, model, config):
+ del model, config
+ self.last_cm = _SeedableConnectCM()
+ return self.last_cm
+
+ def _make_client(*, api_key=None):
+ client = SimpleNamespace(
+ api_key=api_key,
+ aio=SimpleNamespace(live=_SeedableLiveAPI()),
+ closed=False,
+ )
+ holder["client"] = client
+ return client
+
+ from google import genai
+
+ monkeypatch.setattr(genai, "Client", _make_client)
+ return holder
+
+
+async def test_open_session_seeds_prior_call_history(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """BUG-088: a mid-call transport rebuild reopens Gemini with a fresh,
+ empty conversation. The open must replay the bounded call transcript via
+ send_client_content(turn_complete=False) — Gemini's initial-history
+ channel — so follow-up questions keep their earlier-turn grounding."""
+ holder = _patch_seedable_genai_client(monkeypatch)
+ await GeminiLiveProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig(
+ history=(
+ {"role": "user", "text": "let's talk programming languages"},
+ {"role": "assistant", "text": "Sure — which one interests you?"},
+ {"role": "user", "text": "what is the hardest language"},
+ )
+ )
+ )
+
+ live = holder["client"].aio.live
+ calls = live.last_cm.client_content_calls
+ assert len(calls) == 1
+ assert calls[0]["turn_complete"] is False
+ turns = calls[0]["turns"]
+ assert [turn.role for turn in turns] == ["user", "model", "user"]
+ assert [turn.parts[0].text for turn in turns] == [
+ "let's talk programming languages",
+ "Sure — which one interests you?",
+ "what is the hardest language",
+ ]
+
+
+async def test_open_session_without_history_sends_no_client_content(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ holder = _patch_seedable_genai_client(monkeypatch)
+ await GeminiLiveProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig()
+ )
+
+ assert holder["client"].aio.live.last_cm.client_content_calls == []
+
+
+async def test_history_seeding_failure_keeps_the_session_alive(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Seeding fails open: an amnesiac session is exactly the pre-BUG-088
+ behavior and strictly better than no session at all."""
+ async def _broken_send_client_content(*, turns=None, turn_complete=True):
+ del turns, turn_complete
+ raise RuntimeError("seed rejected")
+
+ class _BrokenSeedCM:
+ async def __aenter__(self):
+ return SimpleNamespace(
+ send_client_content=_broken_send_client_content
+ )
+
+ async def __aexit__(self, *_args):
+ return None
+
+ def _make_client(*, api_key=None):
+ return SimpleNamespace(
+ api_key=api_key,
+ aio=SimpleNamespace(
+ live=SimpleNamespace(
+ connect=lambda *, model, config: _BrokenSeedCM()
+ )
+ ),
+ )
+
+ from google import genai
+
+ monkeypatch.setattr(genai, "Client", _make_client)
+ session = await GeminiLiveProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig(history=({"role": "user", "text": "hello"},))
+ )
+
+ assert session is not None
+
+
# --- function_declarations schema sanitizing --------------------------------
diff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.py
index ff973f8928..cc4b7f1e90 100644
--- a/tests/unit/realtime/test_openai_realtime.py
+++ b/tests/unit/realtime/test_openai_realtime.py
@@ -186,6 +186,104 @@ async def test_text_update_creates_tool_free_audio_response(
await session.close()
+async def test_open_session_seeds_prior_call_history(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """BUG-088: a mid-call open (cross-family fallback after another
+ provider's transport died) carries the call transcript; the adapter must
+ recreate it as conversation items so the model keeps the context."""
+ holder = _patch_openai_client(monkeypatch)
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig(
+ history=(
+ {"role": "user", "text": "let's talk programming languages"},
+ {"role": "assistant", "text": "Sure — which one?"},
+ )
+ )
+ )
+ conn = holder["client"].realtime.last_conn
+
+ assert conn.created_items == [
+ {
+ "type": "message",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "let's talk programming languages",
+ }
+ ],
+ },
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "text", "text": "Sure — which one?"}],
+ },
+ ]
+ await session.close()
+
+
+async def test_transport_rebuild_replays_the_current_history_snapshot(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """BUG-088 x BUG-064: the in-place transport rebuild replaces the
+ connection that held the conversation server-side. The rebuilt transport
+ must receive the orchestrator's latest history snapshot — not the (empty)
+ open-time seed — so the call continues with context."""
+ holder = _patch_openai_client(monkeypatch)
+ monkeypatch.setattr(openai_realtime, "_TRANSCRIPT_OVERDUE_S", 0.0)
+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig(model="gpt-realtime")
+ )
+ session.set_history_snapshot(
+ (
+ {"role": "user", "text": "let's talk programming languages"},
+ {"role": "assistant", "text": "Sure — which one?"},
+ {"role": "ignored-role", "text": "dropped"},
+ {"role": "user", "text": " "},
+ )
+ )
+ api = holder["client"].realtime
+ conn1 = api.last_conn
+ conn2 = _FakeConn()
+ conn2._events = iter([SimpleNamespace(type="session.updated")])
+ api.extra_conns.append(conn2)
+ conn1._events = iter(
+ [
+ SimpleNamespace(
+ type="response.created",
+ response=SimpleNamespace(id="resp-auto", metadata=None),
+ ),
+ SimpleNamespace(type="input_audio_buffer.speech_started"),
+ ]
+ )
+ session._events = conn1.__aiter__()
+
+ _events = [event async for event in session.receive()]
+
+ assert session._conn is conn2
+ assert conn2.created_items == [
+ {
+ "type": "message",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "let's talk programming languages",
+ }
+ ],
+ },
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "text", "text": "Sure — which one?"}],
+ },
+ ]
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_unsolicited_second_response_is_cancelled_without_replaying_audio(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/realtime/test_protocol.py b/tests/unit/realtime/test_protocol.py
index 29136f49f1..3676593ee9 100644
--- a/tests/unit/realtime/test_protocol.py
+++ b/tests/unit/realtime/test_protocol.py
@@ -39,3 +39,11 @@ def test_session_config_defaults_to_shared_thinking_pause():
assert RealtimeSessionConfig().silence_duration_ms == (
SpeechConfig().vad_silence_ms
) == 1_500
+
+
+def test_session_config_history_defaults_empty():
+ from jarvis.realtime.protocol import RealtimeSessionConfig
+
+ # The first open of a call carries no history; only a mid-call reopen
+ # (transport rebuild / cross-family fallback) seeds it (BUG-088).
+ assert RealtimeSessionConfig().history == ()
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index bf0863ae71..12a294b539 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -4613,9 +4613,11 @@ class RebuildingProvider(FakeProvider):
self._session_factories = list(session_factories)
self.open_calls = 0
self.sessions = []
+ self.opened_cfgs = []
async def open_session(self, cfg):
self.opened_with = cfg
+ self.opened_cfgs.append(cfg)
self.open_calls += 1
factory = self._session_factories[
min(self.open_calls - 1, len(self._session_factories) - 1)
@@ -4884,6 +4886,99 @@ async def test_transport_rebuild_mirrors_the_frozen_turn_to_the_surface():
await sess.end(reason="test")
+async def test_transport_rebuild_seeds_the_call_history_into_the_fresh_session():
+ """BUG-088: an in-place transport rebuild used to hand the fresh provider
+ session a completely empty conversation, so the native voice model
+ answered every follow-up with amnesia ("what is the hardest language?"
+ lost its programming-language framing from earlier turns). The rebuild
+ open must carry the bounded call transcript; the first open of a call
+ stays seedless."""
+ provider = RebuildingProvider(
+ [
+ lambda: DyingSession(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="what is the hardest language",
+ is_final=True,
+ ),
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="Malbolge is widely feared.",
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ ),
+ lambda: StayOpenSession([]),
+ ]
+ )
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="rebuild-history-seed",
+ 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 _wait_until(lambda: len(provider.sessions) == 2)
+
+ assert provider.opened_cfgs[0].history == ()
+ assert provider.opened_cfgs[1].history == (
+ {"role": "user", "text": "what is the hardest language"},
+ {"role": "assistant", "text": "Malbolge is widely feared."},
+ )
+ await sess.end(reason="test")
+
+
+async def test_completed_turns_refresh_the_session_history_snapshot():
+ """The orchestrator must keep a snapshot-capable provider session current
+ after every completed turn (BUG-088), so a provider-internal transport
+ rebuild (openai_realtime's BUG-064 stack) can restore the conversation
+ without a wire call."""
+
+ class SnapshotSession(FakeSession):
+ def __init__(self, events):
+ super().__init__(events)
+ self.history_snapshots = []
+
+ def set_history_snapshot(self, history):
+ self.history_snapshots.append(history)
+
+ class SnapshotProvider(FakeProvider):
+ async def open_session(self, cfg):
+ self.opened_with = cfg
+ self.session = SnapshotSession(self._events)
+ return self.session
+
+ provider = SnapshotProvider(
+ [
+ RealtimeEvent(type="input_transcript", text="hello", is_final=True),
+ RealtimeEvent(type="output_transcript_delta", text="Hi there."),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ sess = RealtimeVoiceSession(
+ session_id="history-snapshot",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _m: asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(),
+ bus=None,
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await _wait_until(lambda: bool(provider.session.history_snapshots))
+
+ assert provider.session.history_snapshots[-1] == (
+ {"role": "user", "text": "hello"},
+ {"role": "assistant", "text": "Hi there."},
+ )
+ await sess.end(reason="test")
+
+
@pytest.mark.asyncio
async def test_transport_death_after_end_call_converts_to_hangup():
"""The user already asked to end the call (end_call acknowledged); a