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.

chore: auto-save WIP via Claude stop-hook safety net (2026-06-30 12:56)

Ruben Lütkeb96c28830a0e
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 0a86edcc89..f0b0753fd8 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -1763,8 +1763,12 @@ class VoiceConfig(BaseModel):
# genuinely new command is mis-attached.
continuation_grace_ms: int = 2500
# Max fragments coalesced into one turn before the next utterance is a fresh
- # turn (mirrors completion_max_chain — bounds indefinite chaining).
- continuation_max_chain: int = 3
+ # turn (mirrors completion_max_chain — bounds indefinite chaining). Set
+ # generously: users who correct themselves in several short bursts while the
+ # brain is still thinking ("…nicht australische" → "Australien oder so, nein"
+ # → "sondern der weiteste Ort") chain many fragments into ONE intended
+ # prompt; a low cap drops the earliest context on the (cap+1)-th fragment.
+ continuation_max_chain: int = 8
# Floor (seconds) below which the canned "that took too long, say it again"
# phrase is structurally SUPPRESSED, as a stale-state guard. None of the
# three timeout paths (20 s no-first-frame ceiling / 30 s no-progress stall /
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index ecc235013e..391b9a7751 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -92,6 +92,12 @@ class TranscriptPartial(Event):
@dataclass(frozen=True, slots=True)
class TranscriptFinal(Event):
transcript: Transcript | None = None
+ # True when this finalized utterance will be re-attached to the still-open
+ # turn by the continuation-recombine path (the brain is mid-thinking and the
+ # window is live). The SessionRecorder reads this to record the coalesced
+ # fragments as ONE transcript turn instead of splitting them — so the
+ # Transcription view shows the single prompt the brain actually processes.
+ continues_previous: bool = False
@dataclass(frozen=True, slots=True)
diff --git a/jarvis/marketplace/plugin_relevance.py b/jarvis/marketplace/plugin_relevance.py
index aaf2d30c3e..68510e7f45 100644
--- a/jarvis/marketplace/plugin_relevance.py
+++ b/jarvis/marketplace/plugin_relevance.py
@@ -1,27 +1,55 @@
"""Per-turn relevance gate for plugin tools. Keyword-only, no LLM, no IO (AP-9).
-A plugin tool is namespaced "<plugin_id>/<tool>". We keep a plugin's tools when
-its usage-card keywords match the utterance. Non-namespaced tools (the native
-router tools) are never touched.
-
-Gating triggers on the TOTAL number of plugin tools, not the plugin count: a
-single heavy plugin (e.g. GitHub exposes ~37 tools) already bloats the surface,
-while a couple of light plugins do not. So we skip gating only while the total
-plugin-tool count is <= ``max_unfiltered_tools`` (over-offering a handful beats
-wrongly dropping a relevant one); above that we keep only the plugins whose
-usage-card keywords match the utterance. Gating is plugin-granular: a matched
-plugin contributes all its tools, an unmatched one contributes none.
+A plugin tool is namespaced ``<plugin_id>/<tool>``. We keep a plugin's tools
+only when the turn actually SIGNALS that plugin; a connected-but-unmentioned
+plugin/MCP server is dropped so it is never offered to the brain just because it
+happens to be connected. Non-namespaced tools (the native router tools) are
+never touched.
+
+A plugin is relevant this turn when EITHER of these holds:
+
+ * the user explicitly NAMES it — its id, or a separator-stripped human form, so
+ "NotebookLM" / "notebook lm" / "notebook-lm" all match the id
+ ``notebooklm-mcp``; or
+ * it has a usage card whose keywords match the utterance.
+
+A card-less plugin/MCP that the user did NOT name is NOT relevant — its only
+cheap signal is its own name, so when the name is absent it stays hidden.
+(Authoring a usage card adds richer keywords; the explicit-name path is the
+always-available escape hatch.)
+
+This replaces the old fail-open behavior — keep-if-no-card plus a small-surface
+bypass that skipped the gate entirely for tiny surfaces. Together those let a
+connected MCP server with no card (e.g. ``notebooklm-mcp``) survive on an
+unrelated turn: a plain flight question reflexively fired
+``notebooklm-mcp/chat_configure``, wasting ~35s before timing out. We now run the
+per-plugin relevance decision for EVERY connected plugin regardless of surface
+size — a tiny surface of carded plugins is still gated correctly by their cards,
+and a tiny surface of card-less MCP servers is exactly what must be gated.
+
+We deliberately derive the card-less signal from the plugin's NAME only — not
+from its tool names or descriptions, which are generic verbs ("create",
+"configure", "chat", "report") that would re-introduce the exact over-trigger
+this gate removes. Richer keywords belong in a hand-authored usage card.
"""
from __future__ import annotations
+import re
from typing import Any
from jarvis.marketplace.usage_cards.loader import load_usage_card
-# Above this many plugin tools in the turn's surface, gate by keywords. Chosen
-# so a single connected GitHub/Linear-class plugin (35-37 tools) trips the gate
-# while a couple of light plugins (a few tools each) stay fully visible.
-_DEFAULT_MAX_UNFILTERED_TOOLS = 12
+# Common MCP-server id suffixes that are not part of the spoken product name —
+# stripped before deriving the human-readable form ("notebooklm-mcp" -> the name
+# "notebooklm", not "notebooklm mcp").
+_ID_SUFFIXES = ("-mcp", "_mcp", "-server", "_server")
+
+# Minimum length of a plugin's normalized name token before we accept a bare
+# substring match against the (also normalized) utterance — guards a 2-3 char id
+# from matching random letters inside an unrelated word.
+_MIN_NAME_TOKEN = 4
+
+_NON_ALNUM = re.compile(r"[^a-z0-9]+")
def _plugin_id_of(tool_name: str) -> str | None:
@@ -29,24 +57,65 @@ def _plugin_id_of(tool_name: str) -> str | None:
return pid if sep else None
-def filter_plugin_tools(
- user_text: str,
- tools: list[Any],
- *,
- max_unfiltered_tools: int = _DEFAULT_MAX_UNFILTERED_TOOLS,
-) -> list[Any]:
- plugin_tools = [t for t in tools if _plugin_id_of(t.name)]
- if len(plugin_tools) <= max_unfiltered_tools:
- # Small surface — keep everything, no bloat and no wrong-drop risk.
- return list(tools)
-
- plugin_ids = {pid for t in plugin_tools if (pid := _plugin_id_of(t.name))}
- relevant: set[str] = set()
- for pid in plugin_ids:
- card = load_usage_card(pid)
- # No card => can't gate it => keep it (conservative).
- if card is None or card.matches(user_text):
- relevant.add(pid)
+def _normalize(text: str) -> str:
+ """Lowercase and drop every non-alphanumeric char, so spacing/punctuation
+ variants of a plugin name collapse to one token ("Notebook LM" ->
+ "notebooklm")."""
+ return _NON_ALNUM.sub("", (text or "").lower())
+
+
+def _name_tokens(plugin_id: str) -> set[str]:
+ """Normalized name tokens the user could utter to NAME this plugin: the full
+ id (separators removed) plus the same with a trailing server-suffix stripped.
+
+ Short tokens (< ``_MIN_NAME_TOKEN``) are dropped to avoid spurious substring
+ hits inside unrelated words. Keyword-only, no IO.
+ """
+ low = plugin_id.lower()
+ candidates = {low}
+ for suffix in _ID_SUFFIXES:
+ if low.endswith(suffix):
+ candidates.add(low[: -len(suffix)])
+ return {tok for c in candidates if len(tok := _normalize(c)) >= _MIN_NAME_TOKEN}
+
+
+def _utterance_names_plugin(plugin_id: str, user_norm: str) -> bool:
+ if not user_norm:
+ return False
+ return any(tok in user_norm for tok in _name_tokens(plugin_id))
+
+
+def _plugin_is_relevant(plugin_id: str, user_text: str, user_norm: str) -> bool:
+ # 1. The user said the plugin's name -> always relevant (works even without a
+ # card, and even if a card's keywords happen to miss the name itself).
+ if _utterance_names_plugin(plugin_id, user_norm):
+ return True
+ # 2. A usage card gates by its curated keywords.
+ card = load_usage_card(plugin_id)
+ if card is not None:
+ return card.matches(user_text)
+ # 3. Card-less and un-named -> not signaled this turn. No fail-open: a
+ # connected MCP server must EARN its place on the turn, not ride along.
+ return False
+
+
+def filter_plugin_tools(user_text: str, tools: list[Any]) -> list[Any]:
+ """Drop namespaced plugin tools the turn does not signal; keep native tools.
+
+ Defensive: a malformed tool name simply yields no plugin id and is treated as
+ native (kept). Callers additionally wrap this in try/except so a gate fault
+ can never blind the brain on the voice path.
+ """
+ plugin_ids = {pid for t in tools if (pid := _plugin_id_of(t.name))}
+ if not plugin_ids:
+ return list(tools) # nothing namespaced to gate
+
+ user_norm = _normalize(user_text)
+ relevant = {
+ pid
+ for pid in plugin_ids
+ if _plugin_is_relevant(pid, user_text, user_norm)
+ }
kept: list[Any] = []
for t in tools:
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index 0aa3fec2ea..381c2248ff 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -475,6 +475,26 @@ class SessionRecorder:
# session — see BUG-008 history and the BUG_TRANSCRIPT_OVERWRITE entry.
cur = self._state.current_turn
if cur is not None and cur.user_text and not cur.finalized:
+ # Continuation-recombine: the user kept talking while the brain was
+ # still thinking, so the pipeline re-thinks the COMBINED sentence as
+ # ONE turn (TranscriptFinal.continues_previous). Mirror that here —
+ # APPEND the new fragment to the open turn instead of finalizing it
+ # and opening a new one — so the Transcription view shows the single
+ # prompt the brain processes, not 2-3 split user turns.
+ #
+ # When it is NOT a continuation we keep splitting (below): that guard
+ # exists so multi-utterance sessions with no SPEAKING boundary
+ # (brain returned suppress_response) don't overwrite each other into
+ # the last word — see BUG-008 history / the BUG_TRANSCRIPT_OVERWRITE
+ # entry.
+ if getattr(event, "continues_previous", False) and event.transcript is not None:
+ frag = event.transcript.text
+ if frag:
+ cur.user_text = f"{cur.user_text} {frag}".strip()
+ lang = getattr(event.transcript, "language", None) or self._state.language
+ cur.user_lang = lang
+ cur.transcript_final_ms = ts_ms
+ return
self._finalize_current_turn(end_ms=ts_ms)
self._ensure_turn_open(ts_ms)
diff --git a/jarvis/speech/continuation_window.py b/jarvis/speech/continuation_window.py
index 6376998d2d..a53c7772a7 100644
--- a/jarvis/speech/continuation_window.py
+++ b/jarvis/speech/continuation_window.py
@@ -95,6 +95,20 @@ class ContinuationWindow:
return
self._deadline_ns = None
+ def is_live(self) -> bool:
+ """True if the NEXT utterance WOULD recombine — armed, not expired, and
+ under the chain cap. NON-mutating mirror of ``try_recombine``'s gate, so
+ a caller (e.g. the pipeline tagging ``TranscriptFinal.continues_previous``
+ before dispatch) can learn the recombine decision without consuming the
+ window. Fail-safe: never raises."""
+ if not self.is_armed:
+ return False
+ if self._deadline_ns is not None and self._clock() > self._deadline_ns:
+ return False
+ if self._chain >= self._max_chain:
+ return False
+ return True
+
def try_recombine(self, new_text: str) -> str | None:
"""Return ``prior + new`` if a continuation is live, else ``None``.
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index bc6c798f60..7a95e26048 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -321,12 +321,35 @@ _STT_UNAVAILABLE_PHRASE: dict[str, str] = {
# AD-OE6 zero-silent-drop fallback for a brain TURN that times out. Live bug
# 2026-05-29: "kannst du Claude Code öffnen" stalled the Gemini stream; the
# brain-timeout path returned to LISTENING in SILENCE (and idle_timeout
-# pre-empted brain_timeout, so the turn just hung up with no feedback). Short,
-# bilingual, TTS-clean (``_speak`` does not scrub).
-_BRAIN_TIMEOUT_PHRASE: dict[str, str] = {
- "de": "Entschuldige, ich habe die Antwort nicht rechtzeitig fertigbekommen.",
- "en": "Sorry, I couldn't finish the answer in time.",
- "es": "Lo siento, no pude terminar la respuesta a tiempo.",
+# pre-empted brain_timeout, so the turn just hung up with no feedback).
+#
+# Honest, cause-aware messaging (live complaint 2026-06-30). The old single
+# phrase ("Sorry, I couldn't finish the answer in time.") explained NOTHING:
+# a slow MCP/plugin tool hung ~35 s, the turn timed out, and Jarvis apologised
+# for "taking too long" with no reason. Honesty over guessing (CLAUDE.md §1.4):
+# • TOOL-STALL — the turn was beheaded mid-tool-loop (no first audio frame,
+# i.e. the assistant was blocked waiting on a tool/stage that never
+# returned) OR a desktop (computer_use) tool was demonstrably active when
+# the stall fired: name that honest cause. The concrete tool NAME lives in
+# the brain's tool-use loop (jarvis/brain/manager.py), not reachable from
+# here without coupling, so we name the generic-but-true cause.
+# • NO-ANSWER — a bare provider stall / total cap with no tool evidence:
+# honestly admit we could not find it out, never the vague "took too long".
+# Both are short, TTS-clean (``_speak`` does not scrub — no em-dash, two short
+# sentences), and carry all supported locales (de/en/es). String-only: NO LLM
+# call in this timeout/scrub path (AP-11). Resolved through the ONE output-
+# language decision via ``_resolve_timeout_phrase`` below (CLAUDE.md §1 — no
+# per-layer language re-derivation).
+_TIMEOUT_TOOL_STALL_PHRASE: dict[str, str] = {
+ "de": "Ich habe rechtzeitig keine Antwort bekommen. Ein Tool, auf das ich gewartet habe, hat nicht reagiert.",
+ "en": "I couldn't get an answer in time. A tool I was waiting on didn't respond.",
+ "es": "No pude obtener una respuesta a tiempo. Una herramienta que esperaba no respondió.",
+}
+
+_TIMEOUT_NO_ANSWER_PHRASE: dict[str, str] = {
+ "de": "Das konnte ich gerade nicht herausfinden.",
+ "en": "I couldn't find that out just now.",
+ "es": "No pude averiguar eso ahora mismo.",
}
# AD-OE6 zero-silent-drop fallback for an ABANDONED incomplete utterance. When
@@ -385,6 +408,31 @@ def _phrase_lang(lang: str | None) -> str:
code = normalize_language_tag(lang)
return code if code in _PHRASE_LANGS else DEFAULT_LOCALE
+
+# Timeout sites that PROVE the assistant was blocked waiting on a downstream
+# tool/stage when the turn timed out: a no-first-frame beheading means the brain
+# produced no first audio frame because it was still inside a tool call that
+# never returned. Such a site always speaks the honest TOOL-STALL phrase. The
+# stream-stall / total-cap sites only do so when a desktop tool was demonstrably
+# active (``_long_tool_last_activity``); otherwise they carry no tool evidence
+# and admit the honest NO-ANSWER outcome instead.
+_TIMEOUT_TOOL_STALL_SITES: frozenset[str] = frozenset({"empty_after_no_first_frame"})
+
+
+def _resolve_timeout_phrase(site: str, lang: str, *, tool_active: bool) -> str:
+ """Pick the honest, cause-aware timeout phrase for ``site``.
+
+ Resolves language through the ONE shared decision (``_phrase_lang``) — never
+ a per-layer re-derivation (CLAUDE.md §1). String-only, no LLM call (AP-11).
+ Names a tool cause when the turn was beheaded mid-tool-loop (no first frame)
+ or a desktop tool was active; otherwise honestly admits no answer was found.
+ """
+ key = _phrase_lang(lang)
+ if site in _TIMEOUT_TOOL_STALL_SITES or tool_active:
+ return _TIMEOUT_TOOL_STALL_PHRASE[key]
+ return _TIMEOUT_NO_ANSWER_PHRASE[key]
+
+
# Transient STT failures worth a retry: cloud rate-limit (429) and transient
# gateway/server errors (5xx). Anything else (401 bad key, 400 bad audio) is a
# hard error and must NOT be retried — retrying only hammers the provider.
@@ -1167,6 +1215,13 @@ class SpeechPipeline:
# turn ends with an audible timeout notice instead of silent LISTENING
# (AD-OE6; live bug 2026-06-10 14:34). Reset at every turn finalize.
self._playback_aborted_no_first_frame = False
+ # Per-turn terminal mark: a timeout / "couldn't finish" notice already
+ # spoke for this utterance, so the outcome is closed. The double-answer
+ # guard in ``_speak`` reads it to suppress a late/abandoned brain ANSWER
+ # (kind="reply") that would otherwise speak a SECOND time for the same
+ # content (live complaint 2026-06-30: a stalled tool timed out, then the
+ # turn re-answered). Re-armed at every utterance finalize.
+ self._brain_timeout_spoken_this_turn = False
self._pending_context_flush_s = max(0.5, float(pending_context_flush_s))
self._pending_flush_task: asyncio.Task[None] | None = None
self._vad = SileroEndpointer(
@@ -5122,6 +5177,10 @@ class SpeechPipeline:
# Per-turn re-arm of the beheaded-playback mark (BUG-032 lesson: never
# let a previous turn's abort leak into this turn's empty-turn handling).
self._playback_aborted_no_first_frame = False
+ # Per-turn re-arm of the timeout-terminal mark: a fresh utterance must
+ # be free to speak its answer even if the PREVIOUS turn ended in a
+ # timeout notice (the double-answer guard is scoped to ONE utterance).
+ self._brain_timeout_spoken_this_turn = False
# Anchor this brain-bound turn's wall-clock here — the single point past
# all early returns (forced-cut carry, empty PCM, wake-only) where the
# turn commits to the brain. The floor guard in _speak_brain_timeout uses
@@ -5152,8 +5211,24 @@ class SpeechPipeline:
transcript.language,
getattr(transcript, "confidence", 0.0) or 0.0,
)
+ # Tag whether this finalized utterance will be re-attached to the still-
+ # open turn by the continuation-recombine path (brain mid-thinking, window
+ # live). NON-mutating mirror of _maybe_recombine_continuation's gate
+ # (enabled + armed/live + not a cancel phrase) — so the SessionRecorder
+ # records the coalesced fragments as ONE turn instead of splitting them.
+ _cont_win = getattr(self, "_continuation_window", None)
+ continues_previous = bool(
+ getattr(self, "_continuation_interrupt_enabled", False)
+ and _cont_win is not None
+ and _cont_win.is_live()
+ and not is_cancel(transcript.text)
+ )
await self._publish_event(
- TranscriptFinal(source_layer="speech.stt", transcript=transcript)
+ TranscriptFinal(
+ source_layer="speech.stt",
+ transcript=transcript,
+ continues_previous=continues_previous,
+ )
)
if self._latency_tracker is not None:
self._latency_tracker.mark(LatencyPhase.STT_FINALIZE)
@@ -7108,7 +7183,18 @@ class SpeechPipeline:
return
log.warning("brain-timeout phrase spoken: " + payload, *fields)
picker_lang = _phrase_lang(lang)
- phrase = _BRAIN_TIMEOUT_PHRASE[picker_lang]
+ # Cause-aware, honest phrase (live complaint 2026-06-30): name a tool
+ # cause when the turn was beheaded mid-tool-loop (no first frame) or a
+ # desktop tool was demonstrably active; otherwise honestly admit no
+ # answer was found. Resolved through the one output-language decision.
+ tool_active = getattr(self, "_long_tool_last_activity", 0.0) > 0.0
+ phrase = _resolve_timeout_phrase(site, lang, tool_active=tool_active)
+ # The outcome is now terminal for this utterance: arm the double-answer
+ # guard BEFORE speaking so a concurrently-abandoned brain stream that
+ # later reaches ``_speak`` (kind="reply") is suppressed, never voiced as
+ # a second answer for the same content. Set only here — past the floor
+ # guard's early return — so a floor-suppressed (no-op) call never arms it.
+ self._brain_timeout_spoken_this_turn = True
try:
await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
await self._speak(phrase, language=picker_lang, kind=SPOKEN_KIND_TIMEOUT)
@@ -7415,6 +7501,22 @@ class SpeechPipeline:
if getattr(self, "_muted", False):
log.debug("_speak suppressed — voice muted")
return False
+ # Double-answer guard (live complaint 2026-06-30): once a timeout /
+ # "couldn't finish" notice closed THIS utterance, an ordinary brain
+ # ANSWER (kind="reply", the default) must NOT also be voiced — a stalled
+ # tool that timed out and then re-answered for the same content. Gate
+ # ONLY the brain answer: every canned notice (timeout / clarify / ack /
+ # unavailable) and every background mission readback (completion /
+ # subagent / announcement) carries its own kind and is intentionally
+ # exempt, so a legitimately-spawned later result still speaks. The flag
+ # re-arms at the next utterance finalize. Before ``_emit_spoken`` so a
+ # suppressed answer — never actually voiced — is not logged.
+ if kind == "reply" and getattr(self, "_brain_timeout_spoken_this_turn", False):
+ log.info(
+ "Brain answer suppressed — a timeout notice already closed this "
+ "turn (no double-answer)."
+ )
+ return False
# Document the voiced phrase in the session log (no-op for the reply
# sentinel and empty text). After the mute check, so a suppressed
# phrase — which is never actually voiced — is not recorded.
diff --git a/jarvis/ui/web/frontend/pythonw_Zj1e4At5Rl.png b/jarvis/ui/web/frontend/pythonw_Zj1e4At5Rl.png
new file mode 100644
index 0000000000..b23ab6e31e
Binary files /dev/null and b/jarvis/ui/web/frontend/pythonw_Zj1e4At5Rl.png differ
diff --git a/scripts/config-soll.json b/scripts/config-soll.json
index 84cc1a25a0..1e00842d7b 100644
--- a/scripts/config-soll.json
+++ b/scripts/config-soll.json
@@ -89,6 +89,6 @@
"model": "gemini-3.5-flash"
},
"brain.providers.openrouter": {
- "model": "nvidia/nemotron-3.5-content-safety:free"
+ "model": "anthropic/claude-opus-4.8-fast"
}
}
diff --git a/tests/unit/sessions/test_recorder_lifecycle.py b/tests/unit/sessions/test_recorder_lifecycle.py
index ea2d03bd52..406eefa1bb 100644
--- a/tests/unit/sessions/test_recorder_lifecycle.py
+++ b/tests/unit/sessions/test_recorder_lifecycle.py
@@ -17,7 +17,7 @@ from jarvis.sessions.recorder import SessionRecorder
from jarvis.sessions.store import SessionStore
-def _final(text: str, lang: str = "de") -> TranscriptFinal:
+def _final(text: str, lang: str = "de", *, continues: bool = False) -> TranscriptFinal:
return TranscriptFinal(
source_layer="speech.stt",
transcript=Transcript(
@@ -26,6 +26,7 @@ def _final(text: str, lang: str = "de") -> TranscriptFinal:
confidence=0.9,
is_partial=False,
),
+ continues_previous=continues,
)
@@ -154,6 +155,113 @@ async def test_multiple_transcript_finals_in_suppressed_session_keep_each_uttera
store.close()
+async def test_continuation_finals_merge_into_one_turn(tmp_path) -> None:
+ """When the user keeps talking while the brain is still thinking, the pipeline
+ tags the follow-up TranscriptFinals with ``continues_previous=True``
+ (continuation-recombine). The recorder must record them as ONE turn carrying
+ the combined user_text — matching the single prompt the brain re-thinks —
+ instead of 2-3 split user turns (the maintainer's "drei Prompts" complaint,
+ transcript session 2026-06-30)."""
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await bus.publish(
+ VoiceSessionStarted(
+ source_layer="speech.pipeline",
+ session_id="s-cont",
+ wake_keyword="hey_jarvis",
+ language="de",
+ )
+ )
+ await bus.publish(ListeningStarted(source_layer="speech"))
+ # First utterance, then two follow-ups WHILE the brain is still thinking
+ # (no SPEAKING boundary yet) — flagged as continuations.
+ await bus.publish(_final("Was ist der weiteste Ort"))
+ await bus.publish(_final("nicht australische", continues=True))
+ await bus.publish(_final("sondern wirklich der weiteste", continues=True))
+ # Brain finally speaks the combined answer → SPEAKING boundary finalizes.
+ await bus.publish(
+ SystemStateChanged(
+ source_layer="speech", previous="LISTENING", new_state="SPEAKING"
+ )
+ )
+ await bus.publish(
+ ResponseGenerated(source_layer="brain", text="Das ist Sydney.", language="de")
+ )
+ await bus.publish(
+ SystemStateChanged(
+ source_layer="speech", previous="SPEAKING", new_state="LISTENING"
+ )
+ )
+ await bus.publish(
+ VoiceSessionEnded(
+ source_layer="speech.pipeline",
+ session_id="s-cont",
+ hangup_reason="voice_pattern",
+ )
+ )
+
+ turns = store.get_turns("s-cont")
+ user_texts = [t.user_text for t in turns]
+ assert len(turns) == 1, user_texts
+ assert (
+ turns[0].user_text
+ == "Was ist der weiteste Ort nicht australische sondern wirklich der weiteste"
+ )
+
+
+async def test_continuation_merges_then_a_fresh_utterance_splits(tmp_path) -> None:
+ """A continuation merges into the open turn, but a genuinely new utterance
+ AFTER the brain has spoken (continues_previous=False) starts a fresh turn —
+ so merge and split coexist correctly."""
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await bus.publish(
+ VoiceSessionStarted(
+ source_layer="speech.pipeline",
+ session_id="s-mix",
+ wake_keyword="hey_jarvis",
+ language="de",
+ )
+ )
+ await bus.publish(ListeningStarted(source_layer="speech"))
+ await bus.publish(_final("frage eins"))
+ await bus.publish(_final("mit zusatz", continues=True)) # merges into turn 0
+ await bus.publish(
+ SystemStateChanged(
+ source_layer="speech", previous="LISTENING", new_state="SPEAKING"
+ )
+ )
+ await bus.publish(
+ ResponseGenerated(source_layer="brain", text="Antwort eins.", language="de")
+ )
+ await bus.publish(
+ SystemStateChanged(
+ source_layer="speech", previous="SPEAKING", new_state="LISTENING"
+ )
+ )
+ # New, unrelated utterance after the answer → fresh turn (not a continuation).
+ await bus.publish(_final("ganz neue frage"))
+ await bus.publish(
+ VoiceSessionEnded(
+ source_layer="speech.pipeline",
+ session_id="s-mix",
+ hangup_reason="voice_pattern",
+ )
+ )
+
+ turns = store.get_turns("s-mix")
+ user_texts = [t.user_text for t in turns]
+ assert user_texts == ["frage eins mit zusatz", "ganz neue frage"]
+
+
@pytest.mark.asyncio
async def test_voice_confirm_pending_turn_is_flagged_awaiting_confirmation(
tmp_path,
diff --git a/tests/unit/speech/test_clarify_question.py b/tests/unit/speech/test_clarify_question.py
index 4823ee0d5a..452ede4acb 100644
--- a/tests/unit/speech/test_clarify_question.py
+++ b/tests/unit/speech/test_clarify_question.py
@@ -306,9 +306,11 @@ async def test_beheaded_turn_speaks_timeout_notice_despite_clarify_off() -> None
assert len(pipe._spoken) == 1, pipe._spoken
spoken_text, spoken_lang = pipe._spoken[0]
- from jarvis.speech.pipeline import _BRAIN_TIMEOUT_PHRASE
+ # A no-first-frame beheading means the assistant was blocked waiting on a
+ # tool that never returned — name that honest cause, not the old vague phrase.
+ from jarvis.speech.pipeline import _TIMEOUT_TOOL_STALL_PHRASE
- assert spoken_text == _BRAIN_TIMEOUT_PHRASE["de"]
+ assert spoken_text == _TIMEOUT_TOOL_STALL_PHRASE["de"]
assert spoken_lang == "de"
# The mark is consumed — the next empty turn must not re-fire the notice.
assert pipe._playback_aborted_no_first_frame is False
diff --git a/tests/unit/speech/test_continuation_window.py b/tests/unit/speech/test_continuation_window.py
index ec4582885f..52f36a1953 100644
--- a/tests/unit/speech/test_continuation_window.py
+++ b/tests/unit/speech/test_continuation_window.py
@@ -113,3 +113,43 @@ def test_speech_resume_while_in_flight_is_harmless_noop():
# No mark_idle call — window is still in flight (deadline None)
w.note_speech_resumed() # should be a pure no-op
assert w.try_recombine("zweiter teil") == "erster teil zweiter teil"
+
+
+# ---------------------------------------------------------------------------
+# is_live — non-mutating mirror of try_recombine's gate. The pipeline uses it to
+# tag TranscriptFinal.continues_previous so the recorder merges the coalesced
+# fragments into ONE transcript turn (it must NOT consume the window).
+# ---------------------------------------------------------------------------
+
+
+def test_is_live_false_when_unarmed():
+ w = ContinuationWindow(grace_ms=2500, max_chain=3, clock=FakeClock())
+ assert w.is_live() is False
+
+
+def test_is_live_true_while_in_flight():
+ w = ContinuationWindow(grace_ms=2500, max_chain=3, clock=FakeClock())
+ w.note_dispatch("erster teil", continued=False)
+ assert w.is_live() is True
+
+
+def test_is_live_tracks_grace_and_never_mutates():
+ clk = FakeClock()
+ w = ContinuationWindow(grace_ms=2500, max_chain=3, clock=clk)
+ w.note_dispatch("erster teil", continued=False)
+ w.mark_idle()
+ clk.advance_ms(2000) # within grace
+ assert w.is_live() is True
+ assert w.is_armed # not consumed
+ assert w.try_recombine("zweiter teil") == "erster teil zweiter teil"
+ clk.advance_ms(2000) # past the grace deadline
+ assert w.is_live() is False # expired
+ assert w.is_armed # is_live did NOT clear it (try_recombine does)
+
+
+def test_is_live_false_at_chain_cap():
+ w = ContinuationWindow(grace_ms=9999, max_chain=2, clock=FakeClock())
+ w.note_dispatch("a", continued=False) # chain=1
+ assert w.is_live() is True
+ w.note_dispatch("a b", continued=True) # chain=2 == max
+ assert w.is_live() is False
diff --git a/tests/unit/speech/test_speak_playback_timeout.py b/tests/unit/speech/test_speak_playback_timeout.py
index 7ab6c55e47..391b63e736 100644
--- a/tests/unit/speech/test_speak_playback_timeout.py
+++ b/tests/unit/speech/test_speak_playback_timeout.py
@@ -26,9 +26,9 @@ from jarvis.core.bus import EventBus
from jarvis.core.config import JarvisConfig
from jarvis.core.protocols import AudioChunk
from jarvis.speech.pipeline import (
- SPOKEN_KIND_COMPLETION,
_TIMEOUT_NO_ANSWER_PHRASE,
_TIMEOUT_TOOL_STALL_PHRASE,
+ SPOKEN_KIND_COMPLETION,
SpeechPipeline,
)
diff --git a/tests/unit/speech/test_turn_taking.py b/tests/unit/speech/test_turn_taking.py
index b96a1b3c0a..7ae5b7b033 100644
--- a/tests/unit/speech/test_turn_taking.py
+++ b/tests/unit/speech/test_turn_taking.py
@@ -10,7 +10,6 @@ from jarvis.core.events import TranscriptFinal, TranscriptionUpdate
from jarvis.core.protocols import AudioChunk, Transcript
from jarvis.speech.pipeline import (
_TIMEOUT_NO_ANSWER_PHRASE,
- _TIMEOUT_TOOL_STALL_PHRASE,
SpeechPipeline,
TurnTakingState,
)
@@ -637,7 +636,7 @@ async def test_streaming_long_tool_loop_speaks_real_answer_not_timeout() -> None
loop round — exactly what ``ToolUseLoop`` does (tool_use_loop.py:400). Before
the fix, ``_await_playback`` only honoured the computer_use heartbeat, so the
20 s ceiling beheaded the working turn: the answer was discarded and the
- empty-turn handler spoke ``_BRAIN_TIMEOUT_PHRASE`` ("…zu lange gedauert…").
+ empty-turn handler spoke a canned timeout fallback ("…zu lange gedauert…").
This drives the REAL streaming path end-to-end (``_handle_utterance`` →
``_run_brain_with_stall_guard`` → ``_brain_streaming`` → ``_await_playback``)