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(voice): preserve listening after long tool responses

rubenluetke10-beep0476e4ea7731
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 57e63a815a..da3b29ca48 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -24,6 +24,17 @@ host's Tk bootstrap root cannot steal them.
Windows (OLE/WebView2) and macOS (AppKit/WKWebView) sources. P-15 records the
remaining GTK source gap; reveal/open actions remain available on Linux.
+**Voice termination diagnostics (2026-09-07).** The existing
+`VoiceSessionEnded` event accepts optional JSON text in `detail`; omitted
+metadata remains supported for realtime and older publishers. The recorder
+persists the producer and detail in its existing event payload, and plain-text
+and Markdown exports expose the final reason. Pipeline snapshots add control
+and timing evidence without recording raw model output. This uses the same
+stdlib/SQLite path on Windows, macOS and Linux, including headless installs;
+it needs no native capability probe. Contract tests cover serialization,
+persistence and export with and without diagnostics. Live audio and fresh
+single-key install verification are separate from these automated checks.
+
**Fix pass 2026-07-31:** P-28 fixed and removed. Codex subscription voice now
uses a parent-lifeline process-group supervisor on macOS and Linux, while
Windows retains kernel Job Object containment.
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 670e227500..3fa197f8e8 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1770,6 +1770,9 @@ class VoiceSessionEnded(Event):
hangup_reason: str = ""
turn_count: int = 0
duration_s: float = 0.0
+ # Optional JSON diagnostic snapshot captured by the terminating path.
+ # Empty on older publishers; never contains raw model output or secrets.
+ detail: str = ""
@dataclass(frozen=True, slots=True)
diff --git a/jarvis/sessions/diagnostics.py b/jarvis/sessions/diagnostics.py
new file mode 100644
index 0000000000..bd091ef878
--- /dev/null
+++ b/jarvis/sessions/diagnostics.py
@@ -0,0 +1,117 @@
+"""Read termination evidence without guessing missing historical measurements."""
+from __future__ import annotations
+
+import json
+import math
+from collections.abc import Iterable
+
+from .models import VoiceEventRow, VoiceSessionRow
+
+_SNAPSHOT_FIELDS = (
+ "hangup_pattern_matched", "hangup_pattern", "end_call_signal",
+ "legacy_farewell_matched", "single_turn_mode", "continue_listening_after_response",
+ "idle_timeout_s", "idle_deadline_monotonic", "last_activity_monotonic",
+ "last_answer_floor_monotonic", "turn_state", "previous_turn_state",
+ "assistant_work_active", "tool_active", "screen_active", "computer_use_active",
+ "input_error_type", "input_replay_overrun",
+)
+_EVENT_TIMESTAMPS = {
+ "UtteranceCaptured": "last_user_utterance_end_ms",
+ "TranscriptFinal": "last_user_transcript_final_ms",
+ "ToolCallStarted": "last_tool_start_ms",
+ "ToolCallCompleted": "last_tool_end_ms",
+ "BrainTurnStarted": "last_assistant_generation_start_ms",
+ "BrainTurnCompleted": "last_assistant_generation_end_ms",
+ "AudioOutFirst": "last_assistant_audio_start_ms",
+ "SpeechSpoken": "last_assistant_audio_confirmed_ms",
+}
+_LATENCY_TIMESTAMPS = {
+ "tts_request_sent": "last_tts_request_ms",
+ "tts_stream_done": "last_tts_stream_done_ms",
+}
+
+
+def _scalar(value: object) -> str | int | float | bool | None:
+ if isinstance(value, str):
+ return " ".join(value.split())[:240] or None
+ if isinstance(value, (int, float)):
+ try:
+ if math.isfinite(value):
+ return value
+ except OverflowError:
+ # JSON allows integers too large for the float finiteness check.
+ # Such a value is not a plausible timestamp or setting.
+ return None
+ return None
+
+
+def session_termination_diagnostics(
+ session: VoiceSessionRow, events: Iterable[VoiceEventRow],
+) -> dict[str, object]:
+ """Merge a terminal snapshot with recorded event times, never raw content.
+
+ Monotonic seconds are labelled separately from wall-clock epoch milliseconds.
+ Event timestamps are publication times; audio confirmation is not a guessed
+ TTS synthesis or hardware-playback boundary. Missing evidence stays null.
+ """
+ relevant = sorted(
+ (
+ event for event in events
+ if event.session_id == session.id
+ and (session.ended_ms is None or event.ts_ms <= session.ended_ms)
+ ),
+ key=lambda event: (event.ts_ms, event.seq or 0),
+ )
+ ended = next((event for event in reversed(relevant) if event.kind == "VoiceSessionEnded"), None)
+ snapshot: dict[str, object] = {}
+ if ended is not None:
+ detail = ended.payload.get("detail")
+ if isinstance(detail, str) and len(detail) <= 16_384:
+ try:
+ decoded = json.loads(detail)
+ except (ValueError, RecursionError):
+ # Legacy/malformed diagnostics must not break transcript export.
+ decoded = None
+ if isinstance(decoded, dict):
+ snapshot = {
+ field: value for field, value in decoded.items()
+ if field in _SNAPSHOT_FIELDS or field == "producer"
+ }
+ producer = _scalar(snapshot.get("producer"))
+ if not producer and ended is not None:
+ producer = _scalar(ended.payload.get("source_layer"))
+ result: dict[str, object] = {
+ "hangup_reason": session.hangup_reason or None,
+ "producer": producer,
+ "snapshot_recorded": bool(snapshot),
+ }
+ for field in _SNAPSHOT_FIELDS:
+ result[field] = _scalar(snapshot.get(field))
+ for field in (*_EVENT_TIMESTAMPS.values(), *_LATENCY_TIMESTAMPS.values()):
+ result[field] = None
+ result["last_state_transition"] = None
+ result["last_state_transition_ms"] = None
+ result["session_end_ms"] = session.ended_ms
+ for event in relevant:
+ field = _EVENT_TIMESTAMPS.get(event.kind)
+ if field:
+ result[field] = event.ts_ms
+ if event.kind == "LatencySpan":
+ phase = event.payload.get("phase")
+ if isinstance(phase, str) and phase in _LATENCY_TIMESTAMPS:
+ result[_LATENCY_TIMESTAMPS[phase]] = event.ts_ms
+ if event.kind == "SystemStateChanged":
+ previous = _scalar(event.payload.get("previous"))
+ current = _scalar(event.payload.get("new_state"))
+ if previous and current:
+ result["last_state_transition"] = f"{previous} -> {current}"
+ result["last_state_transition_ms"] = event.ts_ms
+ return result
+
+
+def diagnostic_value(value: object) -> str:
+ if value is None:
+ return "not recorded"
+ if isinstance(value, bool):
+ return str(value).lower()
+ return str(value)
diff --git a/jarvis/sessions/formatter.py b/jarvis/sessions/formatter.py
index 31552de733..7e950fff9e 100644
--- a/jarvis/sessions/formatter.py
+++ b/jarvis/sessions/formatter.py
@@ -1,23 +1,9 @@
-"""Markdown- und Plain-Text-Renderer fuer Voice-Sessions.
-
-Zwei Output-Formate:
-
-- ``markdown`` — strukturiert mit Headings/Listen, fuer Copy in Chat-
- Apps, Issues, Notion/Obsidian. Nutzt Emojis als visuelle Anker
- (🎤 User, 🧠 Jarvis, 🔧 Tool, ⏱ Latenz) — sind Single-Codepoints,
- kompatibel mit allen UTF-8-Targets.
-
-- ``plain`` — die *schlichte* Gespraechs-Transkription, die ein Mensch
- zum Weitergeben kopiert. Reiner Dialog mit ``Du:`` / ``Jarvis:`` als
- Sprecher, eine schlanke Kopfzeile (Datum + Dauer). Keine Emojis, keine
- Markdown-Marker und keine Pro-Turn-Telemetrie (Tier/Provider/Tokens/
- Kosten/Latenz) — diese Maschinen-Details leben im ``json``-Export.
- Beim Einfuegen in Chat, Notiz oder E-Mail entsteht so kein "AI-Slop".
-
-Beide Renderer arbeiten auf den gleichen ``VoiceSessionRow`` +
-``VoiceTurnRow``-Inputs aus ``store.py``. Die rohen ``VoiceEventRow``
-sind nicht im Output — das ist Detail-Replay-Daten und nicht fuer
-Copy-Paste-Konsum gedacht.
+"""Markdown and plain-text renderers for recorded voice sessions.
+
+Both formats preserve the audible dialogue and the final termination reason.
+Markdown adds per-turn metadata; plain text keeps those details out of the
+conversation. When recorded, termination diagnostics follow as an explicitly
+unspoken appendix. Raw event payloads remain available in the JSON export.
"""
from __future__ import annotations
@@ -26,6 +12,7 @@ from dataclasses import dataclass, replace
from datetime import UTC, datetime
from .constants import SPOKEN_KIND_WITHHELD
+from .diagnostics import diagnostic_value, session_termination_diagnostics
from .models import VoiceEventRow, VoiceSessionRow, VoiceTurnRow
@@ -147,9 +134,11 @@ def format_session_markdown(
turns: Iterable[VoiceTurnRow],
events: Iterable[VoiceEventRow] | None = None,
) -> str:
- """Markdown-Version fuer reichen Copy-Paste-Konsum."""
+ """Render a structured transcript for rich copy-and-paste targets."""
turns_list = list(turns)
- events_map = _events_by_turn(events)
+ events_list = list(events or [])
+ events_map = _events_by_turn(events_list)
+ termination = session_termination_diagnostics(session, events_list)
lines: list[str] = []
# --- Header ---
@@ -165,6 +154,9 @@ def format_session_markdown(
lines.append(f"- **Wake-Word:** {session.wake_keyword}")
if session.hangup_reason:
lines.append(f"- **Beendet durch:** {_pretty_hangup(session.hangup_reason)}")
+ if session.ended_ms is not None:
+ lines.append(f"- **Termination reason:** {diagnostic_value(termination['hangup_reason'])}")
+ lines.append(f"- **Termination producer:** {diagnostic_value(termination['producer'])}")
if session.total_cost_usd > 0:
lines.append(f"- **Kosten:** ${session.total_cost_usd:.4f}")
if session.total_tokens_in or session.total_tokens_out:
@@ -180,6 +172,7 @@ def format_session_markdown(
# --- Turns ---
if not turns_list:
lines.append("_(keine Turns aufgezeichnet)_")
+ lines.extend(_termination_details(termination))
return "\n".join(lines)
for display_index, t in enumerate(turns_list, start=1):
@@ -192,7 +185,7 @@ def format_session_markdown(
lines.append(f"> {t.user_text}")
lines.append("")
- # Brain-Meta-Zeile, nur wenn was substantielles da ist
+ # Only include brain metadata when a recorded value exists.
meta_parts: list[str] = []
if t.tier:
meta_parts.append(f"Tier: `{t.tier}`")
@@ -262,6 +255,7 @@ def format_session_markdown(
lines.append("---")
lines.append("")
+ lines.extend(_termination_details(termination))
return "\n".join(lines).rstrip() + "\n"
@@ -270,24 +264,19 @@ def format_session_plain(
turns: Iterable[VoiceTurnRow],
events: Iterable[VoiceEventRow] | None = None,
) -> str:
- """Schlichte Gespraechs-Transkription — reiner Dialog, kein Slop.
-
- Aufbau: eine Kopfzeile (``Voice-Session · Datum · Dauer``), dann jede
- Aeusserung mit ``Du:`` bzw. ``Jarvis:`` als Sprecher, durch Leerzeilen
- getrennt. Bewusst *weggelassen*: Emojis, Markdown, sowie jede
- Pro-Turn-Telemetrie (Tier/Provider/Model/Tokens/Kosten/Latenz/Tools).
- Wer diese Maschinen-Details braucht, nutzt den ``json``-Export.
-
- Every VOICED non-reply phrase (timeout / clarify / announcement text from
- the SpeechSpoken events) also appears here as a ``Jarvis:`` line — without
- a kind tag, to keep the dialogue clean. That way even the plain export
- documents everything the user heard.
+ """Render dialogue plus the session's final termination evidence.
+
+ The body uses speaker labels, without Markdown, emojis, or per-turn
+ cost/model telemetry. Supplemental audible phrases remain dialogue;
+ termination diagnostics are labelled as not spoken after the dialogue.
"""
turns_list = list(turns)
- events_map = _events_by_turn(events)
+ events_list = list(events or [])
+ events_map = _events_by_turn(events_list)
+ termination = session_termination_diagnostics(session, events_list)
lines: list[str] = []
- # --- Schlanke Kopfzeile: "Voice-Session · 07.06.2026, 19:24 · 1 min 42 s"
+ # Keep the date, mode and duration together in one compact header.
header_bits = [
_fmt_dt_human(session.started_ms),
f"Modus: {_pretty_voice_mode(session.voice_mode)}",
@@ -296,15 +285,19 @@ def format_session_plain(
if duration:
header_bits.append(duration)
lines.append("Voice-Session · " + " · ".join(header_bits))
+ if session.ended_ms is not None:
+ lines.append(
+ f"Ended by: {diagnostic_value(termination['hangup_reason'])}"
+ f" · Producer: {diagnostic_value(termination['producer'])}"
+ )
lines.append("")
if not turns_list:
lines.append("(keine Turns aufgezeichnet)")
+ lines.extend(_termination_details(termination))
return "\n".join(lines).rstrip() + "\n"
- # Reiner Dialog: pro Turn die vorhandenen Aeusserungen, durch Leer-
- # zeilen getrennt. Turns ohne Antwort (z.B. "auflegen") erzeugen keine
- # leere "Jarvis:"-Zeile.
+ # An unanswered turn must not produce an empty assistant speaker label.
blocks: list[str] = []
for t in turns_list:
if t.user_text:
@@ -317,14 +310,29 @@ def format_session_plain(
if blocks:
lines.append("\n\n".join(blocks))
+ lines.extend(_termination_details(termination))
return "\n".join(lines).rstrip() + "\n"
+def _termination_details(termination: dict[str, object]) -> list[str]:
+ if not termination["snapshot_recorded"]:
+ return []
+ lines = [
+ "", "Session termination diagnostics (not spoken):",
+ "Times ending in _ms are recorded event times in epoch milliseconds;",
+ "times ending in _monotonic are process-local seconds.",
+ ]
+ for key, value in termination.items():
+ if key not in {"snapshot_recorded", "hangup_reason", "producer"}:
+ lines.append(f"{key}: {diagnostic_value(value)}")
+ return lines
+
+
# --- Helpers ----------------------------------------------------------
def _local_dt(ts_ms: int) -> datetime:
- """Wall-clock-ms -> lokale ``datetime`` (eine Stelle fuer die TZ-Logik)."""
+ """Convert epoch milliseconds using the local timezone in one place."""
return datetime.fromtimestamp(ts_ms / 1000.0, tz=UTC).astimezone()
@@ -336,7 +344,7 @@ def _fmt_dt(ts_ms: int, *, time_only: bool = False) -> str:
def _fmt_dt_human(ts_ms: int) -> str:
- """Schlankes deutsches Datum fuer die Kopfzeile: ``07.06.2026, 19:24``."""
+ """Compact day-first date for the transcript header."""
return _local_dt(ts_ms).strftime("%d.%m.%Y, %H:%M")
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index 9c73679e56..8385c34dbd 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -1261,6 +1261,9 @@ def _payload_for(event: Event) -> dict[str, Any]:
"task_id", # TaskCancelled
}
payload: dict[str, Any] = {}
+ if isinstance(event, VoiceSessionEnded):
+ # Provenance matters when several independent paths can end a call.
+ payload["source_layer"] = event.source_layer
for k in fields_whitelist:
if not hasattr(event, k):
continue
diff --git a/jarvis/speech/hangup.py b/jarvis/speech/hangup.py
index 7b0158e64f..9df876d126 100644
--- a/jarvis/speech/hangup.py
+++ b/jarvis/speech/hangup.py
@@ -115,6 +115,14 @@ _HANGUP_PATTERNS: Final[tuple[str, ...]] = (
HANGUP_RE: Final[re.Pattern[str]] = re.compile("|".join(_HANGUP_PATTERNS), re.IGNORECASE)
+
+def matched_hangup_pattern(text: str) -> str | None:
+ """Identify the static matching branch for diagnostics without user text."""
+ return next(
+ (pattern for pattern in _HANGUP_PATTERNS if re.search(pattern, text, re.IGNORECASE)),
+ None,
+ )
+
# --- Brain control sentinel (post-brain, semantic) ------------------------
END_CALL_SIGNAL: Final[str] = "[[END_CALL]]"
@@ -124,6 +132,42 @@ def contains_end_signal(text: str | None) -> bool:
return bool(text) and END_CALL_SIGNAL in text
+# Semantic closure needs evidence in the USER's turn as well as the model's
+# sentinel. Match the complete speech act: an informational request that quotes
+# a farewell or describes a finished task must never become session control.
+# Gratitude alone is not closing intent, and neither is the assistant saying
+# that it has completed the requested work.
+_SEMANTIC_CLOSING_RE = re.compile(
+ r"\s*(?:(?:okay|ok|thanks|thank you|danke|gracias)[\s,.!]+)*" # i18n-allow
+ r"(?:(?:i think|i guess|ich glaube|ich denke|creo que)[\s,]+)?" # i18n-allow
+ r"(?:"
+ r"(?:we are|we're|i am|i'm) (?:done|finished)(?: (?:here|for now|for today))?"
+ r"|(?:that is|that's|that was) all(?: (?:for now|for today|i needed))?"
+ r"|that will be all|nothing else(?: for now)?|no more questions"
+ r"|i (?:have|need) to go|let's stop here|you can go now"
+ r"|wir sind (?:durch|fertig)(?: für heute)?" # i18n-allow
+ r"|ich bin (?:durch|fertig)(?: für heute)?" # i18n-allow
+ r"|das war'?s(?: für heute)?|das ist alles|mehr brauche ich nicht" # i18n-allow
+ r"|keine weiteren fragen|ich muss (?:los|gehen)|du kannst gehen" # i18n-allow
+ r"|eso es todo(?: por (?:ahora|hoy))?|hemos terminado|ya terminamos"
+ r"|no necesito nada más|no tengo más preguntas|me tengo que ir"
+ r")"
+ r"(?:[\s,.!]+(?:thanks|thank you|danke|gracias|jarvis))*[\s.!]*", # i18n-allow
+ re.IGNORECASE,
+)
+
+
+def supports_semantic_hangup(user_text: str | None) -> bool:
+ """Whether the user independently expressed conversation-closing intent.
+
+ This never hangs up by itself. A model sentinel or legacy farewell must
+ agree with it; ambiguous speech stays open and explicit commands continue
+ to use the immediate pre-brain matcher.
+ """
+ text = (user_text or "").replace("’", "'")
+ return _SEMANTIC_CLOSING_RE.fullmatch(text) is not None
+
+
def strip_end_signal(text: str | None) -> str:
"""Remove the sentinel and trim surrounding whitespace.
@@ -164,5 +208,7 @@ __all__ = [
"LEGACY_FAREWELL_PHRASES",
"contains_end_signal",
"is_legacy_farewell",
+ "matched_hangup_pattern",
"strip_end_signal",
+ "supports_semantic_hangup",
]
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 7d10ba8e67..b8065d23f4 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import asyncio
import enum
import hashlib
+import json
import logging
import os
import random
@@ -136,6 +137,8 @@ from jarvis.speech.hangup import (
HANGUP_RE,
contains_end_signal,
is_legacy_farewell,
+ matched_hangup_pattern,
+ supports_semantic_hangup,
)
from jarvis.speech.pending_buffer import PendingPromptBuffer
from jarvis.speech.persona import PhrasePicker, iter_all_start_ack
@@ -1413,6 +1416,9 @@ class _SessionInputBuffer:
self._chunks: deque[tuple[int, AudioChunk]] = deque()
self._max_buffer_bytes = max(1, int(max_buffer_bytes))
self._retained_bytes = 0
+ # Latest timestamp among evicted frames. None means at least one frame
+ # had no trustworthy capture timestamp, so skipping a gap is unsafe.
+ self._evicted_through_ns: int | None = 0
self._next_seq = 0
self._updated = asyncio.Event()
self._pump_task: asyncio.Task[None] | None = None
@@ -1447,6 +1453,11 @@ class _SessionInputBuffer:
):
_seq, dropped = self._chunks.popleft()
self._retained_bytes = max(0, self._retained_bytes - len(dropped.pcm))
+ timestamp = int(dropped.timestamp_ns or 0)
+ if timestamp <= 0 or self._evicted_through_ns is None:
+ self._evicted_through_ns = None
+ else:
+ self._evicted_through_ns = max(self._evicted_through_ns, timestamp)
self._chunks.append((self._next_seq, chunk))
self._retained_bytes += chunk_bytes
self._next_seq += 1
@@ -1472,7 +1483,9 @@ class _SessionInputBuffer:
self._source_done = True
self._updated.set()
- async def stream(self) -> AsyncIterator[AudioChunk]:
+ async def stream(
+ self, *, discard_before_ns: Callable[[], int] | None = None
+ ) -> AsyncIterator[AudioChunk]:
self._active_consumers += 1
cursor = 0
try:
@@ -1480,10 +1493,26 @@ class _SessionInputBuffer:
if self._chunks:
earliest = self._chunks[0][0]
if cursor < earliest:
- raise RuntimeError(
- "Voice input exceeded the 30-second replay window; "
- "refusing to drop the command prefix."
+ discard_before = discard_before_ns() if discard_before_ns else 0
+ can_skip_suppressed = (
+ cursor > 0
+ and self._evicted_through_ns is not None
+ and 0 < self._evicted_through_ns < discard_before
+ )
+ if not can_skip_suppressed:
+ raise RuntimeError(
+ "Voice input exceeded the 30-second replay window; "
+ "refusing to drop the command prefix."
+ )
+ # An inline reply pauses VAD while capture keeps running.
+ # Its post-TTS echo guard already rejects these frames;
+ # apply that SAME cutoff before enforcing replay bounds.
+ # New user audio and first-consumer startup are protected.
+ log.debug(
+ "Skipped %d expired voice-input frames after assistant playback.",
+ earliest - cursor,
)
+ cursor = earliest
offset = cursor - earliest
if 0 <= offset < len(self._chunks):
_seq, chunk = self._chunks[offset]
@@ -2855,6 +2884,11 @@ class SpeechPipeline:
# utterance expired 6 s later). The idle-expiry branch grants ONE fresh
# window while within this grace (== one idle window).
self._last_answer_floor_monotonic: float | None = None
+ self._assistant_work_count = 0
+ self._termination_producer = ""
+ self._termination_detail: dict[str, Any] = {}
+ self._idle_deadline_monotonic: float | None = None
+ self._previous_turn_state: str | None = None
self._post_tts_listen_suppression_s = post_tts_listen_suppression_s
self._input_suppressed_until_ns: int = 0
self._continue_listening_after_response = continue_listening_after_response
@@ -3759,6 +3793,7 @@ class SpeechPipeline:
if only_from is not None and previous != only_from:
return
if previous != new_state:
+ self._previous_turn_state = previous.value
log.info("turn-state: %s -> %s", previous.value, new_state.value)
# Jarvis just STOPPED speaking → the floor goes back to the user. Stamp it
# so the idle loop can grant a fresh listening window even when the turn
@@ -3796,6 +3831,39 @@ class SpeechPipeline:
last = self._last_answer_floor_monotonic
return last is not None and (time.monotonic() - last) < self._idle_timeout_s
+ def _assistant_work_in_flight(self) -> bool:
+ """Owned off-loop work keeps idle expiry from closing a busy session."""
+ return bool(getattr(self, "_assistant_work_count", 0))
+
+ def _termination_snapshot(self, reason: str) -> dict[str, Any]:
+ """Bounded diagnostics, without user text, collected before teardown."""
+ from jarvis.harness.computer_use_context import cu_mission_active
+
+ continuing = getattr(self, "_continue_listening_after_response", None)
+ state = getattr(self, "_turn_state", None)
+ detail = dict(getattr(self, "_termination_detail", {}))
+ detail.update({
+ "hangup_reason": reason,
+ "producer": getattr(self, "_termination_producer", "")
+ or "speech.pipeline._state_loop.finalize",
+ "continue_listening_after_response": continuing,
+ "single_turn_mode": None if continuing is None else not continuing,
+ "idle_timeout_s": (
+ getattr(self, "_idle_timeout_s", None)
+ if getattr(self, "_idle_hangup_enabled", True) else 0
+ ),
+ "idle_deadline_monotonic": getattr(self, "_idle_deadline_monotonic", None),
+ "last_activity_monotonic": getattr(self, "_last_user_activity_monotonic", None),
+ "last_answer_floor_monotonic": getattr(self, "_last_answer_floor_monotonic", None),
+ "turn_state": getattr(state, "value", None),
+ "previous_turn_state": getattr(self, "_previous_turn_state", None),
+ "assistant_work_active": self._assistant_work_in_flight(),
+ "tool_active": None,
+ "screen_active": None,
+ "computer_use_active": cu_mission_active(),
+ })
+ return detail
+
@staticmethod
def _supervisor_state_for_turn(state: TurnTakingState) -> str:
if state == TurnTakingState.IDLE:
@@ -5137,6 +5205,7 @@ class SpeechPipeline:
animate = is_readback and self._supervisor is not None
if animate:
await self._transition("SPEAKING")
+ self._assistant_work_count = getattr(self, "_assistant_work_count", 0) + 1
try:
# Drive the TTS pin from the SAME resolved language as the scrub,
# not from event.language again — a None/auto tag here used to send
@@ -5180,6 +5249,8 @@ class SpeechPipeline:
except Exception as exc: # noqa: BLE001
log.warning("Announcement-Speak fehlgeschlagen: %s", exc)
finally:
+ self._assistant_work_count -= 1
+ self._last_announcement_spoken_monotonic = time.monotonic()
if animate:
hungup = hangup is not None and hangup.is_set()
await self._transition("IDLE" if hungup else "LISTENING")
@@ -5781,6 +5852,7 @@ class SpeechPipeline:
hangup = getattr(self, "_hangup_event", None)
if animate:
await self._transition("SPEAKING")
+ self._assistant_work_count = getattr(self, "_assistant_work_count", 0) + 1
try:
self._register_assistant_speech(cleaned)
try:
@@ -5794,6 +5866,8 @@ class SpeechPipeline:
except Exception as exc: # noqa: BLE001
log.warning("Background-completed Voice-Ansage failed: %s", exc)
finally:
+ self._assistant_work_count -= 1
+ self._last_announcement_spoken_monotonic = time.monotonic()
if animate:
hungup = hangup is not None and hangup.is_set()
await self._transition("IDLE" if hungup else "LISTENING")
@@ -7253,6 +7327,8 @@ class SpeechPipeline:
``stop_player=False`` is used when the brain itself emitted the
farewell ("Goodbye, Ruben.") — we let that final utterance play.
"""
+ if not getattr(self, "_termination_producer", ""):
+ self._termination_producer = "speech.pipeline._trigger_voice_hangup"
if stop_player:
try:
self._player.stop()
@@ -8427,6 +8503,13 @@ class SpeechPipeline:
# spoken cue. (The spoken-cue path is for mid-conversation use.)
self._session_has_assistant_spoken = False
session_id = str(uuid4())
+ self._termination_producer = ""
+ self._termination_detail = {}
+ self._idle_deadline_monotonic = None
+ self._last_user_activity_monotonic = None
+ self._last_answer_floor_monotonic = None
+ self._last_announcement_spoken_monotonic = None
+ self._previous_turn_state = None
self._current_voice_session_id = session_id
self._active_voice_mode = self._configured_voice_mode()
self._active_realtime_provider = ""
@@ -8463,6 +8546,7 @@ class SpeechPipeline:
or self._external_hangup_pending.is_set()
):
hangup_reason = HANGUP_HOTKEY
+ self._termination_producer = "speech.pipeline._state_loop.startup_hangup"
log.info("Voice session cancelled during startup.")
else:
log.info(
@@ -8478,9 +8562,15 @@ class SpeechPipeline:
hangup_reason = await self._active_session(
input_buffer=input_buffer
)
+ except asyncio.CancelledError:
+ hangup_reason = HANGUP_SHUTDOWN
+ self._termination_producer = "speech.pipeline._state_loop.cancelled"
+ raise
except Exception as exc: # noqa: BLE001
+ self._termination_producer = "speech.pipeline._state_loop.error"
log.exception("Voice session failed: %s", exc)
finally:
+ termination = self._termination_snapshot(hangup_reason)
reopen_after_engine_change = bool(
getattr(self, "_reopen_after_engine_change", False)
)
@@ -8536,10 +8626,11 @@ class SpeechPipeline:
spend.flush()
await self._publish_event(
VoiceSessionEnded(
- source_layer="speech.pipeline",
+ source_layer=termination["producer"],
session_id=session_id,
hangup_reason=hangup_reason,
duration_s=max(0.0, time.time() - session_started_at),
+ detail=json.dumps(termination, ensure_ascii=True),
)
)
self._state = PipelineState.IDLE
@@ -8625,11 +8716,17 @@ class SpeechPipeline:
@asynccontextmanager
async def _session_input_source(
- self, input_buffer: _SessionInputBuffer | None
+ self,
+ input_buffer: _SessionInputBuffer | None,
+ *,
+ discard_suppressed: bool = False,
) -> AsyncIterator[AsyncIterator[AudioChunk]]:
"""Yield a pre-opened session stream or own a fallback capture."""
if input_buffer is not None:
- yield input_buffer.stream()
+ discard_before = (
+ lambda: int(getattr(self, "_input_suppressed_until_ns", 0))
+ ) if discard_suppressed else None
+ yield input_buffer.stream(discard_before_ns=discard_before)
return
async with MicrophoneCapture(
device=self._input_device,
@@ -8701,7 +8798,9 @@ class SpeechPipeline:
self._active_realtime_provider = ""
self._active_realtime_model = ""
self._voice_engine_transitioning = False
- async with self._session_input_source(input_buffer) as input_chunks:
+ async with self._session_input_source(
+ input_buffer, discard_suppressed=True
+ ) as input_chunks:
vad_iter = self._vad.utterances(
self._session_input_stream(input_chunks)
).__aiter__()
@@ -8717,11 +8816,16 @@ class SpeechPipeline:
next_task: asyncio.Task[bytes] | None = None
try:
while not self._hangup_event.is_set():
- await self._set_turn_state(TurnTakingState.LISTENING)
- await self._publish_event(ListeningStarted(source_layer="speech"))
+ if not self._assistant_work_in_flight():
+ await self._set_turn_state(TurnTakingState.LISTENING)
+ await self._publish_event(ListeningStarted(source_layer="speech"))
if next_task is None:
next_task = asyncio.create_task(vad_iter.__anext__())
hangup_task = asyncio.create_task(self._hangup_event.wait())
+ self._idle_deadline_monotonic = (
+ time.monotonic() + self._idle_timeout_s
+ if getattr(self, "_idle_hangup_enabled", True) else None
+ )
try:
done, _pending = await asyncio.wait(
{next_task, hangup_task},
@@ -8748,8 +8852,17 @@ class SpeechPipeline:
hangup_task.cancel()
if hangup_task in done:
next_task.cancel()
+ if not getattr(self, "_termination_producer", ""):
+ self._termination_producer = (
+ "speech.pipeline._active_session.hangup_event"
+ )
return HANGUP_HOTKEY
if next_task not in done:
+ if self._assistant_work_in_flight():
+ log.debug(
+ "Idle window expired during assistant work; keeping session open."
+ )
+ continue
# Idle timeout — the VAD is still waiting for speech.
# ``_live_spawn_watchdogs`` prunes fired/cancelled
# watchdogs (the watchdog self-removes after its single
@@ -8805,6 +8918,7 @@ class SpeechPipeline:
continue
log.info("⏲ Idle-Timeout — lege auf.")
next_task.cancel()
+ self._termination_producer = "speech.pipeline._active_session.idle_timeout"
return HANGUP_IDLE_TIMEOUT
# The VAD yielded (or raised) — consume it, then recreate the
# task on the next loop iteration.
@@ -8812,11 +8926,23 @@ class SpeechPipeline:
utterance_pcm: bytes = next_task.result()
except StopAsyncIteration:
next_task = None
+ self._termination_producer = (
+ "speech.pipeline._active_session.input_exhausted"
+ )
return HANGUP_SHUTDOWN
except Exception as exc: # noqa: BLE001
log.exception("VAD failed: %s", exc)
next_task = None
- continue
+ # An exception closes the async generator. Reading it
+ # again can only produce StopAsyncIteration, disguising
+ # this capture failure as an application shutdown.
+ self._termination_producer = "speech.pipeline._active_session.vad_error"
+ self._termination_detail = {
+ **getattr(self, "_termination_detail", {}),
+ "input_error_type": type(exc).__name__,
+ "input_replay_overrun": "replay window" in str(exc),
+ }
+ return HANGUP_ERROR
next_task = None
await self._set_turn_state(TurnTakingState.WAITING_FOR_FINAL_TRANSCRIPT)
await self._publish_utterance_captured(utterance_pcm)
@@ -13980,6 +14106,7 @@ class SpeechPipeline:
await self._set_turn_state(TurnTakingState.LISTENING)
return True
self._session_end_reason = HANGUP_TURN_COMPLETE
+ self._termination_producer = "speech.pipeline._finish_after_response.single_turn"
await self._set_turn_state(TurnTakingState.IDLE)
return False
@@ -14460,7 +14587,16 @@ class SpeechPipeline:
# Hangup muss vor dem STT-Halluzinationsfilter laufen: kurze
# "Auflegen"-Turns werden von Whisper gelegentlich als "Vielen Dank"
# transkribiert, was sonst als Halluzination verworfen wuerde.
- if HANGUP_RE.search(text):
+ hangup_match = HANGUP_RE.search(text)
+ self._last_user_activity_monotonic = time.monotonic()
+ self._termination_detail = {
+ "hangup_pattern_matched": hangup_match is not None,
+ "hangup_pattern": matched_hangup_pattern(text) if hangup_match else None,
+ "end_call_signal": None,
+ "legacy_farewell_matched": None,
+ }
+ if hangup_match:
+ self._termination_producer = "speech.pipeline._handle_utterance_turn.explicit_hangup"
log.info("Voice-Hangup via Regex (%r) - lege auf.", text)
self._trigger_voice_hangup()
return False
@@ -14768,8 +14904,21 @@ class SpeechPipeline:
# `response` is the RAW streamed full text (still carries the
# sentinel); the spoken sentences were already scrubbed inside
# _brain_streaming. Legacy exact farewells stay supported.
- is_hangup = contains_end_signal(response) or is_legacy_farewell(normalized)
+ requested_hangup = contains_end_signal(response) or is_legacy_farewell(normalized)
+ self._termination_detail.update({
+ "end_call_signal": contains_end_signal(response),
+ "legacy_farewell_matched": is_legacy_farewell(normalized),
+ })
+ is_hangup = requested_hangup and supports_semantic_hangup(text)
+ if requested_hangup and not is_hangup:
+ log.warning(
+ "Ignored streamed brain hangup signal: the user did not "
+ "express conversation-closing intent."
+ )
if is_hangup:
+ self._termination_producer = (
+ "speech.pipeline._handle_utterance_turn.streamed_end_signal"
+ )
log.info("🔚 Voice-Hangup via Brain-Signal (streamed) — lege auf.")
self._trigger_voice_hangup(stop_player=False)
return False
@@ -14838,7 +14987,17 @@ class SpeechPipeline:
# Hang-up intent must be read from the RAW brain response, BEFORE
# scrub_for_voice strips the [[END_CALL]] sentinel below.
_normalized_raw = response.strip().rstrip("!.").strip().lower()
- is_hangup = contains_end_signal(response) or is_legacy_farewell(_normalized_raw)
+ requested_hangup = contains_end_signal(response) or is_legacy_farewell(_normalized_raw)
+ self._termination_detail.update({
+ "end_call_signal": contains_end_signal(response),
+ "legacy_farewell_matched": is_legacy_farewell(_normalized_raw),
+ })
+ is_hangup = requested_hangup and supports_semantic_hangup(text)
+ if requested_hangup and not is_hangup:
+ log.warning(
+ "Ignored brain hangup signal: the user did not express "
+ "conversation-closing intent."
+ )
# Phase-1-Output-Filter (Persona-Mandat): Tool-JSON, Stacktraces,
# Engineering-Jargon, Self-Reference, Echo-/Filler-Opener vor TTS
@@ -14879,6 +15038,7 @@ class SpeechPipeline:
await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
barged = await self._speak(response, language=lang)
if is_hangup:
+ self._termination_producer = "speech.pipeline._handle_utterance_turn.end_signal"
log.info("🔚 Voice-Hangup via Brain-Signal — lege auf.")
self._trigger_voice_hangup(stop_player=False)
return False
@@ -15592,6 +15752,7 @@ class SpeechPipeline:
"""
if not text:
return
+ self._assistant_work_count = getattr(self, "_assistant_work_count", 0) + 1
try:
await self._set_turn_state(TurnTakingState.PROCESSING)
log.info("→ Brain (from completion buffer)…")
@@ -15614,10 +15775,13 @@ class SpeechPipeline:
generate_call = self._brain.generate(text)
reply = await generate_call
if reply:
+ await self._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
await self._speak(reply, language=lang, kind=SPOKEN_KIND_COMPLETION)
except Exception as exc: # noqa: BLE001 — AD-OE6: never crash the turn
log.exception("Buffered-completion dispatch failed: %s", exc)
finally:
+ self._assistant_work_count -= 1
+ self._last_answer_floor_monotonic = time.monotonic()
try:
await self._set_turn_state(TurnTakingState.LISTENING)
except Exception: # noqa: BLE001, S110
diff --git a/tests/contract/test_voice_termination_diagnostics.py b/tests/contract/test_voice_termination_diagnostics.py
new file mode 100644
index 0000000000..c6ac58ad3c
--- /dev/null
+++ b/tests/contract/test_voice_termination_diagnostics.py
@@ -0,0 +1,84 @@
+"""Termination metadata survives generic event, SQLite and export boundaries."""
+from __future__ import annotations
+
+import json
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import VoiceSessionEnded, VoiceSessionStarted
+from jarvis.sessions.recorder import SessionRecorder
+from jarvis.sessions.store import SessionStore
+from jarvis.ui.web.schema import event_to_ws_envelope
+from jarvis.ui.web.sessions_routes import router
+
+
+ "with_detail", [False, True], ids=["legacy-realtime", "pipeline-diagnostics"],
+)
+async def test_termination_event_persists_and_exports_without_a_session_schema_change(
+ tmp_path, with_detail: bool,
+) -> None:
+ snapshot = {
+ "producer": "speech.pipeline.input_stream_error",
+ "hangup_pattern_matched": False,
+ "end_call_signal": False,
+ "single_turn_mode": False,
+ "idle_timeout_s": 0,
+ "assistant_work_active": False,
+ "input_error_type": "RuntimeError",
+ "input_replay_overrun": True,
+ }
+ kwargs = {"detail": json.dumps(snapshot)} if with_detail else {}
+ event = VoiceSessionEnded(
+ session_id="termination-contract", hangup_reason="error",
+ source_layer=(
+ "speech.pipeline.input_stream_error" if with_detail else "realtime.session.end"
+ ),
+ timestamp_ns=2000_000_000, **kwargs,
+ )
+ envelope = json.loads(json.dumps(event_to_ws_envelope(event)))
+ assert envelope["payload"]["hangup_reason"] == "error"
+ assert envelope["payload"]["detail"] == (json.dumps(snapshot) if with_detail else "")
+ assert envelope["source_layer"] == event.source_layer
+
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await bus.publish(VoiceSessionStarted(
+ session_id=event.session_id, timestamp_ns=1000_000_000,
+ ))
+ await bus.publish(event)
+ row = store.get_session(event.session_id)
+ assert row is not None and row.hangup_reason == "error"
+ recorded = store.get_events(event.session_id)[-1]
+ assert recorded.payload["source_layer"] == event.source_layer
+ assert recorded.payload["detail"] == event.detail
+
+ app = FastAPI()
+ app.state.session_store = store
+ app.include_router(router)
+ with TestClient(app) as client:
+ for export_format in ("plain", "markdown", "json"):
+ response = client.get(
+ f"/api/sessions/{event.session_id}/export?format={export_format}"
+ )
+ assert response.status_code == 200
+ assert event.source_layer in response.text
+ assert "error" in response.text
+ if with_detail and export_format != "json":
+ assert "hangup_pattern_matched: false" in response.text
+ assert "idle_timeout_s: 0" in response.text
+ assert "input_error_type: RuntimeError" in response.text
+ assert "input_replay_overrun: true" in response.text
+ assert "assistant_work_active: false" in response.text
+ assert "computer_use_active: not recorded" in response.text
+ if not with_detail and export_format != "json":
+ assert "hangup_pattern_matched: false" not in response.text
+ finally:
+ store.close()
diff --git a/tests/unit/sessions/test_termination_diagnostics.py b/tests/unit/sessions/test_termination_diagnostics.py
new file mode 100644
index 0000000000..8177908b5c
--- /dev/null
+++ b/tests/unit/sessions/test_termination_diagnostics.py
@@ -0,0 +1,105 @@
+"""Missing or untrusted termination evidence must never become invented facts."""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from jarvis.sessions.diagnostics import session_termination_diagnostics
+from jarvis.sessions.formatter import format_session_markdown, format_session_plain
+from jarvis.sessions.models import VoiceEventRow, VoiceSessionRow
+
+
+def _session() -> VoiceSessionRow:
+ return VoiceSessionRow(id="session", started_ms=1000, ended_ms=5000, hangup_reason="shutdown")
+
+
+def _event(kind: str, ts_ms: int, **payload: object) -> VoiceEventRow:
+ return VoiceEventRow(session_id="session", ts_ms=ts_ms, kind=kind, payload=payload)
+
+
+def test_historical_export_keeps_known_reason_and_missing_evidence() -> None:
+ session = _session()
+ result = session_termination_diagnostics(session, [])
+ assert result["hangup_reason"] == "shutdown"
+ assert result["producer"] is None
+ assert result["idle_timeout_s"] is None
+ assert result["end_call_signal"] is None
+ for renderer in (format_session_plain, format_session_markdown):
+ output = renderer(session, [])
+ assert "shutdown" in output
+ assert "not recorded" in output
+ assert "end_call_signal: false" not in output
+
+
+def test_snapshot_keeps_false_and_zero_but_never_exports_unknown_raw_content() -> None:
+ events = [_event("VoiceSessionEnded", 5000, detail=json.dumps({
+ "producer": "speech.pipeline.idle_timeout",
+ "hangup_pattern_matched": False, "idle_timeout_s": 0,
+ "single_turn_mode": False, "end_call_signal": True,
+ "raw_brain_response": "PRIVATE RESPONSE", "api_key": "PRIVATE CREDENTIAL",
+ }))]
+ output = format_session_plain(_session(), [], iter(events))
+ assert "hangup_pattern_matched: false" in output
+ assert "idle_timeout_s: 0" in output
+ assert "single_turn_mode: false" in output
+ assert "end_call_signal: true" in output
+ assert "PRIVATE" not in output
+ assert "Session termination diagnostics (not spoken):" in output
+
+
[email protected]("detail", ["", "bad json", "[]", '{"x":1}', "[" * 2000, "x" * 20_000])
+def test_malformed_or_old_detail_does_not_break_export(detail: str) -> None:
+ event = _event("VoiceSessionEnded", 5000, source_layer="pipeline.stop", detail=detail)
+ output = format_session_plain(_session(), [], [event])
+ assert "shutdown" in output
+ assert "pipeline.stop" in output
+ assert "hangup_pattern_matched: false" not in output
+
+
+def test_event_times_exclude_other_sessions_and_after_hangup_readbacks() -> None:
+ events = [
+ _event("UtteranceCaptured", 1200),
+ _event("ToolCallStarted", 1400),
+ _event("ToolCallCompleted", 4000),
+ _event("LatencySpan", 4010, phase="tts_request_sent", duration_ms=0),
+ _event("AudioOutFirst", 4100),
+ _event("LatencySpan", 4400, phase="tts_stream_done", duration_ms=390),
+ _event("SpeechSpoken", 4500),
+ _event("SystemStateChanged", 4600, previous="SPEAKING", new_state="LISTENING"),
+ _event("VoiceSessionEnded", 5000),
+ _event("SpeechSpoken", 5500),
+ _event("LatencySpan", 5600, phase="tts_stream_done", duration_ms=1500),
+ VoiceEventRow(session_id="other", ts_ms=4900, kind="UtteranceCaptured"),
+ ]
+ result = session_termination_diagnostics(_session(), reversed(events))
+ assert result["last_user_utterance_end_ms"] == 1200
+ assert result["last_tool_start_ms"] == 1400
+ assert result["last_tool_end_ms"] == 4000
+ assert result["last_assistant_audio_start_ms"] == 4100
+ assert result["last_assistant_audio_confirmed_ms"] == 4500
+ assert result["last_tts_request_ms"] == 4010
+ assert result["last_tts_stream_done_ms"] == 4400
+ assert result["last_state_transition"] == "SPEAKING -> LISTENING"
+ assert result["last_state_transition_ms"] == 4600
+ assert result["session_end_ms"] == 5000
+ assert result["tool_active"] is None
+
+
+def test_oversized_json_number_is_unknown_instead_of_breaking_export() -> None:
+ event = _event("VoiceSessionEnded", 5000, detail=json.dumps({"idle_timeout_s": 10**400}))
+ result = session_termination_diagnostics(_session(), [event])
+ assert result["idle_timeout_s"] is None
+ assert "idle_timeout_s: not recorded" in format_session_plain(_session(), [], [event])
+
+
+def test_late_termination_event_cannot_replace_the_recorded_end_snapshot() -> None:
+ events = [
+ _event("VoiceSessionEnded", 5000, detail=json.dumps({"producer": "pipeline.stop"})),
+ _event("VoiceSessionEnded", 5001, detail=json.dumps({"producer": "late.unrelated"})),
+ ]
+ result = session_termination_diagnostics(_session(), events)
+ assert result["producer"] == "pipeline.stop"
+ output = format_session_plain(_session(), [], events)
+ assert "pipeline.stop" in output
+ assert "late.unrelated" not in output
diff --git a/tests/unit/speech/test_hangup.py b/tests/unit/speech/test_hangup.py
index 872f523829..885386dedf 100644
--- a/tests/unit/speech/test_hangup.py
+++ b/tests/unit/speech/test_hangup.py
@@ -10,6 +10,7 @@ from jarvis.speech.hangup import (
contains_end_signal,
is_legacy_farewell,
strip_end_signal,
+ supports_semantic_hangup,
)
@@ -149,3 +150,24 @@ def test_is_legacy_farewell_rejects_other_text() -> None:
assert is_legacy_farewell("auf wiedersehen ruben war mir ein vergnügen") is False # i18n-allow
assert is_legacy_farewell("hallo ruben") is False
assert is_legacy_farewell("") is False
+
+
+ "Ich glaube wir sind durch", "Danke, das war's für heute.", # i18n-allow
+ "I think we're done here, thanks.", "That is all for now.",
+ "I need to go", "No more questions", "Eso es todo por hoy, gracias.",
+ "Creo que hemos terminado", "No necesito nada más",
+])
+def test_semantic_closure_requires_positive_user_evidence(text: str) -> None:
+ assert supports_semantic_hangup(text)
+
+
+ "Explain the selected text on my screen", "Translate that please",
+ "The task is complete", "The build is done", "Thanks", "Vielen Dank", # i18n-allow
+ "We are not done", "We're done with step one, now continue with step two",
+ 'Translate "we are done" into German', "We're done?", "No hemos terminado",
+ "Ich glaube wir sind nicht fertig", "Das war's mit dem Fehler, mach weiter", # i18n-allow
+])
+def test_task_completion_and_quoted_closings_are_not_session_closure(text: str) -> None:
+ assert not supports_semantic_hangup(text)
diff --git a/tests/unit/speech/test_long_response_capture.py b/tests/unit/speech/test_long_response_capture.py
new file mode 100644
index 0000000000..15f878623e
--- /dev/null
+++ b/tests/unit/speech/test_long_response_capture.py
@@ -0,0 +1,189 @@
+"""RUB-35: a long screen response must not exhaust the input replay reader."""
+
+import asyncio
+import time
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.speech.pipeline as pipeline_mod
+from jarvis.core.protocols import AudioChunk
+from jarvis.sessions.constants import HANGUP_ERROR, HANGUP_HOTKEY, HANGUP_IDLE_TIMEOUT
+from jarvis.speech.pipeline import TurnTakingState, _SessionInputBuffer
+from tests.unit.speech.test_idle_spawn_inflight import _make_active_session_pipeline
+from tests.unit.speech.test_turn_taking import FakeSTT, _make_pipeline
+
+
+class EndpointPerChunk:
+ async def utterances(self, chunks):
+ async for chunk in chunks:
+ yield chunk.pcm
+
+
+async def test_long_inline_screen_answer_keeps_next_user_command() -> None:
+ pipe = _make_active_session_pipeline(idle_timeout_s=30)
+ pipe._idle_hangup_enabled = False
+ pipe._post_tts_listen_suppression_s = 0.3
+ pipe._vad = EndpointPerChunk()
+ buffer = _SessionInputBuffer()
+ start_ns = time.time_ns() - 70_000_000_000
+ buffer.put(AudioChunk(pcm=b"translate-screen", sample_rate=16000, timestamp_ns=start_ns))
+ received = []
+
+ async def handle(pcm):
+ received.append(pcm)
+ if len(received) == 1:
+ await pipe._set_turn_state(TurnTakingState.PROCESSING)
+ # 60 seconds of actual PCM volume while the inline tool/generation
+ # owns the loop. This exceeds the unchanged 30-second replay cap.
+ for second in range(1, 61):
+ buffer.put(AudioChunk(
+ pcm=b"\x00\x00" * 16000,
+ sample_rate=16000,
+ timestamp_ns=start_ns + second * 1_000_000_000,
+ ))
+ await pipe._set_turn_state(TurnTakingState.JARVIS_SPEAKING)
+ # Exercise the existing half-duplex policy after final audio.
+ pipe._suppress_session_input_after_tts("response")
+ await pipe._set_turn_state(TurnTakingState.LISTENING)
+ buffer.put(AudioChunk(
+ pcm=b"next-user-command", sample_rate=16000,
+ timestamp_ns=pipe._input_suppressed_until_ns + 1,
+ ))
+ return True
+ pipe._session_end_reason = HANGUP_HOTKEY # Test-controlled stop after follow-up.
+ return False
+
+ pipe._handle_utterance = handle
+ try:
+ reason = await asyncio.wait_for(pipe._active_session(input_buffer=buffer), timeout=2)
+ finally:
+ await buffer.close()
+
+ assert received == [b"translate-screen", b"next-user-command"]
+ assert reason == HANGUP_HOTKEY
+ assert not getattr(pipe, "_termination_detail", {}).get("input_replay_overrun")
+
+
[email protected]("cutoff", [0, 2])
+async def test_unsuppressed_command_prefix_overflow_remains_an_error(cutoff: int) -> None:
+ buffer = _SessionInputBuffer(max_buffer_bytes=4)
+ buffer.put(AudioChunk(pcm=b"aaaa", sample_rate=16000, timestamp_ns=1))
+ stream = buffer.stream(discard_before_ns=lambda: cutoff)
+ assert (await anext(stream)).pcm == b"aaaa"
+ buffer.put(AudioChunk(pcm=b"bbbb", sample_rate=16000, timestamp_ns=2))
+ buffer.put(AudioChunk(pcm=b"cccc", sample_rate=16000, timestamp_ns=3))
+ with pytest.raises(RuntimeError, match="refusing to drop the command prefix"):
+ await anext(stream)
+ await buffer.close()
+
+
+async def test_startup_prefix_guard_cannot_be_bypassed_by_old_echo_cutoff() -> None:
+ buffer = _SessionInputBuffer(max_buffer_bytes=4)
+ buffer.put(AudioChunk(pcm=b"aaaa", sample_rate=16000, timestamp_ns=1))
+ buffer.put(AudioChunk(pcm=b"bbbb", sample_rate=16000, timestamp_ns=2))
+ with pytest.raises(RuntimeError, match="refusing to drop the command prefix"):
+ await anext(buffer.stream(discard_before_ns=lambda: 100))
+ await buffer.close()
+
+
+async def test_capture_failure_is_not_mislabeled_as_shutdown() -> None:
+ pipe = _make_active_session_pipeline(idle_timeout_s=30)
+ pipe._vad = EndpointPerChunk()
+ buffer = _SessionInputBuffer(max_buffer_bytes=4)
+ buffer.put(AudioChunk(pcm=b"aaaa", sample_rate=16000, timestamp_ns=1))
+ buffer.put(AudioChunk(pcm=b"bbbb", sample_rate=16000, timestamp_ns=2))
+ try:
+ reason = await pipe._active_session(input_buffer=buffer)
+ finally:
+ await buffer.close()
+ assert reason == HANGUP_ERROR
+ assert pipe._termination_producer == "speech.pipeline._active_session.vad_error"
+ assert pipe._termination_detail["input_error_type"] == "RuntimeError"
+ assert pipe._termination_detail["input_replay_overrun"] is True
+
+
[email protected]("streaming", [False, True])
+async def test_completed_information_request_cannot_end_conversation(streaming: bool) -> None:
+ response = "Die Markierung erklärt die Gedanken eines Agenten. [[END_CALL]]" # i18n-allow
+ pipe = _make_pipeline(
+ FakeSTT(text="Kannst du mir bitte den markierten Text erklären?"), # i18n-allow
+ brain_response=response,
+ continue_listening_after_response=True,
+ )
+ pipe._streaming_enabled = lambda: streaming
+ if streaming:
+ async def brain_streaming(_text, _lang):
+ return response, False
+
+ async def stall_guard(coro, **_kwargs):
+ return await coro
+
+ pipe._brain_streaming = brain_streaming
+ pipe._run_brain_with_stall_guard = stall_guard
+ keep_listening = await pipe._handle_utterance(b"\x01\x00" * 1024)
+ assert keep_listening
+ assert not pipe._hangup_event.is_set()
+ assert pipe._session_end_reason is None
+ assert pipe._termination_detail["hangup_pattern_matched"] is False
+ assert pipe._termination_detail["end_call_signal"] is True
+
+
+async def test_buffered_tool_and_tts_get_fresh_idle_window_after_final_audio(monkeypatch) -> None:
+ pipe = _make_active_session_pipeline(idle_timeout_s=30)
+ pipe._idle_hangup_enabled = True
+ pipe._post_readback_grace_s = 30
+ clock = [0.0]
+ monkeypatch.setattr(pipeline_mod, "time", SimpleNamespace(monotonic=lambda: clock[0]))
+ generation_gate = asyncio.Event()
+ speech_started = asyncio.Event()
+ speech_gate = asyncio.Event()
+
+ async def generate(_text, **_kwargs):
+ await generation_gate.wait()
+ return "Here is the explanation of the selected screen text."
+
+ async def speak(_text, **_kwargs):
+ speech_started.set()
+ await speech_gate.wait()
+
+ pipe._brain = SimpleNamespace(generate=generate)
+ pipe._streaming_enabled = lambda: False
+ pipe._speak = speak
+ response_task = asyncio.create_task(
+ pipe._handle_flushed_pending_text("Explain my screen", "en")
+ )
+ await asyncio.sleep(0)
+ waits = []
+
+ async def wait(_tasks, *, timeout, return_when): # noqa: ASYNC109 - asyncio.wait test double
+ waits.append(timeout)
+ clock[0] += timeout
+ if len(waits) == 2:
+ generation_gate.set() # Tool/generation takes 60 seconds.
+ await speech_started.wait()
+ elif len(waits) == 3:
+ speech_gate.set() # TTS finishes at 90 seconds.
+ await response_task
+ return set(), _tasks
+
+ monkeypatch.setattr(pipeline_mod.asyncio, "wait", wait)
+ buffer = _SessionInputBuffer()
+ try:
+ reason = await pipe._active_session(input_buffer=buffer)
+ finally:
+ await buffer.close()
+ if not response_task.done():
+ response_task.cancel()
+ await asyncio.gather(response_task, return_exceptions=True)
+
+ assert waits == [30, 30, 30, 30]
+ assert clock[0] == 120 # A full 30 seconds AFTER final audio.
+ assert reason == HANGUP_IDLE_TIMEOUT
+ assert pipe._assistant_work_count == 0