Skip to content

The agent that grows with you

fix(voice): spoken barge-in works on every TTS playback path (CLI + gateway/desktop backends)

Tekniumc15f9b71a508
diff --git a/cli.py b/cli.py
index db22d1b4a4e..8e4ae1b23e5 100644
--- a/cli.py
+++ b/cli.py
@@ -12045,6 +12045,19 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
args=(text,),
daemon=True,
).start()
+ # Spoken barge-in must work on the whole-file fallback path too —
+ # previously only the streaming pipeline armed the monitor, so when
+ # streaming TTS couldn't start (missing sounddevice, failed probe)
+ # talking over the reply did nothing. The monitor's _cut_playback
+ # uses stop_playback(), which kills the file player, so the same
+ # machinery covers this path; the stop event it receives is only
+ # used to signal the (nonexistent) streaming pipeline.
+ if self._voice_continuous:
+ threading.Thread(
+ target=self._voice_barge_in_monitor,
+ args=(threading.Event(),),
+ daemon=True,
+ ).start()
def _voice_speak_response(self, text: str):
"""Speak the agent's response aloud using TTS (runs in background thread)."""
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index fec977b0636..3d62e927772 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -2376,6 +2376,7 @@ DEFAULT_CONFIG = {
"silence_threshold": 200, # RMS below this = silence (0-32767)
"silence_duration": 3.0, # Seconds of silence before auto-stop
"barge_in": True, # Stop TTS playback when the user starts talking
+ "barge_in_grace_seconds": 2.0, # Delay before the barge mic opens so VAD calibrates against live TTS playback (0 disables)
# Saying EXACTLY one of these phrases (and nothing else) ends the
# voice chat instead of being sent to the agent. Case-insensitive,
# surrounding punctuation ignored. Set [] to disable.
diff --git a/hermes_cli/voice.py b/hermes_cli/voice.py
index d72ab379bb2..24ee29736cc 100644
--- a/hermes_cli/voice.py
+++ b/hermes_cli/voice.py
@@ -881,7 +881,7 @@ def _continuous_on_silence() -> None:
# ── TTS API ──────────────────────────────────────────────────────────
-def _speak_text_streaming(text: str) -> bool:
+def _speak_text_streaming(text: str, stop_event: Optional[threading.Event] = None) -> bool:
"""Speak ``text`` via the generic streaming dispatcher; True on success.
Bridges the one-shot ``speak_text`` contract onto the shared
@@ -891,6 +891,11 @@ def _speak_text_streaming(text: str) -> bool:
has, so callers (and the mic re-arm logic in ``speak_text``) see no
behavioral difference beyond earlier first audio.
+ ``stop_event`` (optional) is wired straight into the pipeline so
+ external barge-in / stop paths can cut streaming playback — without
+ it the pipeline's stop event was private and speech over this path
+ was uninterruptible (the desktop/TUI fallback-speak hole).
+
Returns False when playback produced nothing (caller falls back to the
whole-file sync path).
"""
@@ -902,13 +907,14 @@ def _speak_text_streaming(text: str) -> bool:
text_queue: "_queue.Queue" = _queue.Queue()
text_queue.put(text)
text_queue.put(None) # end-of-text sentinel
- stop_event = _threading.Event()
+ if stop_event is None:
+ stop_event = _threading.Event()
done_event = _threading.Event()
stream_tts_to_speaker(text_queue, stop_event, done_event)
return done_event.is_set()
-def speak_text(text: str) -> None:
+def speak_text(text: str, stop_event: Optional[threading.Event] = None) -> None:
"""Synthesize ``text`` with the configured TTS provider and play it.
Mirrors cli.py:_voice_speak_response exactly — same markdown strip
@@ -963,7 +969,7 @@ def speak_text(text: str) -> None:
from tools.tts_tool import _load_tts_config
if resolve_streaming_provider(_load_tts_config()) is not None:
- if _speak_text_streaming(text):
+ if _speak_text_streaming(text, stop_event):
return
except Exception as e:
_debug(f"speak_text: streaming dispatch unavailable ({e}); using sync path")
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 4c28623bf42..133808fee8c 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -14706,6 +14706,103 @@ def test_tts_stream_vad_barge_in_cuts_pipeline_and_submits_capture(monkeypatch,
server._tts_stream_stop()
+def test_speak_text_with_barge_arms_monitor_and_cuts_playback(monkeypatch, tmp_path):
+ """The fallback whole-reply speak path (streaming pipeline couldn't
+ start) and the voice.tts RPC must be barge-able too: speaking over the
+ reply cuts playback and the captured interruption is emitted as
+ voice.transcript — previously these paths called speak_text bare and
+ were uninterruptible by voice."""
+ import tools.tts_streaming as ts
+
+ ts._interrupted_at = None
+ monkeypatch.setenv("HERMES_VOICE", "1")
+ monkeypatch.setenv("HERMES_VOICE_TTS", "1")
+ monkeypatch.setattr(
+ server,
+ "_load_cfg",
+ lambda: {"voice": {"barge_in": True, "barge_in_grace_seconds": 0}},
+ )
+ events: list = []
+ monkeypatch.setattr(
+ server, "_voice_emit", lambda event, payload=None: events.append((event, payload))
+ )
+
+ wav = tmp_path / "barge.wav"
+ wav.write_bytes(b"RIFF")
+
+ speak_calls = {}
+ speak_started = threading.Event()
+ release_speak = threading.Event()
+
+ def fake_speak_text(text, stop_event=None):
+ speak_calls["text"] = text
+ speak_calls["stop_event"] = stop_event
+ speak_started.set()
+ release_speak.wait(5)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "hermes_cli.voice",
+ types.SimpleNamespace(speak_text=fake_speak_text),
+ )
+
+ def fake_listen(should_stop, capture=False, on_trigger=None, **_kw):
+ assert capture is True
+ speak_started.wait(5)
+ on_trigger() # user talks over the reply → cut now
+ return str(wav)
+
+ _fake_tts_modules(
+ monkeypatch,
+ listen=fake_listen,
+ transcribe=lambda path, model=None: {"success": True, "transcript": "hang on"},
+ )
+
+ server._speak_text_with_barge("a long spoken reply")
+
+ deadline = time.monotonic() + 5.0
+ while time.monotonic() < deadline and ("voice.transcript", {"text": "hang on"}) not in events:
+ time.sleep(0.01)
+ release_speak.set()
+
+ assert speak_calls["text"] == "a long spoken reply"
+ # The pipeline stop event is shared with speak_text so a streaming
+ # dispatch inside it is cut too.
+ assert speak_calls["stop_event"] is not None
+ assert speak_calls["stop_event"].is_set()
+ assert ("voice.interrupted", None) in events
+ assert ("voice.transcript", {"text": "hang on"}) in events
+ assert ts.take_speech_interrupted() is True
+
+
+def test_speak_text_with_barge_no_monitor_when_voice_mode_off(monkeypatch):
+ """Auto-speak with voice mode off (no mic loop) must not open the mic."""
+ monkeypatch.setenv("HERMES_VOICE", "0")
+ monkeypatch.setenv("HERMES_VOICE_TTS", "1")
+ monkeypatch.setattr(server, "_load_cfg", lambda: {"voice": {"barge_in": True}})
+
+ listened = threading.Event()
+
+ def fake_listen(should_stop, capture=False, on_trigger=None, **_kw):
+ listened.set()
+ return None
+
+ done_speaking = threading.Event()
+ monkeypatch.setitem(
+ sys.modules,
+ "hermes_cli.voice",
+ types.SimpleNamespace(
+ speak_text=lambda text, stop_event=None: done_speaking.set()
+ ),
+ )
+ _fake_tts_modules(monkeypatch, listen=fake_listen)
+
+ server._speak_text_with_barge("quiet reply")
+ assert done_speaking.wait(5)
+ time.sleep(0.1)
+ assert not listened.is_set()
+
+
def test_clarify_callback_uses_configured_timeout(monkeypatch):
"""The TUI/desktop clarify bridge honors the canonical clarify timeout
(via _clarify_timeout_seconds) instead of the hardcoded _block default."""
diff --git a/tests/tools/test_voice_cli_integration.py b/tests/tools/test_voice_cli_integration.py
index 0fa4304b487..b9fb323502c 100644
--- a/tests/tools/test_voice_cli_integration.py
+++ b/tests/tools/test_voice_cli_integration.py
@@ -1502,3 +1502,47 @@ class TestTypedVoiceStop:
cli = self._cli(_voice_mode=True)
assert cli._typed_voice_stop(("text", ["img.png"])) is False
assert cli._disable_calls == []
+
+
+# ============================================================================
+# Fallback (whole-file) TTS path arms the spoken barge-in monitor
+# ============================================================================
+
+class TestFallbackSpeakArmsBargeMonitor:
+ """_voice_speak_response_async must arm _voice_barge_in_monitor in
+ continuous voice mode. Previously ONLY the streaming pipeline armed the
+ monitor (chat() gate), so when streaming TTS couldn't start the whole-file
+ fallback speech was uninterruptible by voice — Teknium's "speaking over
+ the agent does nothing" report on the non-streaming path."""
+
+ def _cli(self, **overrides):
+ cli = _make_voice_cli(**overrides)
+ cli._monitor_calls = []
+ cli._voice_barge_in_monitor = (
+ lambda stop_event: cli._monitor_calls.append(stop_event)
+ )
+ cli._voice_speak_response = lambda text: None
+ return cli
+
+ def _drain_threads(self):
+ import time
+ time.sleep(0.15)
+
+ def test_monitor_armed_in_continuous_voice_mode(self):
+ cli = self._cli(_voice_mode=True, _voice_tts=True, _voice_continuous=True)
+ cli._voice_speak_response_async("a reply")
+ self._drain_threads()
+ assert len(cli._monitor_calls) == 1
+ assert isinstance(cli._monitor_calls[0], threading.Event)
+
+ def test_no_monitor_outside_continuous_mode(self):
+ cli = self._cli(_voice_mode=True, _voice_tts=True, _voice_continuous=False)
+ cli._voice_speak_response_async("a reply")
+ self._drain_threads()
+ assert cli._monitor_calls == []
+
+ def test_no_monitor_when_tts_disabled(self):
+ cli = self._cli(_voice_mode=True, _voice_tts=False, _voice_continuous=True)
+ cli._voice_speak_response_async("a reply")
+ self._drain_threads()
+ assert cli._monitor_calls == []
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 5f8ba266c7d..2e0f065bc5d 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -12540,11 +12540,11 @@ def _run_prompt_submit(
and _voice_tts_enabled()
):
try:
- from hermes_cli.voice import speak_text
-
spoken = raw
+ # Barge-aware: spoken interruptions must cut this
+ # fallback playback too, not just the streaming path.
threading.Thread(
- target=speak_text, args=(spoken,), daemon=True
+ target=_speak_text_with_barge, args=(spoken,), daemon=True
).start()
except ImportError:
logger.warning("voice TTS skipped: hermes_cli.voice unavailable")
@@ -17918,6 +17918,39 @@ def _tts_stream_barge_in_monitor(stop: threading.Event, done: threading.Event) -
logger.debug("TTS barge-in monitor failed: %s", e)
+def _speak_text_with_barge(text: str) -> None:
+ """Speak *text* via hermes_cli.voice.speak_text with spoken barge-in.
+
+ The streaming-TTS turn pipeline arms ``_tts_stream_barge_in_monitor``;
+ the fallback whole-reply path (streaming couldn't start) and the
+ ``voice.tts`` RPC previously called ``speak_text`` bare — speech over
+ those paths was UNINTERRUPTIBLE by voice. Run the same monitor beside
+ the speak thread: it cuts playback (``stop_playback`` kills the file
+ player; the stop event drains a streaming dispatch inside speak_text),
+ captures the interruption, and emits ``voice.transcript`` /
+ the stop-phrase signal exactly like the streaming path.
+ """
+ from hermes_cli.voice import speak_text
+
+ stop = threading.Event()
+ done = threading.Event()
+
+ def _speak():
+ try:
+ speak_text(text, stop)
+ except TypeError:
+ # Older wrapper without the stop_event parameter.
+ speak_text(text)
+ finally:
+ done.set()
+
+ threading.Thread(target=_speak, daemon=True).start()
+ if _voice_mode_enabled() and _voice_cfg_dict().get("barge_in", True):
+ threading.Thread(
+ target=_tts_stream_barge_in_monitor, args=(stop, done), daemon=True
+ ).start()
+
+
def _voice_cfg_dict() -> dict:
"""Shape-safe accessor for the ``voice:`` block in config.yaml.
@@ -18550,9 +18583,13 @@ def _(rid, params: dict) -> dict:
if not text:
return _err(rid, 4020, "text required")
try:
- from hermes_cli.voice import speak_text
+ # Import check up front so a missing voice module still returns the
+ # documented 5026 instead of failing silently in the thread.
+ import hermes_cli.voice # noqa: F401
- threading.Thread(target=speak_text, args=(text,), daemon=True).start()
+ threading.Thread(
+ target=_speak_text_with_barge, args=(text,), daemon=True
+ ).start()
return _ok(rid, {"status": "speaking"})
except ImportError:
return _err(rid, 5026, "voice module not available")