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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(realtime): benign cancel race no longer kills the session; scrub aborts recorded
Ruben Lütkede00f7046325
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 9d616cf697..f4fa967acb 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -3803,7 +3803,14 @@ health, and a zero-error run row are never sufficient evidence by themselves.Never recover a silent tool turn by replaying the original request; recoverfrom the retained result so a side effect can occur at most once.-## BUG-053: A normal realtime barge-in ends the call when cancellation loses a response-boundary race (HIGH, OPEN, 2026-07-14)+## BUG-053: A normal realtime barge-in ends the call when cancellation loses a response-boundary race (HIGH, LARGELY FIXED 2026-07-14 — correction 3 open)++> **Status update (2026-07-14, afternoon).** Corrections 1 and 2 are+> implemented (see BUG-056 below, which is the same defect fired through the+> scrub-cancel path): `response_cancel_not_active` is now a recoverable+> provider event, and `interrupt()` skips the wire cancel when no response+> lifecycle is active. Correction 3 (preserve and forward the accepted+> barge-in audio into the next turn) remains open.**Symptom.** During a healthy desktop realtime session, the user began afollow-up about NotebookLM and its MCP server while the preceding answer was@@ -4062,3 +4069,76 @@ menus) must be created and driven on the main thread; a worker-threadviolation is a native abort, not a catchable exception. "No platformmarker in the code" does not mean cross-platform — threading contractsdiffer per OS, and only a real-device boot proves them.++## BUG-056: A scrub-gate abort's stale cancellation ends the session, and the transcript hides the abort (HIGH, FIXED 2026-07-14)++**Symptom.** Voice session 2026-07-14 15:12: "Welche MCP-Server habe ich+alle?" was answered by a healthy 5.4 s delegated turn <!-- i18n-allow: quoted German user utterance under forensic analysis -->+(the BUG-055 latency fixes working as designed), but the spoken answer cut+off mid-sentence at "Du hast zwei", the session ended with+`hangup_reason=error`, and the exported transcript showed only the truncated+reply — no trace of what failed or why the answer stopped.++**Evidence (desktop log + sessions.db, session c3c1997f).**++- 15:13:09.594 `realtime_delegate_completed` success=True after 5393 ms.+- 15:13:12.468 `scrub gate cancelled output: unsafe output transcript` — the+ ScrubHoldGate flagged a transcript delta as a hard leak while the answer+ was being voiced; the honest fallback line was then spoken via classic TTS+ (audible 15:13:18–15:13:20).+- 15:13:20.536 `terminal provider error: response_cancel_not_active:+ Cancellation failed: no active response found` — recorded with+ `recoverable: false`; the pump set `_failed` and the session ended+ `reason=error` at 15:13:23.918.+- The recorded spoken track contains the progress bridge and the truncated+ reply, but NOT the fallback line and NOT the abort reason.++**Root causes (three).**++1. **BUG-053's misclassification, second firing path.** The scrub cancel+ calls the adapter's `interrupt()`; the provider's response lifecycle was+ already over, so `response.cancel` answered with the benign+ `response_cancel_not_active`. The adapter's recoverable set contained only+ `conversation_already_has_active_response`, so this idempotent no-op race+ was labeled terminal and killed an otherwise healthy session.+2. **Transcript dishonesty.** `_cancel_unsafe_output` spoke a fallback line+ through `error_spoken` but never published it as a `SpeechSpoken` event,+ so the recorder — and therefore the exported transcript — had no trace of+ the abort (the exact gap the maintainer reported).+3. **Undiagnosable trigger.** Only the generic reason string "unsafe output+ transcript" survived; the gate did not surface WHICH scrub detectors+ tripped, so a possible false positive on a technical-but-harmless answer+ (MCP server names) cannot be judged after the fact.++**Fix (2026-07-14).**++- `_RECOVERABLE_ERROR_CODES` gains `response_cancel_not_active` (BUG-053+ correction 1): both sides of the response-boundary race are now benign.+- `interrupt()` skips the wire cancel when `_response_idle` is set (BUG-053+ correction 2); the recoverable classification stays as the backstop for+ the remaining check-to-wire race window.+- `_cancel_unsafe_output` publishes the spoken fallback as+ `SpeechSpoken(spoken_kind="withheld", detail=<reason>)` — new vocabulary+ entry wired through all four parity layers (constants.py, models.py,+ types.ts, TurnCard.tsx) — so the transcript shows the abort, its fallback+ line, and the detector names.+- `ScrubHoldGate.hard_leak_actions()` exposes the tripped detector names+ (safe metadata, never the flagged content) and the session embeds them in+ the cancel reason.++**Still open.** Whether the 15:13 hard leak itself was a false positive is+not reconstructable (transcript deltas are not persisted); the detector-name+diagnosis added here answers that question at the next occurrence. BUG-053+correction 3 (forward accepted barge-in audio into the next turn) also+remains open.++**Class rule.** A cancellation that finds nothing to cancel has already+succeeded — treat provider races idempotently on both boundaries (create and+cancel). And every safety abort that changes what the user hears MUST leave+an honest, user-visible trace in the recorded conversation; a silent abort+reads as a broken answer and is undebuggable afterwards.++Guards: `tests/unit/realtime/test_openai_realtime.py` (recoverable + skip),+`tests/unit/realtime/test_scrub_gate.py` (detector diagnosis),+`tests/unit/realtime/test_session.py` (withheld recording),+`tests/unit/sessions/test_spoken_kind_parity.py`.diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.pyindex 59f36201df..3f5085a226 100644--- a/jarvis/realtime/scrub_gate.py+++ b/jarvis/realtime/scrub_gate.py@@ -41,10 +41,22 @@ class ScrubHoldGate:self._hard_leak = Falseself._transcript_seen = Falseself._transcript_tail = ""+ self._hard_leak_actions: tuple[str, ...] = ()def hard_leak_pending(self) -> bool:return self._hard_leak+ def hard_leak_actions(self) -> tuple[str, ...]:+ """Scrub-action names behind the current hard leak (diagnosis only).++ Safe metadata: detector names such as ``replaced_shell_command`` —+ never the flagged content itself, so surfacing them in transcripts+ and latency spans cannot re-leak what the gate withheld (BUG-056:+ the 15:13 abort was undiagnosable because only the generic reason+ string survived).+ """+ return self._hard_leak_actions+def fallback_phrase(self) -> str:return FALLBACK_PHRASES.get(self._language, FALLBACK_PHRASES["en"])@@ -67,6 +79,9 @@ class ScrubHoldGate:result_is_hard = _is_hard_scrub_result(result)if aggregate_is_hard or result_is_hard:self._hard_leak = True+ self._hard_leak_actions = tuple(+ sorted(set(aggregate.actions) | set(result.actions))+ )self._cleared = Falseself._pending.clear()self._pending_audio_ms = 0.0@@ -131,6 +146,7 @@ class ScrubHoldGate:self._pending_audio_ms = 0.0self._cleared = Falseself._hard_leak = True+ self._hard_leak_actions = ("no_transcript",)return Truedef fail_if_pending_exceeds(self, max_pending_ms: int) -> bool:@@ -145,6 +161,7 @@ class ScrubHoldGate:self._pending_audio_ms = 0.0self._cleared = Falseself._hard_leak = True+ self._hard_leak_actions = ("transcript_stalled",)return Truedef finalize(self) -> list[AudioChunk]:@@ -165,6 +182,7 @@ class ScrubHoldGate:self._hard_leak = Falseself._transcript_seen = Falseself._transcript_tail = ""+ self._hard_leak_actions = ()def _restore_edge_whitespace(original: str, cleaned: str) -> str:diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex a754cde240..455f9492a9 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -31,6 +31,7 @@ from jarvis.sessions.constants import (HANGUP_CLIENT_STOP,HANGUP_VOICE_PATTERN,SPOKEN_KIND_PROGRESS,+ SPOKEN_KIND_WITHHELD,)from jarvis.speech.hangup import HANGUP_RE@@ -1098,8 +1099,15 @@ class RealtimeVoiceSession:self._mark_latency_named("REALTIME_FIRST_TRANSCRIPT")display = await self._gate.feed_transcript(event.text)if self._gate.hard_leak_pending():+ # Name the tripped detectors (safe metadata, never the+ # flagged content) so a false-positive abort is+ # diagnosable from the transcript alone (BUG-056).+ _actions = ", ".join(self._gate.hard_leak_actions())await self._cancel_unsafe_output(- reason="unsafe output transcript"+ reason=(+ "unsafe output transcript"+ f" (detectors: {_actions or 'unknown'})"+ ))self._gate.drain()continue@@ -1383,16 +1391,37 @@ class RealtimeVoiceSession:passself._output_active = Falseself._output_samples_sent = 0+ spoken_fallback = fallback_text or self._gate.fallback_phrase()try:await self._send_json({"type": "error_spoken",- "text": fallback_text or self._gate.fallback_phrase(),+ "text": spoken_fallback,"language": self._language,})except Exception: # noqa: BLE001, S110 — surface may already be gonepass+ # Keep the transcript honest (BUG-056): the 15:13 session recorded a+ # reply truncated to "Du hast zwei" with NO trace of why the audible+ # answer stopped. Persist the spoken fallback on the spoken track so+ # the exported transcript shows the abort and its detector names.+ if self._bus is not None:+ try:+ from jarvis.core.events import SpeechSpoken++ await self._bus.publish(+ SpeechSpoken(+ **self._event_trace_kwargs(),+ source_layer=f"realtime.{self.active_provider}",+ text=spoken_fallback,+ language=self._language,+ spoken_kind=SPOKEN_KIND_WITHHELD,+ detail=reason,+ )+ )+ except Exception: # noqa: BLE001, S110 — recording never breaks the turn+ passasync def _recover_unbacked_action_claim(self) -> bool:"""Turn a provider's unsupported action promise into a real outcome."""diff --git a/jarvis/sessions/constants.py b/jarvis/sessions/constants.pyindex 64183988d7..37750fef45 100644--- a/jarvis/sessions/constants.py+++ b/jarvis/sessions/constants.py@@ -189,5 +189,6 @@ __all__ = ["SPOKEN_KIND_SUBAGENT","SPOKEN_KIND_TIMEOUT","SPOKEN_KIND_UNAVAILABLE",+ "SPOKEN_KIND_WITHHELD","SPOKEN_KINDS",]diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsxindex c99ff42c19..379cd87f3a 100644--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx@@ -44,6 +44,7 @@ export const SPOKEN_KIND_LABEL: Record<string, string> = {announcement: "Announcement",preamble: "Preamble",progress: "Progress update",+ withheld: "Answer withheld (safety)",other: "Spoken",};diff --git a/jarvis/ui/web/frontend/src/components/sessions/types.ts b/jarvis/ui/web/frontend/src/components/sessions/types.tsindex 9da3ad0bf4..cef0e9fa50 100644--- a/jarvis/ui/web/frontend/src/components/sessions/types.ts+++ b/jarvis/ui/web/frontend/src/components/sessions/types.ts@@ -52,6 +52,7 @@ export const KNOWN_SPOKEN_KINDS = ["announcement","preamble","progress",+ "withheld","other",] as const;diff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.pyindex 2213a3d1ba..1c01f74c22 100644--- a/tests/unit/realtime/test_scrub_gate.py+++ b/tests/unit/realtime/test_scrub_gate.py@@ -186,3 +186,29 @@ async def test_untranscribed_audio_buffer_is_bounded_by_audio_duration():assert gate.fail_if_pending_exceeds(50) is Trueassert gate.hard_leak_pending() is Trueassert gate.finalize() == []++async def test_hard_leak_exposes_detector_actions_for_diagnosis():+ """BUG-056: the 15:13 abort was undiagnosable — only the generic reason+ string survived. The gate must name WHICH detectors tripped (safe+ metadata, never the flagged content), and reset them on drain()."""+ gate = ScrubHoldGate(language="en")+ assert gate.hard_leak_actions() == ()+ await gate.feed_transcript(+ "Traceback (most recent call last):\n File x\nValueError: y\n\n"+ )+ assert gate.hard_leak_pending() is True+ actions = gate.hard_leak_actions()+ assert actions, "a hard leak must carry at least one detector name"+ # Detector names only — the flagged content itself must not appear.+ assert all("Traceback" not in a and "ValueError" not in a for a in actions)+ gate.drain()+ assert gate.hard_leak_actions() == ()+++async def test_fail_closed_reports_missing_transcript_action():+ gate = ScrubHoldGate(language="en")+ await gate.push_audio(_chunk(4))+ assert gate.fail_closed() is True+ assert gate.hard_leak_actions() == ("no_transcript",)diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 77705ae40e..1c9329cd35 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -3630,3 +3630,33 @@ async def test_delegate_does_not_retry_an_internal_type_error():assert brain.calls == 1assert provider.session.tool_results[0][2]["success"] is Falseawait sess.end(reason="test")+++async def test_scrub_cancel_records_spoken_fallback_on_the_spoken_track():+ """BUG-056: the 15:13 session's transcript ended at a truncated reply with+ no trace of the safety abort. The scrub cancel must persist its spoken+ fallback as a SpeechSpoken(withheld) event carrying the detector names in+ ``detail``, so the exported transcript shows what happened and why."""+ provider = FakeProvider([])+ bus = FakeBus()+ sess = RealtimeVoiceSession(+ session_id="scrub-cancel-record",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=bus,+ surface="desktop",+ )+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})++ reason = "unsafe output transcript (detectors: replaced_stacktrace)"+ await sess._cancel_unsafe_output(reason=reason)+ await sess.end(reason="test")++ spoken = [event for event in bus.events if isinstance(event, SpeechSpoken)]+ assert len(spoken) == 1+ assert spoken[0].spoken_kind == "withheld"+ assert spoken[0].detail == reason+ assert spoken[0].text == sess._gate.fallback_phrase()