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): answer the barge-in question, and supersede stale turn directives

rubenluetke10-beepa7555b7c3907
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 3299dec61e..34c3ad7308 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -511,12 +511,27 @@ class _CodexSubscriptionRealtimeSession:
# counter makes ``receive`` drop every remaining frame of the response
# that was cut off. Read by the receive loop, which keeps its own copy.
self._output_drop_barrier = 0
+ # Set by ``interrupt(retire_input_entitlement=True)`` (delegation
+ # paths only), consumed by the receive loop's barrier handler: the
+ # delegated utterance's response entitlement is withdrawn so the far
+ # end's own answer to it can never start after the cut. A plain
+ # barge-in must NOT set this — at that moment the generation already
+ # belongs to the user's NEW utterance.
+ self._retire_entitlement_pending = False
# Set by ``interrupt``, read and cleared by ``truncate``: the played
# position only means something for a response that was actually cut.
self._interrupt_pending_truncation = False
# Last persona/context text actually delivered, so a re-issued
# identical one is not sent again mid-call.
self._delivered_context = ""
+ # Last turn-scoped directive delivered whole. Tracked separately from
+ # the context diff: the three per-turn directives are mutually
+ # exclusive, so a change is delivered as a full REPLACEMENT block —
+ # a line-diff would leave contradictory "this current turn" texts
+ # standing in the append-only thread.
+ self._delivered_turn_directive = ""
+ # One INFO line per session for the discarded tool declarations.
+ self._tools_discard_noted = False
# False once the local recognizer stream DIED. It is the only grounding
# source this transport has, so losing it must degrade to the same
# fail-open behaviour as a host that never had one — otherwise the gate
@@ -1047,16 +1062,22 @@ class _CodexSubscriptionRealtimeSession:
_cancel_completion()
_reset_assistant_capture()
_close_response(spent=True)
- # Jarvis owns everything spoken up to this cut (barge-in or
- # a delegation taking the turn): an utterance that already
- # happened must not re-authorize the far end's answer AFTER
- # the interrupt. Closing the open response alone left that
- # entitlement standing whenever the interrupt beat the
- # response's first frame, and the "retired" answer simply
- # started afterwards.
- consumed_input_generation = max(
- consumed_input_generation, local_input_generation
- )
+ if self._retire_entitlement_pending:
+ # A DELEGATION took this turn: the utterance it was
+ # dispatched for must not re-authorize the far end's
+ # own answer AFTER the cut. Closing the open response
+ # alone left that entitlement standing whenever the
+ # interrupt beat the response's first frame, and the
+ # "retired" answer simply started afterwards. Guarded
+ # by the explicit flag because on a BARGE-IN the
+ # current generation already belongs to the user's
+ # NEW utterance — retiring it there silenced the
+ # answer to the very question the user just asked
+ # (independent review 2026-08-05).
+ self._retire_entitlement_pending = False
+ consumed_input_generation = max(
+ consumed_input_generation, local_input_generation
+ )
interrupt_grace_until = (
asyncio.get_running_loop().time() + _POST_INTERRUPT_GRACE_S
)
@@ -1631,8 +1652,14 @@ class _CodexSubscriptionRealtimeSession:
# to Jarvis's deterministic supervisor.
_cancel_completion()
# The model yielded control; whatever it produces next
- # needs its own grounding, never this turn's.
+ # needs its own grounding, never this turn's — and the
+ # yielded utterance's entitlement retires with it, or
+ # the model's own answer to the handed-off request
+ # could still start later.
_close_response(spent=True)
+ consumed_input_generation = max(
+ consumed_input_generation, local_input_generation
+ )
self._handoff_interrupt_pending = True
direct_turn_id = str(
item.get("turn_id", "") or item.get("turnId", "") or ""
@@ -1752,6 +1779,7 @@ class _CodexSubscriptionRealtimeSession:
instructions: str | None = None,
language: str | None = None,
tools: tuple[dict[str, Any], ...] | None = None,
+ turn_directive: str | None = None,
) -> None:
# Tools cannot be declared here, and that is a transport fact rather
# than a policy choice: the app-server realtime RPC surface is only
@@ -1763,7 +1791,7 @@ class _CodexSubscriptionRealtimeSession:
# INFO once per session, DEBUG afterwards: the discard repeats on
# every turn, but a session that silently swallows the entire tool
# surface is exactly the AP-30 failure mode.
- already_noted = getattr(self, "_tools_discard_noted", False)
+ already_noted = self._tools_discard_noted
self._tools_discard_noted = True
log.log(
logging.DEBUG if already_noted else logging.INFO,
@@ -1777,7 +1805,7 @@ class _CodexSubscriptionRealtimeSession:
# knowledge — dropping them was why the voice knew nothing about its own
# project. ChatGPT-Live accepts developer context, so a changed persona
# is delivered mid-call instead of being discarded.
- await self._deliver_context(instructions)
+ await self._deliver_context(instructions, turn_directive=turn_directive)
await self._pin_language(language)
async def _pin_language(self, language: object) -> None:
@@ -1804,7 +1832,9 @@ class _CodexSubscriptionRealtimeSession:
)
self._language = normalized
- async def _deliver_context(self, instructions: str | None) -> None:
+ async def _deliver_context(
+ self, instructions: str | None, *, turn_directive: str | None = None
+ ) -> None:
"""Give the model Jarvis's own persona, capabilities and context.
ChatGPT-Live has no session-instructions field a client may set, but
@@ -1815,32 +1845,58 @@ class _CodexSubscriptionRealtimeSession:
the whole block grew the live thread by a full persona per turn: the
call got slower with every exchange and the model kept re-reading
stale copies of per-turn directives. The full block goes out once;
- afterwards only the lines that actually changed are appended, under a
- header that says the rest stays in force.
+ afterwards only the lines that actually changed are appended.
+
+ The TURN-scoped directive is the exception to line-diffing: its three
+ states (required / pending / discouraged) are mutually exclusive, so a
+ change is delivered as one whole block that explicitly REPLACES every
+ earlier current-turn instruction — a diff plus a blanket "everything
+ stays in force" left contradictory turn directives standing in the
+ thread (independent review 2026-08-05).
"""
text = str(instructions or "").strip()
- if not text or text == self._delivered_context:
- return
- payload = text
- if self._delivered_context:
- previous_lines = set(self._delivered_context.splitlines())
- changed = [
- line
- for line in text.splitlines()
- if line.strip() and line not in previous_lines
- ]
- if not changed:
- # Only removals or reordering: nothing an append can retract.
- self._delivered_context = text
- return
- payload = "\n".join(
- (
- "Developer context update — only the CHANGED lines "
- "follow; everything else from the previous developer "
- "context stays in force:",
- *changed,
- )
+ directive = str(turn_directive or "").strip()
+ directive_lines = set(directive.splitlines()) if directive else set()
+ sections: list[str] = []
+ if text and text != self._delivered_context:
+ if not self._delivered_context:
+ sections.append(text)
+ else:
+ previous_lines = set(self._delivered_context.splitlines())
+ changed = [
+ line
+ for line in text.splitlines()
+ if line.strip()
+ and line not in previous_lines
+ and line not in directive_lines
+ ]
+ if changed:
+ sections.append(
+ "\n".join(
+ (
+ "Developer context update — apply the "
+ "following changed lines on top of the "
+ "persona and project context already given; "
+ "unchanged parts of THAT context stay in "
+ "force:",
+ *changed,
+ )
+ )
+ )
+ if directive and directive != self._delivered_turn_directive:
+ sections.append(
+ "Current-turn instructions — these REPLACE every earlier "
+ "instruction about how to handle the current turn:\n"
+ + directive
)
+ if not sections:
+ # Identical, or only removals/reordering an append cannot retract.
+ if text:
+ self._delivered_context = text
+ if directive:
+ self._delivered_turn_directive = directive
+ return
+ payload = "\n\n".join(sections)
try:
await self._append_trusted(
lambda: self._client.realtime_append_text(
@@ -1855,7 +1911,10 @@ class _CodexSubscriptionRealtimeSession:
exc_info=True,
)
return
- self._delivered_context = text
+ if text:
+ self._delivered_context = text
+ if directive:
+ self._delivered_turn_directive = directive
async def _deliver_history(self, history: Any) -> None:
"""Restore bounded same-call context after a transport rebuild."""
@@ -1928,7 +1987,7 @@ class _CodexSubscriptionRealtimeSession:
exc_info=True,
)
- async def interrupt(self) -> None:
+ async def interrupt(self, *, retire_input_entitlement: bool = False) -> None:
"""Stop the assistant on barge-in, with or without a Codex turn id.
``turn/interrupt`` addresses an app-server TURN, and an ordinary
@@ -1942,8 +2001,19 @@ class _CodexSubscriptionRealtimeSession:
works: raising the barrier makes ``receive`` retire the cut response,
so every frame the far end still sends for it is dropped instead of
played over the person who interrupted.
+
+ ``retire_input_entitlement`` separates the two callers, and getting it
+ wrong is audible either way. A DELEGATION owns the utterance it was
+ dispatched for, so the far end's own answer to that utterance must
+ never start later — the delegation paths pass True. A BARGE-IN happens
+ after the user's NEW utterance already bumped the local input
+ generation; retiring it there consumed the new question's one response
+ entitlement and the assistant fell permanently silent (found in
+ independent review 2026-08-05).
"""
self._output_drop_barrier += 1
+ if retire_input_entitlement:
+ self._retire_entitlement_pending = True
self._interrupt_pending_truncation = True
await self._interrupt_active_codex_turn()
diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.py
index 668e6dc312..283296ebfe 100644
--- a/jarvis/realtime/scrub_gate.py
+++ b/jarvis/realtime/scrub_gate.py
@@ -72,15 +72,16 @@ _COVERAGE_MS_PER_CHAR = 55.0
# A finalize() tail this far beyond the coverage estimate cannot be explained
# by the deliberate underestimation alone; log it as a transcription stall.
_FINALIZE_EXCESS_LOG_MS = 5_000.0
-# Release budget for ONE injected direct-speech utterance — a generous
-# OVERestimate of its rendering time (the opposite direction of
-# _COVERAGE_MS_PER_CHAR's deliberate underestimate). Clamping the trusted
-# answer itself would recreate "the action ran and the user heard nothing",
-# so the bound exists only to stop the clearance from covering an UNBOUNDED
-# amount of foreign audio on a transport that generates its own responses:
-# without it, one injection opened the gate for the rest of the call.
-_DIRECT_SPEECH_MS_PER_CHAR = 150.0
-_DIRECT_SPEECH_BUDGET_FLOOR_MS = 10_000.0
+# Release budget for ONE injected direct-speech utterance — an OVERestimate
+# of its rendering time (the opposite direction of _COVERAGE_MS_PER_CHAR's
+# deliberate underestimate: 2x that rate, so a real voice can never outrun
+# it). Clamping the trusted answer itself would recreate "the action ran and
+# the user heard nothing", so the bound must stay generous — but not so
+# generous it misses the incident class it exists for: the live 2026-08-04
+# case was 8.2 s of foreign audio riding a stall-phrase-length clearance,
+# which a 10 s floor would have waved through entirely.
+_DIRECT_SPEECH_MS_PER_CHAR = 110.0
+_DIRECT_SPEECH_BUDGET_FLOOR_MS = 3_000.0
class ScrubHoldGate:
@@ -149,6 +150,7 @@ class ScrubHoldGate:
int(self._direct_speech_released_ms),
int(self._direct_speech_budget_ms),
)
+ self._direct_speech_budget_ms = 0.0
@property
def pending_audio_ms(self) -> float:
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 280fe2b3b9..90e0b5c69e 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -475,8 +475,9 @@ def _handoff_variant(directive: str) -> str:
)
.replace(
"Use end_call only when the user says goodbye.",
- "When the user says goodbye, answer with a brief goodbye — the "
- "call system ends the call itself.",
+ "When the user asks to end the call, answer with a brief goodbye "
+ "— the call system itself detects the explicit hang-up phrase; "
+ "you neither can nor need to end the call.",
)
.replace("Call jarvis_action on this turn ONLY", "Request a handoff on this turn ONLY")
.replace("calling any function", "requesting a handoff")
@@ -2625,6 +2626,15 @@ class RealtimeVoiceSession:
tools_changed = bool(
callable(refresh_tools) and refresh_tools()
)
+ turn_tool_directive = self._tool_directive(
+ delegate_required=self._delegate_required_for_turn,
+ action_pending=(
+ self._has_pending_delegate_from_earlier_turn()
+ ),
+ delegate_discouraged=(
+ not turn_plan.requires_orchestrator
+ ),
+ )
update_kwargs: dict[str, Any] = {
"instructions": _session_instructions(
new_language,
@@ -2632,15 +2642,7 @@ class RealtimeVoiceSession:
provider=self.active_provider,
model=self._active_model,
language_is_pinned=True,
- tool_directive=self._tool_directive(
- delegate_required=self._delegate_required_for_turn,
- action_pending=(
- self._has_pending_delegate_from_earlier_turn()
- ),
- delegate_discouraged=(
- not turn_plan.requires_orchestrator
- ),
- ),
+ tool_directive=turn_tool_directive,
preferences=_preferences_block(self._config),
# Zero extra round trips: this update already
# fires on every final transcript, so a
@@ -2655,6 +2657,12 @@ class RealtimeVoiceSession:
workspace_directive=self._workspace_directive(),
),
"language": new_language,
+ # For append-only transports: the turn-scoped
+ # directive travels separately so the adapter can
+ # supersede the previous one whole instead of
+ # leaving contradictory "this current turn" texts
+ # standing in the thread.
+ "turn_directive": turn_tool_directive,
}
if tools_changed:
update_kwargs["tools"] = self._declared_tools()
@@ -2675,10 +2683,20 @@ class RealtimeVoiceSession:
try:
await self._session.update_session(**update_kwargs)
except TypeError:
- # Compatibility with third-party adapters built
- # against the older update-session protocol.
- update_kwargs.pop("tools", None)
- await self._session.update_session(**update_kwargs)
+ # Compatibility with adapters built against the
+ # older update-session protocols: retire the
+ # NEWEST field first so an adapter that already
+ # understands tools keeps receiving them.
+ update_kwargs.pop("turn_directive", None)
+ try:
+ await self._session.update_session(
+ **update_kwargs
+ )
+ except TypeError: # predates the tools field too
+ update_kwargs.pop("tools", None)
+ await self._session.update_session(
+ **update_kwargs
+ )
if self._tool_bridge is not None and event.is_final and transcript:
await self._tool_bridge.handle_user_transcript(
self._last_user_text
@@ -5685,7 +5703,12 @@ class RealtimeVoiceSession:
# interrupt (idempotent) so the far end is cut no matter which
# path armed the withhold, and inject immediately.
try:
- await self._session.interrupt()
+ try:
+ await self._session.interrupt(
+ retire_input_entitlement=True
+ )
+ except TypeError: # adapter predates the retire flag
+ await self._session.interrupt()
except Exception: # noqa: BLE001, S110 — best-effort boundary
pass
return
@@ -5924,7 +5947,12 @@ class RealtimeVoiceSession:
# fluffy…" played instead of the computed weather answer).
self._drop_provider_output_until_new_response = True
try:
- await self._session.interrupt()
+ try:
+ await self._session.interrupt(
+ retire_input_entitlement=True
+ )
+ except TypeError: # adapter predates the retire flag
+ await self._session.interrupt()
except Exception: # noqa: BLE001, S110 — best-effort retire
pass
if turn_state.wait_for_provider_boundary or bool(
diff --git a/jarvis/realtime/webrtc_transport.py b/jarvis/realtime/webrtc_transport.py
index e8ee1f1c9b..ea4fd8d1dd 100644
--- a/jarvis/realtime/webrtc_transport.py
+++ b/jarvis/realtime/webrtc_transport.py
@@ -205,7 +205,6 @@ class _PcmSenderTrack:
# Composed rather than subclassed at import time so the aiortc import
# stays inside the function that needs it.
self._impl = _build_sender_track(MediaStreamTrack)
- self.queue: asyncio.Queue[bytes] = self._impl.queue
@property
def track(self) -> Any:
@@ -708,10 +707,14 @@ class RealtimeWebRtcAudioEndpoint:
# and to a log reader as a healthy call.
shed_bytes = self._sender.enqueue(payload)
if shed_bytes:
- self._outgoing_drops += max(1, shed_bytes // _WIRE_FRAME_BYTES)
+ previous_drops = self._outgoing_drops
+ self._outgoing_drops = previous_drops + max(
+ 1, shed_bytes // _WIRE_FRAME_BYTES
+ )
if (
- self._outgoing_drops <= _DROP_LOG_EVERY
- or self._outgoing_drops % _DROP_LOG_EVERY == 0
+ previous_drops == 0
+ or previous_drops // _DROP_LOG_EVERY
+ != self._outgoing_drops // _DROP_LOG_EVERY
):
log.warning(
"Realtime WebRTC sender shed ~%d stale outgoing microphone "
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index bce7b42ae1..bf808dd966 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -447,7 +447,45 @@ async def test_context_refresh_appends_only_the_changed_lines() -> None:
update = context_appends[1]
assert "Clock: 12:01." in update
assert "Persona line." not in update
- assert "stays in force" in update
+ assert "stay in force" in update
+ await session.close()
+
+
+async def test_turn_directive_supersedes_instead_of_accumulating() -> None:
+ """A changed turn directive is delivered WHOLE, with replace semantics.
+
+ The three per-turn directives are mutually exclusive; a line-diff plus a
+ blanket "everything stays in force" left the thread claiming "answer
+ directly", "do not answer" and "say you are still working" all at once
+ (independent review 2026-08-05).
+ """
+ client = _Client()
+ session = await _provider(client).open_session(
+ RealtimeSessionConfig(instructions="Persona line.\nDirective A.")
+ )
+
+ await session.update_session(
+ instructions="Persona line.\nDirective B.",
+ turn_directive="Directive B.",
+ )
+ await session.update_session(
+ instructions="Persona line.\nDirective A.",
+ turn_directive="Directive A.",
+ )
+
+ appends = [text for _thread, text, _role in client.text_appends]
+ assert appends[0] == "Persona line.\nDirective A."
+ # 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
+ # 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]
await session.close()
@@ -2355,7 +2393,7 @@ async def test_interrupt_retires_an_entitlement_the_response_never_used(
if event.type == "input_transcript" and event.is_final:
break
- await session.interrupt()
+ await session.interrupt(retire_input_entitlement=True)
audio_after = []
with contextlib.suppress(TimeoutError):
@@ -2368,6 +2406,70 @@ async def test_interrupt_retires_an_entitlement_the_response_never_used(
await session.close()
+async def test_barge_in_never_consumes_the_new_utterances_entitlement() -> None:
+ """A plain barge-in interrupt must keep the NEW question answerable.
+
+ At the moment ``_barge_in`` fires, the local input generation already
+ belongs to the user's new utterance. Retiring it there consumed that
+ question's one response entitlement, so the assistant fell permanently
+ silent after every barge-in (independent review 2026-08-05: 3 frames
+ before the change, 0 after). Only a delegation may retire the
+ entitlement, via ``retire_input_entitlement=True``.
+ """
+ speech = (1000).to_bytes(2, "little", signed=True) * 480
+ endpoint = _FakeAudioEndpoint(output_schedule=((0.5, speech), (0.02, speech)))
+ transcriber = _ScheduledInputTranscriber(
+ [
+ (0.0, InputTranscriptEvent(kind="speech_started")),
+ (
+ 0.02,
+ InputTranscriptEvent(
+ kind="transcript", text="Frage eins", is_final=True
+ ),
+ ),
+ (0.05, InputTranscriptEvent(kind="speech_started")),
+ (
+ 0.02,
+ InputTranscriptEvent(
+ kind="transcript", text="Warte, anders", is_final=True
+ ),
+ ),
+ ]
+ )
+ client = _Client()
+ client.subscription = _keeps_stream_open()
+ session = await _provider(
+ client,
+ endpoint=endpoint,
+ input_transcriber_factory=lambda: transcriber,
+ ).open_session(RealtimeSessionConfig())
+
+ stream = session.receive()
+ finals = 0
+ async with asyncio.timeout(1.5):
+ async for event in stream:
+ if event.type == "input_transcript" and event.is_final:
+ finals += 1
+ if finals == 2:
+ break
+
+ await session.interrupt()
+
+ audio_after = []
+ with contextlib.suppress(TimeoutError):
+ async with asyncio.timeout(1.0):
+ async for event in stream:
+ if event.type == "audio_delta":
+ audio_after.append(event)
+ break
+
+ assert audio_after, (
+ "the far end's answer to the barge-in utterance must stay audible"
+ )
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_post_interrupt_captions_do_not_feed_the_rebuild_counter(
monkeypatch,
diff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.py
index 3aa4210535..05e9434f81 100644
--- a/tests/unit/realtime/test_scrub_gate.py
+++ b/tests/unit/realtime/test_scrub_gate.py
@@ -546,15 +546,15 @@ async def test_direct_speech_clearance_expires_after_its_rendering_budget():
"""
gate = ScrubHoldGate(language="en")
gate.trust_direct_speech("Short answer.")
- five_seconds = AudioChunk(
- pcm=b"\x00\x01" * (24_000 * 5), sample_rate=24_000, timestamp_ns=0
+ two_seconds = AudioChunk(
+ pcm=b"\x00\x01" * (24_000 * 2), sample_rate=24_000, timestamp_ns=0
)
- assert await gate.push_audio(five_seconds)
- assert await gate.push_audio(five_seconds)
- assert await gate.push_audio(five_seconds)
+ assert await gate.push_audio(two_seconds)
+ assert await gate.push_audio(two_seconds)
+ assert await gate.push_audio(two_seconds)
# The utterance's generous rendering budget is spent: whatever streams
# now belongs to another response and is vetted fail-closed again.
- assert await gate.push_audio(five_seconds) == []
+ assert await gate.push_audio(two_seconds) == []
@pytest.mark.asyncio