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(speech): stop the per-sentence scrub from speaking errors mid-answer
Harald56b484cfe869
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 9553998a65..a522e9a09a 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -48,7 +48,7 @@ from jarvis.audio.effects import bind_shared_audio_playerfrom jarvis.audio.player import AudioPlayerfrom jarvis.audio.vad import SileroEndpointerfrom jarvis.audio.vad_reasons import FORCED_CUT_REASONS-from jarvis.brain.output_filter import scrub_for_voice+from jarvis.brain.output_filter import FALLBACK_PHRASES, ScrubResult, scrub_for_voicefrom jarvis.brain.turn_planner import plan_turnfrom jarvis.core.events import (CU_PROGRESS_EVENTS,@@ -1415,7 +1415,132 @@ _DRAIN_HOLDS_FLOOR: frozenset[TurnTakingState] = frozenset({# Matched whitespace/newline DIREKT NACH einem Satzendezeichen — also den# Uebergang von Satz n nach Satz n+1. Final-Flush am Stream-Ende uebernimmt# das letzte Fragment ohne folgendes Whitespace.-_STREAM_SENTENCE_END = re.compile(r"(?<=[.!?…])\s+|(?<=[.!?…])\n+")+#+# OF-12: a period plus whitespace is only a CANDIDATE boundary, never a+# boundary by itself. Ordinals ("Am 1. Januar", "El 31. de enero"), spaced+# abbreviations ("z. B.", "e. g.", "p. m.") and titles ("Dr. Meier",+# "Sr. Lopez") all carry a mid-sentence period, and splitting there made TTS+# speak "Am eins." as its own utterance. Every candidate is therefore+# validated by ``_is_stream_sentence_break`` below.+#+# The match deliberately does NOT require a following character. Waiting for+# the first character of the next sentence would hold sentence 1 hostage to+# the brain's next token — and a tool-use turn streams "Ich schaue nach. " and+# then goes quiet for seconds, which is exactly when the user must hear+# something. Every rule that can decide from the text BEFORE the gap decides+# immediately; the following character only refines a candidate when it+# already happens to be in the buffer.+_STREAM_SENTENCE_END = re.compile(r"(?<=[.!?…])\s+")++# Tokens whose trailing period is practically NEVER a sentence end. One shared+# set for every locale: the turn language is a hint, not a guarantee, and+# assistant prose mixes locales freely (a German answer quoting an English+# product name). Deliberately NOT listed are abbreviations that usually DO+# close a sentence ("etc.", "usw.") — for those the split is correct and must+# stay. Single-letter tokens need no entry: they are rejected as a class,+# which covers "z. B.", "u. a.", "d. h.", "e. g.", "i. e.", "a. m.", "p. m."+# and initials like "J. R. R.".+_STREAM_ABBREVIATIONS: frozenset[str] = frozenset({+ # Titles / forms of address (de/en/es) — always followed by a name.+ "dr", "prof", "dipl", "ing", "hr", "fr", "st", "sankt",+ "mr", "mrs", "ms", "jr",+ "sr", "sra", "srta", "ud", "uds",+ # Reference markers — always followed by a number or a caption.+ "nr", "num", "núm", "abb", "fig", "tab", "vol", "pág",+ # Qualifier / connector abbreviations — always mid-sentence.+ "bzw", "bspw", "ggf", "evtl", "inkl", "exkl", "zzgl", "vgl", "sog",+ "ca", "approx", "aprox", "mind", "max", "min", "mio", "mrd", "ej", "vs",+})++# Punctuation a new sentence may OPEN with; skipped when looking for the first+# real character behind a candidate boundary.+_STREAM_SENTENCE_OPENERS = "\"'“”„‚‘’«»‹›(<[{¿¡-–—*_#"++# A one- or two-digit run before the period is an ordinal ("Am 1. Januar",+# "El 31. de enero"), not a sentence end. A year ("2026.") is four digits and+# keeps its boundary.+_STREAM_ORDINAL_TAIL_RE = re.compile(r"(?<!\d)\d{1,2}\.$")+# The plain-letter token right before the period, if any.+_STREAM_ABBREV_TAIL_RE = re.compile(r"([^\W\d_]+)\.$")+++def _stream_opens_sentence(rest: str) -> bool:+ """True when ``rest`` starts with something that can OPEN a sentence.++ A lowercase letter means the period belonged to an abbreviation or a+ decimal, never to a sentence end. Scripts without case distinction (CJK,+ Arabic) are accepted, otherwise those locales would never split at all.++ ``rest`` is empty while the next token is still in flight. That is NOT a+ rejection: the boundary keeps the behaviour it had before this refinement+ existed, so a pausing brain can never sit on a finished sentence.+ """+ for ch in rest:+ if ch.isspace() or ch in _STREAM_SENTENCE_OPENERS:+ continue+ return ch.isdigit() or (ch.isalpha() and not ch.islower())+ return True+++def _is_stream_sentence_break(buffer: str, gap_start: int, gap_end: int) -> bool:+ """Decide whether the whitespace gap ``[gap_start:gap_end)`` ends a sentence.++ ``gap_start - 1`` is the terminator character matched by+ ``_STREAM_SENTENCE_END``. Only the period is ambiguous — "!", "?" and "…"+ have no abbreviation shape and always close a sentence.+ """+ if buffer[gap_start - 1] != ".":+ return True+ head = buffer[:gap_start]+ if _STREAM_ORDINAL_TAIL_RE.search(head):+ return False+ match = _STREAM_ABBREV_TAIL_RE.search(head)+ if match is not None:+ word = match.group(1)+ if len(word) == 1 or word.casefold() in _STREAM_ABBREVIATIONS:+ return False+ return _stream_opens_sentence(buffer[gap_end:])+++def _is_whole_text_fallback(original: str, scrubbed: ScrubResult) -> bool:+ """True when the scrub replaced the WHOLE input with the generic phrase.++ ``scrub_for_voice`` is a whole-TURN filter: when one of its guards fires+ (stack trace, raw repr, shell command, post-scrub residue) it throws the+ input away and returns the canned error phrase for ALL of it. Per sentence+ that verdict is wrong, so the streaming path has to recognise it (OF-11).++ ``fallback_used`` is the documented signal; the phrase-table comparison is+ a second, independent check so this stays correct if a future guard+ forgets the flag. An answer that genuinely SAYS the phrase (in markdown,+ say) must never be mistaken for one — so the phrase only counts when the+ original did not carry it in the first place.+ """+ if scrubbed.fallback_used:+ return True+ if not scrubbed.actions:+ return False+ cleaned = scrubbed.cleaned.strip()+ if not cleaned or cleaned not in set(FALLBACK_PHRASES.values()):+ return False+ return cleaned not in original+++def _next_stream_sentence_break(buffer: str) -> int | None:+ """Cut index just past the next real sentence boundary in ``buffer``.++ The caller slices ``buffer[:cut]`` as the finished sentence and keeps+ ``buffer[cut:]`` as the rest. ``None`` = no boundary in the buffer yet.+ """+ pos = 0+ while True:+ match = _STREAM_SENTENCE_END.search(buffer, pos)+ if match is None:+ return None+ if _is_stream_sentence_break(buffer, match.start(), match.end()):+ return match.end()+ pos = match.end()+# Wake-Only-Filter: reine Wake-Word-Utterances ohne Follow-Up werden NICHT# ans Brain geschickt. Sonst halluziniert das LLM ein "Ja?" / "Sir?" /@@ -13962,6 +14087,11 @@ class SpeechPipeline:full_text_parts: list[str] = []sentence_buffer = ""spoken_anything = False+ # OF-11: sentences the output filter threw away (whole-text fallback or+ # empty after scrub). Every entry is logged when it happens; the list+ # exists so the END of the turn can tell "filtered a clause out of a+ # healthy answer" from "filtered the entire answer away".+ dropped_sentences: list[str] = []# Turn-level mirror of ``spoken_anything`` that survives this coroutine# being cancelled by the stall guard — the caller's ``except# TimeoutError`` reads it to decide whether a canned fallback phrase@@ -14062,17 +14192,9 @@ class SpeechPipeline:finally:sentence_channels.task_done()- async def _enqueue_sentence(sentence: str) -> None:+ async def _speak_sentence(cleaned: str) -> None:+ """Hand one ALREADY-SCRUBBED sentence to synthesis + playback."""nonlocal spoken_anything- scrubbed = scrub_for_voice(sentence, language=lang)- if scrubbed.actions:- log.info(- "🧹 Output-Filter [stream:%s]: %s (fallback=%s)",- lang, scrubbed.actions, scrubbed.fallback_used,- )- cleaned = scrubbed.cleaned.strip()- if not cleaned:- returnif not spoken_anything:await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)spoken_anything = True@@ -14086,6 +14208,44 @@ class SpeechPipeline:# Blocks once ``lookahead`` channels are outstanding — back-pressure.await sentence_channels.put((channel, cleaned))+ async def _enqueue_sentence(sentence: str) -> None:+ """Scrub one streamed sentence and queue what survives.++ OF-11: ``scrub_for_voice`` judges a WHOLE TURN. Applied per+ sentence its all-or-nothing verdicts (stack trace, raw repr, shell+ command, post-scrub residue) would splice the canned error phrase+ into the middle of an otherwise healthy answer — one short+ sentence losing its only noun was enough. So a sentence-level+ fallback is dropped here and the phrase is re-raised ONCE for the+ completed turn, and only if nothing at all reached TTS.+ """+ scrubbed = scrub_for_voice(sentence, language=lang)+ if scrubbed.actions:+ log.info(+ "🧹 Output-Filter [stream:%s]: %s (fallback=%s)",+ lang, scrubbed.actions, scrubbed.fallback_used,+ )+ if _is_whole_text_fallback(sentence, scrubbed):+ dropped_sentences.append(sentence)+ log.warning(+ "🧹 Output-Filter [stream:%s]: sentence DROPPED — whole-text "+ "fallback fired on a single sentence, actions=%s, text=%r",+ lang, scrubbed.actions, sentence[:120],+ )+ return+ cleaned = scrubbed.cleaned.strip()+ if not cleaned:+ # Never swallow output silently (CLAUDE.md §7): the answer+ # loses a clause here, so the drop has to be visible.+ dropped_sentences.append(sentence)+ log.warning(+ "🧹 Output-Filter [stream:%s]: sentence DROPPED — empty after "+ "scrub, actions=%s, text=%r",+ lang, scrubbed.actions, sentence[:120],+ )+ return+ await _speak_sentence(cleaned)+async def _produce() -> None:nonlocal sentence_buffer, paraphrase_stripped, brain_first_token_markedtry:@@ -14150,11 +14310,11 @@ class SpeechPipeline:paraphrase_stripped = Truewhile True:- m = _STREAM_SENTENCE_END.search(sentence_buffer)- if m is None:+ cut = _next_stream_sentence_break(sentence_buffer)+ if cut is None:break- sentence = sentence_buffer[:m.end()].strip()- sentence_buffer = sentence_buffer[m.end():]+ sentence = sentence_buffer[:cut].strip()+ sentence_buffer = sentence_buffer[cut:]if sentence:await _enqueue_sentence(sentence)@@ -14165,6 +14325,22 @@ class SpeechPipeline:tail = sentence_buffer.strip()if tail:await _enqueue_sentence(tail)++ # OF-11, whole-turn half: the per-sentence drops above kept the+ # canned phrase out of a healthy answer. If they left the turn+ # completely silent, the whole-text verdict was right after all+ # — say the phrase exactly ONCE, or the user hears nothing.+ if dropped_sentences and not spoken_anything:+ log.warning(+ "🧹 Output-Filter [stream:%s]: whole turn filtered away "+ "(%d sentence(s)) — speaking the fallback phrase once",+ lang, len(dropped_sentences),+ )+ await _speak_sentence(+ FALLBACK_PHRASES.get(+ _phrase_lang(lang), FALLBACK_PHRASES["de"]+ )+ )except asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001diff --git a/tests/unit/speech/test_stream_sentence_filter.py b/tests/unit/speech/test_stream_sentence_filter.pynew file mode 100644index 0000000000..22fe0e5d02--- /dev/null+++ b/tests/unit/speech/test_stream_sentence_filter.py@@ -0,0 +1,326 @@+"""Pin the per-sentence contract of the streaming TTS path (OF-11 + OF-12).++Two defects lived in ``_brain_streaming`` (jarvis/speech/pipeline.py):++OF-11 — ``scrub_for_voice`` is a WHOLE-TURN filter. Several of its guards+throw the input away and return a canned error phrase for ALL of it. Called+once per sentence, a single short sentence that lost its only noun turned into+"Es trat ein Fehler auf." spoken in the MIDDLE of an otherwise healthy answer.+The sibling failure was silent: a sentence that scrubbed to nothing vanished+with no log line at all, so the answer lost a clause and nothing downstream+knew.++OF-12 — the sentence splitter cut at every period followed by whitespace, so+"Am 1. Januar" became the utterance "Am eins." plus "Januar …", and "z. B.",+"Dr. Meier", "Mr. Smith", "Sr. Lopez" fragmented the same way.++The OF-11 tests drive the scrub through a FAKE so they pin how the pipeline+USES the filter, not what the filter currently does — the filter's own guards+are pinned in tests/unit/brain/test_output_filter.py.+"""+from __future__ import annotations++import asyncio+import logging+from collections.abc import AsyncIterator+from dataclasses import dataclass, field++import pytest++from jarvis.brain.output_filter import FALLBACK_PHRASES, ScrubResult+from jarvis.core.bus import EventBus+from jarvis.core.protocols import AudioChunk+from jarvis.speech import pipeline as pipeline_module+from jarvis.speech.pipeline import (+ SpeechPipeline,+ _is_whole_text_fallback,+ _next_stream_sentence_break,+ _stream_opens_sentence,+)++# ---------------------------------------------------------------------------+# OF-12: sentence splitting+# ---------------------------------------------------------------------------+++def _split(text: str) -> list[str]:+ """Split ``text`` exactly the way the streaming producer does."""+ out: list[str] = []+ rest = text+ while True:+ cut = _next_stream_sentence_break(rest)+ if cut is None:+ break+ sentence = rest[:cut].strip()+ rest = rest[cut:]+ if sentence:+ out.append(sentence)+ tail = rest.strip()+ if tail:+ out.append(tail)+ return out+++ "text",+ [+ # German ordinals — the reported bug ("Am eins." as its own utterance).+ "Am 1. Januar 2026 ist es soweit.",+ "Am 31. Dezember kam die Rechnung.",+ # Spaced abbreviations: the single-letter token before the period.+ "Das ist z. B. wichtig.",+ "Das gilt u. a. für dich.",+ # Titles.+ "Dr. Meier hat angerufen.",+ "Prof. Schmidt kommt später.",+ # English.+ "Mr. Smith called at 5 p.m. sharp.",+ "Bring water, e.g. a bottle.",+ # Spanish.+ "El Sr. Lopez llamo.",+ "El 1. de enero empieza todo.",+ "Ud. puede traer algo, p. ej. agua.",+ ],+)+def test_mid_sentence_period_is_not_a_boundary(text: str) -> None:+ """None of these is more than ONE utterance."""+ assert _split(text) == [text]+++ ("text", "expected"),+ [+ ("Das ist gut. Das ist besser. Fertig!", 3),+ # A four-digit year is not an ordinal — the boundary survives.+ ("Das war 2026. Danach kam Ruhe.", 2),+ ("Wirklich? Ja! Sicher.", 3),+ ('Er sagte das. "Dann gehen wir", meinte sie.', 2),+ ("Das war knapp. 2026 wird besser.", 2),+ ("Rechnung Nr. 5 kam am 31. Dezember an. Alles bezahlt.", 2),+ ("Prof. Lee wrote about A vs. B. It was good.", 1),+ ],+)+def test_real_boundaries_still_split(text: str, expected: int) -> None:+ assert len(_split(text)) == expected+++def test_finished_sentence_is_not_held_back_for_the_next_token() -> None:+ """A sentence must go to TTS the moment it is complete.++ The next character would refine the decision, but waiting for it hands the+ turn to the brain: a tool-use turn streams "Ich schaue nach. " and then+ goes quiet for seconds — exactly when the user must hear something.+ """+ assert _next_stream_sentence_break("Ich schaue nach. ") == len(+ "Ich schaue nach. "+ )+++ ("rest", "expected"),+ [+ ("Dann kam er.", True), # uppercase+ ("2026 war gut.", True), # digit+ ('"Dann kam er."', True), # opening quote, then uppercase+ ("wichtig.", False), # lowercase continuation+ ("", True), # not streamed yet — never block on it+ ],+)+def test_stream_opens_sentence(rest: str, expected: bool) -> None:+ assert _stream_opens_sentence(rest) is expected+++# ---------------------------------------------------------------------------+# OF-11: whole-text fallback recognition+# ---------------------------------------------------------------------------+++def test_fallback_flag_is_recognised() -> None:+ result = ScrubResult(+ cleaned=FALLBACK_PHRASES["de"],+ actions=["replaced_stacktrace"],+ fallback_used=True,+ )+ assert _is_whole_text_fallback("Traceback (most recent call last):", result)+++def test_fallback_phrase_without_the_flag_is_recognised() -> None:+ """Belt and braces: a guard that forgets ``fallback_used`` still counts."""+ result = ScrubResult(+ cleaned=FALLBACK_PHRASES["en"], actions=["stripped_markdown"]+ )+ assert _is_whole_text_fallback("## Ab.", result)+++def test_answer_that_genuinely_says_the_phrase_is_not_a_fallback() -> None:+ phrase = FALLBACK_PHRASES["de"]+ result = ScrubResult(cleaned=phrase, actions=["stripped_markdown"])+ assert not _is_whole_text_fallback(f"**{phrase}**", result)+ assert not _is_whole_text_fallback(phrase, ScrubResult(cleaned=phrase))+++def test_healthy_sentence_is_not_a_fallback() -> None:+ result = ScrubResult(cleaned="Der Termin steht.", actions=[])+ assert not _is_whole_text_fallback("Der Termin steht.", result)+++# ---------------------------------------------------------------------------+# OF-11: the streaming turn+# ---------------------------------------------------------------------------++_POISON = "POISON" # the fake scrub answers this with the whole-text fallback+_VANISH = "VANISH" # ... and this with an empty result+++def _fake_scrub(+ text: str, *, language: str = "de", ack_mode: bool = False+) -> ScrubResult:+ """Stand-in for ``scrub_for_voice`` with deterministic verdicts."""+ stripped = text.strip()+ if _POISON in stripped:+ return ScrubResult(+ cleaned=FALLBACK_PHRASES.get(language, FALLBACK_PHRASES["de"]),+ actions=["replaced_stacktrace"],+ fallback_used=True,+ )+ if _VANISH in stripped:+ return ScrubResult(cleaned="", actions=["stripped_end_signal"])+ return ScrubResult(cleaned=stripped, actions=[])+++@dataclass+class _RecordingTTS:+ name: str = "recording-tts"+ supports_streaming: bool = True+ synth_started: list[str] = field(default_factory=list)++ async def synthesize(+ self, text: str, voice: str | None = None,+ language_code: str | None = None,+ ) -> AsyncIterator[AudioChunk]:+ self.synth_started.append(text)+ yield AudioChunk(+ pcm=b"\x00\x00", sample_rate=24_000, timestamp_ns=0, channels=1+ )+++@dataclass+class _NullPlayer:+ stop_calls: int = 0++ async def play_chunks(self, chunks: AsyncIterator[AudioChunk]) -> None:+ async for _chunk in chunks:+ pass++ def stop(self) -> None:+ self.stop_calls += 1+++class _ScriptedBrain:+ """Streams a fixed reply token by token."""++ def __init__(self, tokens: list[str]) -> None:+ self._tokens = tokens++ async def __call__(self, text: str) -> str: # pragma: no cover - unused+ return "".join(self._tokens)++ async def generate_stream(self, text: str) -> AsyncIterator[str]:+ for token in self._tokens:+ yield token+++async def _spoken_sentences(tokens: list[str], lang: str) -> list[str]:+ tts = _RecordingTTS()+ pipeline = SpeechPipeline(+ tts=tts, bus=EventBus(), enable_whisper_wake=False+ )+ pipeline._player = _NullPlayer() # type: ignore[assignment]+ pipeline._brain = _ScriptedBrain(tokens) # type: ignore[assignment]+ pipeline._latency_tracker = None+ pipeline._tts_lookahead_sentences = 2++ async def _never_barge(**_kwargs) -> bool:+ await asyncio.sleep(3600)+ return False++ pipeline._barge_monitor = _never_barge # type: ignore[assignment]+ await asyncio.wait_for(pipeline._brain_streaming("egal", lang), timeout=10)+ return tts.synth_started+++async def test_filtered_sentence_never_interrupts_a_healthy_answer(+ monkeypatch, caplog+) -> None:+ """The canned phrase must NOT be spliced between two good sentences."""+ monkeypatch.setattr(pipeline_module, "scrub_for_voice", _fake_scrub)+ with caplog.at_level(logging.WARNING, logger="jarvis.speech.pipeline"):+ spoken = await _spoken_sentences(+ ["Der Bericht ist fertig. ", f"{_POISON} Meldung. ",+ "Sonst noch was?"],+ "de",+ )++ assert spoken == ["Der Bericht ist fertig.", "Sonst noch was?"]+ assert FALLBACK_PHRASES["de"] not in spoken+ # ... and the drop is on the record (CLAUDE.md §7: nothing swallowed).+ dropped = [r for r in caplog.records if "DROPPED" in r.getMessage()]+ assert len(dropped) == 1+ assert _POISON in dropped[0].getMessage()+++async def test_sentence_that_scrubs_to_nothing_is_logged(+ monkeypatch, caplog+) -> None:+ """The silent sibling: an empty scrub result loses a clause — say so."""+ monkeypatch.setattr(pipeline_module, "scrub_for_voice", _fake_scrub)+ with caplog.at_level(logging.WARNING, logger="jarvis.speech.pipeline"):+ spoken = await _spoken_sentences(+ ["Der Bericht ist fertig. ", f"{_VANISH} Rest. ",+ "Sonst noch was?"],+ "de",+ )++ assert spoken == ["Der Bericht ist fertig.", "Sonst noch was?"]+ dropped = [r for r in caplog.records if "DROPPED" in r.getMessage()]+ assert len(dropped) == 1+ assert "empty after scrub" in dropped[0].getMessage()++[email protected]("lang", ["de", "en", "es"])+async def test_fully_filtered_turn_still_speaks_the_fallback_once(+ monkeypatch, lang: str+) -> None:+ """Dropping per sentence must not turn a filtered turn into silence.++ Every locale gets ITS phrase — the runtime-output-language doctrine holds+ for the fallback too.+ """+ monkeypatch.setattr(pipeline_module, "scrub_for_voice", _fake_scrub)+ spoken = await _spoken_sentences(+ [f"{_POISON} eins. ", f"{_POISON} zwei."], lang+ )+ assert spoken == [FALLBACK_PHRASES[lang]]+++async def test_healthy_turn_never_gets_a_fallback_appended(monkeypatch) -> None:+ monkeypatch.setattr(pipeline_module, "scrub_for_voice", _fake_scrub)+ spoken = await _spoken_sentences(+ ["Das ist gut. ", "Das ist besser. ", "Fertig!"], "de"+ )+ assert spoken == ["Das ist gut.", "Das ist besser.", "Fertig!"]+++async def test_ordinal_answer_reaches_tts_as_one_utterance(monkeypatch) -> None:+ """OF-12 through the real producer, not just the splitter helper."""+ monkeypatch.setattr(pipeline_module, "scrub_for_voice", _fake_scrub)+ spoken = await _spoken_sentences(+ ["Am ", "1. ", "Jan", "uar ", "geht ", "es ", "los. ", "Dann ", "ruhe."],+ "de",+ )+ assert spoken == ["Am 1. Januar geht es los.", "Dann ruhe."]