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.

feat(realtime): release the opening hold with a locally recovered shadow transcript

rubenluetke10-beep0ff20a5fd0e8
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 84c40b5436..48fac245a4 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -100,6 +100,18 @@ _UNGROUNDED_CAPTIONS_BEFORE_REBUILD = 2
# them toward the rebuild threshold turned every delegation into a transport
# rebuild storm (live 2026-08-04: 11 rejections, 3 rebuilds in 43 s).
_POST_INTERRUPT_GRACE_S = 3.0
+# When a response's audible audio flows while the far end's own transcript is
+# still absent, the session's scrub gate holds ALL of it fail-closed — and
+# ChatGPT-Live's transcripts lag their audio by SECONDS (measured live
+# 2026-08-05 20:42: the first audio sat 7.4 s in the gate). After this much
+# audible audio with no transcript, the LOCAL recognizer transcribes the
+# captured head and the text goes out as a SHADOW delta: the scrub gate
+# judges real text, the audio releases, and the provider's own transcript
+# stays the only one the user sees. The retry interval spaces attempts when
+# the shared recognizer is busy with the microphone stream (AP-24: its own
+# non-blocking lock makes a busy engine a skip, never a wedge).
+_OUTPUT_EARLY_RECOVERY_AFTER_S = 1.2
+_OUTPUT_EARLY_RECOVERY_RETRY_S = 1.0
# How long a trusted injection's permit may wait for the response it provokes.
# Generous relative to the far end's latency, and bounded so an injection that
# was never answered cannot authorize an unrelated response later in the call.
@@ -297,6 +309,9 @@ class _ProviderEvent:
tool_args: dict[str, Any] | None = None
handoff_id: str | None = None
provider_turn_id: str | None = None
+ # output_transcript_delta only: locally recovered vetting material — see
+ # RealtimeEvent.shadow in jarvis/realtime/protocol.py.
+ shadow: bool = False
def _notification_parts(notification: Any) -> tuple[str, dict[str, Any]]:
@@ -669,6 +684,12 @@ class _CodexSubscriptionRealtimeSession:
assistant_audio = bytearray()
assistant_audio_active = False
assistant_transcript_seen = False
+ # Early shadow recovery (see _OUTPUT_EARLY_RECOVERY_AFTER_S): when the
+ # response's first audible frame arrived, when recovery last ran, and
+ # whether this response already produced its one shadow delta.
+ first_audible_at = 0.0
+ early_recovery_at = 0.0
+ early_shadow_done = False
# ChatGPT-Live's server VAD can start a response to silence or to its
# own speaker echo. Local input is the authority for whether a NEW
# automatic response has a user behind it. A generation is consumed
@@ -766,9 +787,13 @@ class _CodexSubscriptionRealtimeSession:
def _reset_assistant_capture() -> None:
nonlocal assistant_audio_active, assistant_transcript_seen
+ nonlocal first_audible_at, early_recovery_at, early_shadow_done
assistant_audio.clear()
assistant_audio_active = False
assistant_transcript_seen = False
+ first_audible_at = 0.0
+ early_recovery_at = 0.0
+ early_shadow_done = False
def _fresh_local_input_exists() -> bool:
return bool(
@@ -1008,6 +1033,30 @@ class _CodexSubscriptionRealtimeSession:
is_final=True,
)
+ async def _recover_shadow_transcript() -> str:
+ """Locally transcribe the captured head for gate vetting only.
+
+ Unlike ``_recover_output_transcript`` this neither latches
+ ``assistant_transcript_seen`` nor produces display text: the
+ provider's own (late) transcript stays the one the user sees.
+ AP-24: ``transcribe_audio`` bounds itself and skips when the
+ shared engine is busy — a raised skip is an ordinary retry.
+ """
+ recover = getattr(self._input_transcriber, "transcribe_audio", None)
+ if not callable(recover):
+ return ""
+ try:
+ return str(
+ await recover(bytes(assistant_audio), sample_rate=_OUTPUT_RATE)
+ or ""
+ ).strip()
+ except Exception: # noqa: BLE001 - the fail-closed hold simply continues
+ log.debug(
+ "Codex subscription early shadow recovery skipped",
+ exc_info=True,
+ )
+ return ""
+
def _missing_input_boundary() -> _ProviderEvent | None:
"""One placeholder per turn when neither source produced text.
@@ -1258,6 +1307,44 @@ class _CodexSubscriptionRealtimeSession:
):
remaining = _OUTPUT_TRANSCRIPT_RECOVERY_MAX_BYTES - len(assistant_audio)
assistant_audio.extend(pcm[:remaining])
+ if audible and assistant_audio_active and not first_audible_at:
+ first_audible_at = asyncio.get_running_loop().time()
+ if (
+ audible
+ and assistant_audio_active
+ and not assistant_transcript_seen
+ and not early_shadow_done
+ and first_audible_at
+ and assistant_audio
+ ):
+ # The session's scrub gate is holding every one of
+ # these chunks fail-closed until SOME transcript
+ # arrives, and the far end's own can lag by seconds.
+ # Recover a shadow transcript locally so the gate can
+ # judge real text now (see the constants above).
+ now = asyncio.get_running_loop().time()
+ if (
+ now - first_audible_at >= _OUTPUT_EARLY_RECOVERY_AFTER_S
+ and now - early_recovery_at
+ >= _OUTPUT_EARLY_RECOVERY_RETRY_S
+ ):
+ early_recovery_at = now
+ shadow_text = await _recover_shadow_transcript()
+ if shadow_text:
+ early_shadow_done = True
+ log.info(
+ "Codex subscription realtime released the "
+ "opening hold with a locally recovered "
+ "shadow transcript %d ms after the "
+ "response's first audible frame",
+ int((now - first_audible_at) * 1000),
+ )
+ yield _ProviderEvent(
+ type="output_transcript_delta",
+ text=shadow_text,
+ is_final=False,
+ shadow=True,
+ )
yield _ProviderEvent(
type="audio_delta",
audio=_PcmChunk(
diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.py
index d235a066d8..5cc0b7d117 100644
--- a/jarvis/realtime/protocol.py
+++ b/jarvis/realtime/protocol.py
@@ -36,6 +36,11 @@ class RealtimeEvent:
audio: AudioChunk | None = None # audio_delta
text: str | None = None # output_transcript_delta / input_transcript
is_final: bool = False
+ # output_transcript_delta only: locally recovered vetting material for a
+ # response whose provider transcript lags its audio. The scrub gate judges
+ # 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
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 016d1c91f7..2bbf61ff32 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -2928,6 +2928,35 @@ class RealtimeVoiceSession:
),
)
self._start_deterministic_delegate(self._last_user_text)
+ elif (
+ event.type == "output_transcript_delta"
+ and event.text
+ and getattr(event, "shadow", False)
+ ):
+ # Locally recovered SHADOW text: vetting material only.
+ # It lets the scrub gate judge real text when the
+ # provider's own transcript lags its audio by seconds
+ # (live 2026-08-05 20:42: the reply's first audio sat
+ # 7.4 s in the opening hold), but it must never reach
+ # the surface or the turn transcript — the provider's
+ # real text follows and would double up.
+ if self._must_withhold_provider_output():
+ self._note_output_withheld("transcript")
+ continue
+ await self._ensure_turn_started()
+ await self._gate.feed_transcript(event.text)
+ if self._gate.hard_leak_pending():
+ _actions = ", ".join(self._gate.hard_leak_actions())
+ await self._cancel_unsafe_output(
+ reason=(
+ "unsafe output transcript (shadow recovery; "
+ f"detectors: {_actions or 'unknown'})"
+ )
+ )
+ self._gate.drain()
+ continue
+ for chunk in self._gate.release_available():
+ await self._emit_audio(chunk)
elif event.type == "output_transcript_delta" and event.text:
delegate_state = self._delegate_turns.get(self._turn_id)
if (
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index a4d8d40b5e..0e443a145e 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -2382,6 +2382,58 @@ async def test_interrupt_drops_the_remainder_without_any_codex_turn_id(
await session.close()
+async def test_late_provider_transcript_is_shadow_recovered_for_the_gate(
+ monkeypatch,
+) -> None:
+ """Audible audio with no provider transcript earns a SHADOW delta.
+
+ ChatGPT-Live's transcripts can lag their audio by seconds; the session's
+ scrub gate holds all of it fail-closed until SOME transcript arrives
+ (live 2026-08-05 20:42: the reply's first audio sat 7.4 s in the opening
+ hold). The local recognizer recovers vetting text early; the shadow flag
+ keeps it out of the user-visible transcript.
+ """
+ monkeypatch.setattr(
+ codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05
+ )
+ monkeypatch.setattr(
+ codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01
+ )
+ speech = (1000).to_bytes(2, "little", signed=True) * 480
+ endpoint = _FakeAudioEndpoint(
+ output_schedule=(
+ (0.02, speech),
+ (0.05, speech),
+ (0.05, speech),
+ (0.05, speech),
+ )
+ )
+ transcriber = _RecoveringEndpointer("Here is the answer.")
+ client = _Client()
+ client.subscription = _keeps_stream_open()
+ session = await _provider(
+ client,
+ endpoint=endpoint,
+ input_transcriber_factory=lambda: transcriber,
+ ).open_session(RealtimeSessionConfig())
+
+ shadow = None
+ with contextlib.suppress(TimeoutError):
+ async with asyncio.timeout(1.5):
+ async for event in session.receive():
+ if event.type == "output_transcript_delta" and getattr(
+ event, "shadow", False
+ ):
+ shadow = event
+ break
+
+ assert shadow is not None
+ assert shadow.text == "Here is the answer."
+ assert transcriber.recovery_calls
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_interrupt_retires_an_entitlement_the_response_never_used(
monkeypatch,
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 0756c48717..9d747ed9c4 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -7023,3 +7023,47 @@ async def test_session_instructions_carry_the_one_speaker_discipline():
assert "ONE voice" in text
assert "Never speak both sides" in text
assert "Do not say goodbye" in text
+
+
+async def test_shadow_transcript_clears_the_gate_without_reaching_the_surface():
+ """A shadow delta is vetting material: audio releases, no transcript shows.
+
+ The provider's own text follows later and would double up if the locally
+ recovered shadow text were surfaced.
+ """
+ jsons = []
+ binaries = []
+ events = [
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(
+ pcm=b"\x00\x01" * 2_400, sample_rate=24_000, timestamp_ns=0
+ ),
+ ),
+ RealtimeEvent(
+ type="output_transcript_delta",
+ text="Here is the answer.",
+ shadow=True,
+ ),
+ ]
+ sess = RealtimeVoiceSession(
+ session_id="s-shadow",
+ send_binary=lambda pcm: binaries.append(pcm) or asyncio.sleep(0),
+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),
+ provider=FakeProvider(events),
+ config=_cfg(),
+ bus=None,
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await asyncio.sleep(0.1)
+
+ assert binaries, "shadow-cleared audio must reach playback"
+ surfaced = [
+ message
+ for message in jsons
+ if message.get("type") == "transcript"
+ and "Here is the answer." in str(message.get("text", ""))
+ ]
+ assert surfaced == [], "shadow text must never reach the surface"
+ await sess.end(reason="test")