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): honest transcripts, and a first fragment cannot set the call language

rubenluetke10-beepb301daa84215
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index bcf9c2fa69..58c72cea40 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -362,6 +362,11 @@ class _ProviderEvent:
# output_transcript_delta only: locally recovered vetting material — see
# RealtimeEvent.shadow in jarvis/realtime/protocol.py.
shadow: bool = False
+ # input_transcript finals only: how much VOICED audio the local endpointer
+ # measured for this utterance. Feeds the session's first-turn language
+ # duration gate (a sub-half-second misheard fragment must not set the
+ # call language). 0 = unknown; other adapters never set it.
+ voiced_ms: int = 0
def _notification_parts(notification: Any) -> tuple[str, dict[str, Any]]:
@@ -1672,6 +1677,9 @@ class _CodexSubscriptionRealtimeSession:
type="input_transcript",
text=payload.text,
is_final=payload.is_final,
+ voiced_ms=int(
+ getattr(payload, "voiced_ms", 0) or 0
+ ),
)
continue
if queue_kind == "media_audio":
@@ -2413,6 +2421,44 @@ class _CodexSubscriptionRealtimeSession:
if pin_text:
self._language = normalized_pin
+ async def _append_opening_language_hint(self, default_language: object) -> None:
+ """One soft language line at open when NOTHING is pinned.
+
+ Unpinned sessions used to rely only on the thread-start base
+ instructions ("mirror the user's language") — the channel proven
+ unreliable — so every call opened in whatever the far end preferred
+ (live: German sessions booked ``language=en`` throughout). This is a
+ HINT on the working channel, deliberately not a pin: it names the
+ configured default only for the moment before anyone spoke, defers to
+ the user's actual language, and never latches this session's own
+ language state — the ONE resolver keeps deciding per turn (§1).
+ """
+ locale = _normalized_locale(default_language)
+ name = _LANGUAGE_ENDONYMS.get(locale)
+ if name:
+ fallback = f"{name} ({locale})"
+ elif locale:
+ fallback = f"the language with IETF language tag {locale!r}"
+ else:
+ return
+ text = (
+ "Reply in the language the user actually speaks. If nobody has "
+ f"spoken yet, or the first utterance is too short to tell, use "
+ f"{fallback}. Apply this silently — never acknowledge it."
+ )
+ try:
+ await self._append_trusted(
+ lambda: self._client.realtime_append_text(
+ self._thread_id, text, role="developer"
+ ),
+ arms_response=False,
+ )
+ except Exception: # noqa: BLE001 — a missing hint must not kill the open
+ log.debug(
+ "Codex subscription opening language hint not delivered",
+ exc_info=True,
+ )
+
async def _pin_language(self, language: object) -> None:
"""Deliver the resolved output language as the turn's authoritative pin.
@@ -2990,6 +3036,14 @@ class CodexSubscriptionRealtimeProvider:
# the latest actual user audio.
if getattr(cfg, "language_is_pinned", False):
await session._pin_language(getattr(cfg, "language", ""))
+ else:
+ # Unpinned: a soft opening hint on the WORKING channel — the
+ # thread-start "mirror the user" rule alone is the channel
+ # live calls proved unreliable, and every unpinned session
+ # opened in the far end's preferred language.
+ await session._append_opening_language_hint(
+ getattr(cfg, "language", "")
+ )
return session
except BaseException:
try:
diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.py
index 9793bd492c..0df7bf2685 100644
--- a/jarvis/realtime/protocol.py
+++ b/jarvis/realtime/protocol.py
@@ -41,6 +41,10 @@ class RealtimeEvent:
# it like any transcript, but it must never reach the surface or the turn
# transcript — the provider's own text follows and would double up.
shadow: bool = False
+ # input_transcript finals only: voiced audio duration the local endpointer
+ # measured for the utterance. Feeds the session's first-turn language
+ # duration gate; 0 means unknown and disables the gate for that final.
+ voiced_ms: int = 0
ms_played: int | None = None # speech_started: ms of our audio already heard
error: str | None = None
# A recoverable provider event reports a rejected operation while the
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index f0e415cffb..e602f03cd9 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -38,7 +38,11 @@ from jarvis.brain.provider_test import (
from jarvis.brain.turn_planner import TurnPath, TurnPlan, TurnReason, plan_turn
from jarvis.core.protocols import AudioChunk, BrainMessage
from jarvis.core.redact import safe_preview
-from jarvis.core.turn_language import normalize_language_tag, resolve_output_language
+from jarvis.core.turn_language import (
+ is_substantive_turn,
+ normalize_language_tag,
+ resolve_output_language,
+)
from jarvis.realtime.audio import StreamingPcm16Resampler
from jarvis.realtime.protocol import RealtimeSessionConfig
from jarvis.realtime.scrub_gate import ScrubHoldGate
@@ -79,6 +83,11 @@ _HALF_DUPLEX_MUTE_REPEAT_S = 10.0
# reply that is merely pausing keeps its mute, and far below the alert. No
# audio playing means no echo risk — reopening matches barge-in semantics.
_HALF_DUPLEX_SILENT_RELEASE_S = 2.0
+# Before the conversation's language is ESTABLISHED, a final this short is
+# too little audio to trust its words for the language decision ("Was geht
+# ab?" misheard as "Vaskit up" flipped a whole German call to English).
+# Duration, never spelling (the AP-27 class rule).
+_CONVERSATION_LANGUAGE_MIN_VOICED_MS = 500
# Per-turn stall backstop. A provider can stop emitting ENTIRELY — no audio, no
# transcript, no boundary, no error — and the receive iterator then simply never
# yields again. Nothing else in this module bounds that: the pump awaits the
@@ -1279,6 +1288,15 @@ class RealtimeVoiceSession:
self._initial_conversation_language = str(
getattr(brain, "conversation_language", "") or ""
).strip().lower()
+ # False until a SUBSTANTIVE final (>= the voiced-duration floor)
+ # resolves the call language once. Until then the resolver must not
+ # be fed the session's own opening default as "the conversation's
+ # language" — that masquerade made a misheard 300 ms first fragment
+ # both answer in English AND stick. A real handed-over conversation
+ # counts as established from the start.
+ self._conversation_established = bool(
+ self._initial_conversation_language
+ )
self._stt_language = getattr(
getattr(self._config, "stt", None), "language", "unknown"
)
@@ -1421,7 +1439,14 @@ class RealtimeVoiceSession:
self._turn_index = 0
self._current_turn_index = -1
self._last_user_text = ""
- self._user_transcript_parts: list[str] = []
+ # Live caption of the CURRENT unfinished utterance. Surfaces render
+ # it; persistence never does unless the promotion path says so
+ # explicitly (a mid-word partial silently recorded as the turn's
+ # user_text is how "illst." became an utterance, 2026-08-06 17:03).
+ self._last_user_text_preview = ""
+ #: (item_id, text) finals of the current turn; a re-final of a known
+ #: item REPLACES its entry instead of double-booking the utterance.
+ self._user_transcript_parts: list[tuple[str, str]] = []
self._input_turn_observed = False
self._output_transcript: list[str] = []
# BUG-089: text-level self-echo backstop. The realtime path's acoustic
@@ -1495,17 +1520,61 @@ class RealtimeVoiceSession:
# never sees the rejection, so repeated rapid deaths retry seedless.
self._suppress_history_seed = False
- def _resolve_lang(self, *, text: str) -> str:
+ def _note_user_final(self, item_id: str, text: str) -> None:
+ """Record a FINAL user transcript part for the current turn.
+
+ Item-keyed: a provider that re-finalizes the same input item (a
+ correction, a local/server double-book of one utterance) REPLACES its
+ earlier entry instead of concatenating the utterance into itself.
+ Finals without an id keep appending — multi-part turns stay intact.
+ """
+ if item_id:
+ for index, (known_id, _) in enumerate(self._user_transcript_parts):
+ if known_id == item_id:
+ self._user_transcript_parts[index] = (item_id, text)
+ break
+ else:
+ self._user_transcript_parts.append((item_id, text))
+ else:
+ self._user_transcript_parts.append(("", text))
+ self._last_user_text = " ".join(
+ t for _, t in self._user_transcript_parts
+ ).strip()
+ # The turn has real text now; the live caption served its purpose.
+ self._last_user_text_preview = ""
+
+ def _resolve_lang(self, *, text: str, voiced_ms: int = 0) -> str:
brain = getattr(self._config, "brain", None)
pin = getattr(brain, "reply_language", "auto")
+ established = bool(getattr(self, "_conversation_established", False))
+ # The resolver's stickiness input must be an ESTABLISHED conversation
+ # language, never the session's own opening default wearing that hat
+ # (the input lied; the resolver itself is correct and stays untouched
+ # — §1 doctrine).
+ if established:
+ conversation = getattr(self, "_language", "")
+ else:
+ conversation = self._initial_conversation_language
+ if (
+ text
+ and not established
+ and 0 < voiced_ms < _CONVERSATION_LANGUAGE_MIN_VOICED_MS
+ ):
+ # Duration gate, never spelling (AP-27 class): a sub-half-second
+ # first fragment carries too little audio to trust its words for
+ # the call language ("Vaskit up"). Resolve from STT tag/default.
+ log.debug(
+ "realtime[%s] first fragment (%d ms voiced) is too short to "
+ "set the call language",
+ self.session_id,
+ voiced_ms,
+ )
+ text = ""
return resolve_output_language(
pin,
self._stt_language,
text,
- conversation_language=(
- getattr(self, "_language", "")
- or self._initial_conversation_language
- ),
+ conversation_language=conversation,
)
def _plan_turn(self, text: str) -> TurnPlan:
@@ -2602,7 +2671,10 @@ class RealtimeVoiceSession:
# the acoustic gates — dropping it here means no
# response is ever generated for it.
echo_probe = " ".join(
- (*self._user_transcript_parts, transcript)
+ (
+ *(t for _, t in self._user_transcript_parts),
+ transcript,
+ )
).strip()
judge_short = (
time.monotonic() < self._local_barge_short_echo_until
@@ -2656,6 +2728,19 @@ class RealtimeVoiceSession:
and input_item_id in self._response_requested_input_ids
)
if event.is_final and input_already_answered:
+ if transcript:
+ # A re-final of an answered item is a CORRECTION:
+ # record the better text (item-keyed REPLACE, so
+ # the utterance never concatenates into itself)
+ # without re-running any turn machinery for it.
+ self._note_user_final(input_item_id, transcript)
+ log.info(
+ "realtime[%s] recorded a corrected transcript "
+ "for an already-answered item (item=%s)",
+ self.session_id,
+ input_item_id,
+ )
+ continue
# A swallowed user utterance is never a debug-level
# event: if the id space ever collides, this is the
# only trace that turn 2 vanished (AP-30).
@@ -2719,8 +2804,28 @@ class RealtimeVoiceSession:
await self._publish_turn_started()
await self._ensure_turn_started()
new_language = self._language
- if transcript:
- new_language = self._resolve_lang(text=transcript)
+ if transcript and event.is_final:
+ # FINALS ONLY (H3): a partial used to flip the call
+ # language mid-utterance, rebuild the scrub gate and
+ # announce — churn a growing caption re-triggered
+ # several times per sentence, and the en/en bookings
+ # on German turns came from exactly these flips.
+ voiced_ms = int(getattr(event, "voiced_ms", 0) or 0)
+ new_language = self._resolve_lang(
+ text=transcript, voiced_ms=voiced_ms
+ )
+ if not self._conversation_established and (
+ is_substantive_turn(transcript)
+ and (
+ voiced_ms == 0
+ or voiced_ms
+ >= _CONVERSATION_LANGUAGE_MIN_VOICED_MS
+ )
+ ):
+ # From here on the call language sticks; a later
+ # thin interjection cannot flip it (the resolver's
+ # own stickiness takes over).
+ self._conversation_established = True
if new_language != self._language:
self._language_flips += 1
self._language = new_language
@@ -2742,12 +2847,18 @@ class RealtimeVoiceSession:
)
if transcript:
if event.is_final:
- self._user_transcript_parts.append(transcript)
- self._last_user_text = " ".join(
- self._user_transcript_parts
+ self._note_user_final(input_item_id, transcript)
+ else:
+ # Live caption only — never the persisted text.
+ self._last_user_text_preview = " ".join(
+ (
+ *(
+ t
+ for _, t in self._user_transcript_parts
+ ),
+ transcript,
+ )
).strip()
- elif not self._user_transcript_parts:
- self._last_user_text = transcript
if event.is_final and input_observed:
turn_plan = self._plan_turn(self._last_user_text)
reasons = ",".join(
@@ -2880,9 +2991,7 @@ class RealtimeVoiceSession:
if event.is_final:
snapshot = self._last_user_text or transcript
else:
- snapshot = " ".join(
- (*self._user_transcript_parts, transcript)
- ).strip()
+ snapshot = self._last_user_text_preview or transcript
await self._publish_transcription(
snapshot, bool(event.is_final)
)
@@ -4730,6 +4839,24 @@ class RealtimeVoiceSession:
):
return False
+ if (
+ not self._last_user_text
+ and self._input_turn_observed
+ and self._last_user_text_preview
+ ):
+ # The user audibly spoke this turn and no FINAL ever arrived; the
+ # retained live caption is promoted EXPLICITLY - with its own log
+ # line - instead of a partial silently posing as the final (the
+ # recorded "illst.", 2026-08-06 17:03).
+ log.info(
+ "realtime[%s] persisting a non-final preview as user_text "
+ "for turn %s - no final transcript arrived",
+ self.session_id,
+ turn_id,
+ )
+ self._last_user_text = self._last_user_text_preview
+ self._last_user_text_preview = ""
+
if not self._last_user_text:
if self._input_turn_observed:
if self._outage_notice_allowed():
@@ -4911,6 +5038,23 @@ class RealtimeVoiceSession:
if not self._turn_id:
self._reset_turn_tracking()
return
+ if (
+ not self._last_user_text
+ and self._input_turn_observed
+ and self._last_user_text_preview
+ ):
+ # The user audibly spoke this turn and no FINAL ever arrived; the
+ # retained live caption is promoted EXPLICITLY - with its own log
+ # line - instead of a partial silently posing as the final (the
+ # recorded "illst.", 2026-08-06 17:03).
+ log.info(
+ "realtime[%s] persisting a non-final preview as user_text "
+ "for turn %s - no final transcript arrived",
+ self.session_id,
+ self._turn_id,
+ )
+ self._last_user_text = self._last_user_text_preview
+ self._last_user_text_preview = ""
answer = "".join(self._output_transcript).strip()
delegate_state = self._delegate_turns.pop(self._turn_id, None)
external_update = self._external_update
@@ -5155,6 +5299,7 @@ class RealtimeVoiceSession:
self._latency_tracker = None
self._current_turn_index = -1
self._last_user_text = ""
+ self._last_user_text_preview = ""
self._user_transcript_parts.clear()
self._input_turn_observed = False
self._output_transcript.clear()
diff --git a/tests/integration/realtime/test_codex_multi_turn.py b/tests/integration/realtime/test_codex_multi_turn.py
index abca2072c3..d40ad56378 100644
--- a/tests/integration/realtime/test_codex_multi_turn.py
+++ b/tests/integration/realtime/test_codex_multi_turn.py
@@ -758,3 +758,202 @@ async def test_a_hanging_close_does_not_stall_the_transport_rebuild(
assert provider.open_count == 2, "a second transport must have opened"
finally:
await _end(session)
+
+
+def _session_with_bus(
+ name: str,
+) -> tuple[RealtimeVoiceSession, _CodexShapedProvider, _Surface, list[Any]]:
+ """A desktop-shaped session whose VoiceTurnCompleted events are captured."""
+ from jarvis.core.events import VoiceTurnCompleted
+
+ surface = _Surface()
+ provider = _CodexShapedProvider()
+ bus = EventBus()
+ completed: list[Any] = []
+
+ async def _collect(event: VoiceTurnCompleted) -> None:
+ completed.append(event)
+
+ bus.subscribe(VoiceTurnCompleted, _collect)
+ session = RealtimeVoiceSession(
+ session_id=name,
+ send_binary=surface.send_binary,
+ send_json=surface.send_json,
+ providers=[provider],
+ config=_config(),
+ bus=bus,
+ surface="desktop",
+ half_duplex=True,
+ browser_sample_rate=INPUT_RATE,
+ )
+ return session, provider, surface, completed
+
+
+async def _wait_completed(completed: list[Any]) -> None:
+ for _ in range(50):
+ if completed:
+ return
+ await asyncio.sleep(0.01)
+ raise AssertionError("the turn never published VoiceTurnCompleted")
+
+
+async def test_a_partial_only_turn_promotes_its_preview_explicitly() -> None:
+ """A turn whose FINAL never arrives must not silently record a mid-word
+ partial as the user's utterance (the recorded "illst.") - the retained
+ live caption is promoted, with its own log line, instead."""
+ session, provider, surface, completed = _session_with_bus("preview-promote")
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
+ TIMEOUT_S,
+ )
+ try:
+ wire = provider.sessions[0]
+ since = surface.mark()
+ wire.push(
+ RealtimeEvent(type="speech_started"),
+ RealtimeEvent(
+ type="input_transcript",
+ text="what color is the vio",
+ is_final=False,
+ ),
+ RealtimeEvent(type="output_transcript_delta", text="Violet."),
+ RealtimeEvent(type="audio_delta", audio=_audio()),
+ RealtimeEvent(type="turn_complete"),
+ )
+ await surface.wait_json(
+ lambda m: m.get("type") == "turn_complete", since=since
+ )
+ await _wait_completed(completed)
+ assert completed[0].user_text == "what color is the vio", (
+ "the preview is promoted - explicitly - when no final arrived"
+ )
+ finally:
+ await _end(session)
+
+
+async def test_a_refinalized_item_replaces_instead_of_doubling() -> None:
+ """A provider re-finalizing the same input item (a correction) must not
+ concatenate the utterance into itself."""
+ session, provider, surface, completed = _session_with_bus("refinal-replace")
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
+ TIMEOUT_S,
+ )
+ try:
+ wire = provider.sessions[0]
+ since = surface.mark()
+ wire.push(
+ RealtimeEvent(type="speech_started"),
+ RealtimeEvent(
+ type="input_transcript",
+ text="what color is the giraffe",
+ is_final=True,
+ item_id="item-1",
+ ),
+ RealtimeEvent(
+ type="input_transcript",
+ text="what color is the violet giraffe",
+ is_final=True,
+ item_id="item-1",
+ ),
+ RealtimeEvent(type="output_transcript_delta", text="Violet."),
+ RealtimeEvent(type="audio_delta", audio=_audio()),
+ RealtimeEvent(type="turn_complete"),
+ )
+ await surface.wait_json(
+ lambda m: m.get("type") == "turn_complete", since=since
+ )
+ await _wait_completed(completed)
+ assert completed[0].user_text == "what color is the violet giraffe", (
+ "the re-final replaces its item instead of double-booking it"
+ )
+ finally:
+ await _end(session)
+
+
+async def test_a_partial_never_flips_the_call_language() -> None:
+ """Language resolution runs on FINALS only: a growing caption used to
+ flip the call language (and rebuild the scrub gate) mid-utterance."""
+ session, provider, surface, _completed = _session_with_bus("partial-lang")
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
+ TIMEOUT_S,
+ )
+ try:
+ wire = provider.sessions[0]
+ opening_language = session._language # noqa: SLF001
+ wire.push(
+ RealtimeEvent(type="speech_started"),
+ RealtimeEvent(
+ type="input_transcript",
+ # A decidedly German partial on an English-opened call.
+ text="wie viele Raeder hat das erfundene Fahrrad denn nun",
+ is_final=False,
+ ),
+ )
+ await asyncio.sleep(0.15)
+ assert session._language == opening_language, ( # noqa: SLF001
+ "a partial flipped the call language"
+ )
+ finally:
+ await _end(session)
+
+
+async def test_a_thin_first_fragment_does_not_set_the_call_language() -> None:
+ """A misheard 328 ms fragment ("Mask it up!") flipped a German call to
+ English AND stuck. Before the conversation is established, a final under
+ the voiced-duration floor resolves without its unreliable words; the
+ first substantive final then establishes the language for real."""
+ session, provider, surface, _completed = _session_with_bus("thin-fragment")
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
+ TIMEOUT_S,
+ )
+ try:
+ wire = provider.sessions[0]
+ opening_language = session._language # noqa: SLF001
+ since = surface.mark()
+ wire.push(
+ RealtimeEvent(type="speech_started"),
+ RealtimeEvent(
+ type="input_transcript",
+ text="Mask it up!",
+ is_final=True,
+ voiced_ms=328,
+ ),
+ RealtimeEvent(type="output_transcript_delta", text="Hey!"),
+ RealtimeEvent(type="audio_delta", audio=_audio()),
+ RealtimeEvent(type="turn_complete"),
+ )
+ await surface.wait_json(
+ lambda m: m.get("type") == "turn_complete", since=since
+ )
+ assert session._language == opening_language, ( # noqa: SLF001
+ "a 328 ms misheard fragment set the call language"
+ )
+ assert session._conversation_established is False # noqa: SLF001
+
+ # The first SUBSTANTIVE final establishes the language for real.
+ since = surface.mark()
+ wire.push(
+ RealtimeEvent(type="speech_started"),
+ RealtimeEvent(
+ type="input_transcript",
+ text="Wie viele Raeder hat mein erfundenes Fahrrad? Bitte sag es mir.",
+ is_final=True,
+ voiced_ms=2100,
+ ),
+ RealtimeEvent(type="output_transcript_delta", text="Fuenf."),
+ RealtimeEvent(type="audio_delta", audio=_audio()),
+ RealtimeEvent(type="turn_complete"),
+ )
+ await surface.wait_json(
+ lambda m: m.get("type") == "turn_complete", since=since
+ )
+ assert session._conversation_established is True # noqa: SLF001
+ finally:
+ await _end(session)
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index ef247944d3..b4ca14537e 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -275,13 +275,16 @@ async def test_direct_sdp_open_uses_safe_experimental_transport_contract() -> No
# Jarvis's own persona/context reaches the model as developer context —
# ChatGPT-Live has no client-settable session-instructions field. With no
- # explicit reply-language preference there is NO opening pin: nobody has
- # spoken yet, so the "resolved" language is only DEFAULT_LOCALE, and
- # hard-pinning it nailed every call's first reply to English. The base
- # instructions tell the model to mirror the latest actual user audio.
- assert client.text_appends == [
- ("thread-1", "Speak concise English.", "developer"),
- ]
+ # explicit reply-language preference there is NO opening pin (hard-pinning
+ # the default nailed every call's first reply to English), but there IS a
+ # soft opening HINT on the working channel: the thread-start mirror rule
+ # alone is the channel live calls proved unreliable, and unpinned German
+ # sessions opened in English throughout.
+ appended = [text for _thread, text, _role in client.text_appends]
+ assert appended[0] == "Speak concise English."
+ assert len(appended) == 2
+ assert "Reply in the language the user actually speaks" in appended[1]
+ assert "reply only in" not in appended[1], "a hint is not a pin"
_thread_id, start = client.realtime_starts[0]
assert start == {
"output_modality": "audio",
@@ -318,15 +321,19 @@ async def test_reopened_session_restores_bounded_same_call_history() -> None:
)
)
- # Persona, then the restored history. No opening language pin: this
- # session carries no explicit reply-language preference.
- assert len(client.text_appends) == 2
+ # Persona, then the restored history, then the soft opening language
+ # hint (no PIN: this session carries no explicit preference).
+ assert len(client.text_appends) == 3
thread_id, restored, role = client.text_appends[1]
assert thread_id == "thread-1"
assert role == "developer"
assert "conversation_history" in restored
assert "Which language were we discussing?" in restored
assert "We were discussing Malbolge." in restored
+ assert (
+ "Reply in the language the user actually speaks"
+ in client.text_appends[2][1]
+ )
await session.close()
@@ -409,15 +416,12 @@ async def test_language_update_is_developer_context_and_speech_is_authoritative(
await session.update_session(language="es")
await session.send_speech("Trusted answer")
- assert client.text_appends == [
- # No opening pin without an explicit reply-language preference — the
- # first pin is the one this turn actually resolved to.
- (
- "thread-1",
- codex_subscription_mod._language_pin_text("es"),
- "developer",
- ),
- ]
+ appended = [text for _thread, text, _role in client.text_appends]
+ # The soft opening hint (no pin without an explicit preference), then the
+ # first REAL pin — the one this turn actually resolved to.
+ assert len(appended) == 2
+ assert "Reply in the language the user actually speaks" in appended[0]
+ assert appended[1] == codex_subscription_mod._language_pin_text("es")
assert client.speech_appends == [("thread-1", "Trusted answer")]
await session.close()
@@ -507,16 +511,19 @@ async def test_turn_directive_supersedes_instead_of_accumulating() -> None:
appends = [text for _thread, text, _role in client.text_appends]
assert appends[0] == "Persona line.\nDirective A."
+ # The soft opening language hint rides between the persona and the first
+ # per-turn update on every unpinned open.
+ assert "Reply in the language the user actually speaks" in appends[1]
# Turn 2: the directive travels ONLY in its superseding section, never
# additionally as a diffed context line.
- assert "REPLACE every earlier instruction" in appends[1]
- assert "Directive B." in appends[1]
- assert appends[1].count("Directive B.") == 1
+ assert "REPLACE every earlier instruction" in appends[2]
+ assert "Directive B." in appends[2]
+ assert appends[2].count("Directive B.") == 1
# Turn 3: reverting re-issues the directive as a full replacement even
# though an identical copy already sits in the thread's opening block.
- assert "REPLACE every earlier instruction" in appends[2]
- assert "Directive A." in appends[2]
- assert "Directive B." not in appends[2]
+ assert "REPLACE every earlier instruction" in appends[3]
+ assert "Directive A." in appends[3]
+ assert "Directive B." not in appends[3]
await session.close()