The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(voice): honor configured silence_threshold and stop gating streaming TTS on sounddevice
Brooklyn Nicholsonc9ea2140ade4
diff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.pyindex 1a7b160e4d4..9509450e8c7 100644--- a/hermes_cli/cli_chat_turn_mixin.py+++ b/hermes_cli/cli_chat_turn_mixin.py@@ -257,14 +257,18 @@ class CLIChatTurnMixin:threading.Thread(target=self._voice_full_duplex_listener, daemon=True).start()# Streaming TTS: any working provider speaks sentence-by-sentence as tokens arrive.+ # Availability is check_tts_requirements() ALONE: the speaker side picks its own+ # output route per platform (PortAudio stream where usable, tempfile -> afplay on+ # macOS — sounddevice is deliberately never imported for output on Darwin, see+ # tts_tool_speaker._device_usable), so probing it here disabled streaming TTS on+ # macOS via the bare except below (#84046).if self._voice_tts:try:- from tools.tts_tool import _import_sounddevice, check_tts_requirements+ from tools.tts_tool import check_tts_requirementsfrom tools.tts_tool_speaker import stream_tts_to_speaker- _import_sounddevice()turn.use_streaming_tts = check_tts_requirements()except Exception:- pass+ logging.debug("streaming TTS arm check failed", exc_info=True)if turn.use_streaming_tts:turn.text_queue = queue.Queue()diff --git a/tests/hermes_cli/test_chat_turn_streaming_tts_arming.py b/tests/hermes_cli/test_chat_turn_streaming_tts_arming.pynew file mode 100644index 00000000000..e6810804d49--- /dev/null+++ b/tests/hermes_cli/test_chat_turn_streaming_tts_arming.py@@ -0,0 +1,142 @@+"""Streaming-TTS arm gate regression (#84046): ``_chat_setup_turn_audio`` used to gate+streaming TTS on a ``sounddevice`` import, which raises on macOS (PortAudio/CoreAudio+init triggers a kTCCServiceMediaLibrary prompt) even though the speaker path+deliberately avoids sounddevice on Darwin (tempfile -> afplay; see+tts_tool_speaker._device_usable). The swallow-``except`` then disabled streaming TTS+for every working provider on macOS.++The arm gate must not probe sounddevice at all: enablement is+``check_tts_requirements()`` alone, and where sounddevice is unusable a working+provider still arms streaming TTS.++These contracts are host-independent — the arm decision is data (the requirements+probe), not host state — so the tests run unmarked on every lane; the macOS arm of+the *speaker output policy* itself (sounddevice never imported on Darwin) is+covered for real by ``tests/tools/test_tts_macos_output.py`` via+``@pytest.mark.platforms``.++Behavior contracts, mocked per test; no real audio, no config on disk.+"""++import os+import sys+import threading+import types++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))++from cli import HermesCLI, _ChatTurn # noqa: E402+++class _StreamingTTSArming:+ """Drive ``HermesCLI._chat_setup_turn_audio`` without a real CLI instance."""++ def make_cli(self):+ cli = HermesCLI.__new__(HermesCLI)+ cli._voice_mode = False+ cli._voice_continuous = False+ cli._voice_tts = True+ cli._voice_tts_done = threading.Event()+ cli._voice_last_tts_text = ""+ cli.show_timestamps = False+ cli.streaming_enabled = False+ cli.timestamp_format = "%H:%M"+ return cli++ def make_turn(self):+ turn = _ChatTurn()+ turn.mute_notification_reply = False+ return turn+++def _arm_turn(monkeypatch, requirements, sounddevice_factory=None):+ """Arm a voice-tts turn and return ``(turn, sounddevice_probe)``.++ ``sounddevice_factory`` replaces ``tts_tool._import_sounddevice``; the default+ spy raises the same OSError the import raises on macOS (CoreAudio TCC prompt)+ and records that the arm gate called it at all — the gate must never call it,+ so the raise doubles as proof that arming does not depend on the import.+ """+ import tools.tts_tool as tts_tool++ probe = []++ def _spy():+ probe.append(1)+ raise OSError("PaAlsa [ CoreAudio TCC media-library prompt ]")++ monkeypatch.setattr(tts_tool, "_import_sounddevice", sounddevice_factory or _spy)+ monkeypatch.setattr(tts_tool, "check_tts_requirements", lambda: requirements)++ speaker_calls = []+ started = threading.Event()++ def _fake_stream(text_queue, stop_event, done_event, *a, **k):+ speaker_calls.append(True)+ done_event.set()+ started.set()++ import tools.tts_tool_speaker as speaker_mod+ monkeypatch.setattr(speaker_mod, "stream_tts_to_speaker", _fake_stream)++ cli = _StreamingTTSArming().make_cli()+ turn = _StreamingTTSArming().make_turn()+ cli._chat_setup_turn_audio(turn, "hello", False)++ if turn.use_streaming_tts:+ assert turn.text_queue is not None+ assert turn.stop_event is not None+ turn.text_queue.put(None) # drain sentinel so the fake speaker exits+ started.wait(timeout=2)+ return turn, probe, bool(speaker_calls)+++def test_streaming_tts_arms_without_importing_sounddevice(monkeypatch):+ """#84046: the arm gate must not import sounddevice at all — on macOS the+ import raises (CoreAudio TCC prompt) even though the speaker path never uses+ it there, so the import disabled streaming TTS for working providers. A+ raising import (or none at all) must not stand between requirements and+ arming."""+ turn, probe, spoke = _arm_turn(monkeypatch, requirements=True)+ assert turn.use_streaming_tts is True, "streaming TTS must arm without a sounddevice probe"+ assert probe == [], "the arm gate must not probe sounddevice"+ assert spoke is True, "the TTS speaker thread must have been started"+++def test_streaming_tts_arms_with_a_plain_working_import_too(monkeypatch):+ """The gate is import-agnostic in the other direction: where sounddevice+ imports fine it still wires solely from check_tts_requirements()."""+ turn, probe, _ = _arm_turn(+ monkeypatch,+ requirements=True,+ sounddevice_factory=lambda: probe.append(1) or types.ModuleType("sounddevice"),+ )+ assert turn.use_streaming_tts is True+ assert probe == [], "arming must come from check_tts_requirements() alone, never the probe"+++def test_streaming_tts_stays_off_when_provider_unavailable(monkeypatch):+ """Arming remains honest: with the provider unavailable the turn stays unarmed+ (fallback to whole-response TTS), and no sounddevice probe happens there either."""+ turn, probe, _ = _arm_turn(monkeypatch, requirements=False)+ assert turn.use_streaming_tts is False+ assert turn.text_queue is None+ assert probe == [], "no sounddevice probe on the unarmed path"+++def test_streaming_tts_not_armed_without_voice_tts(monkeypatch):+ """Non-voice-tts turns are untouched: no probe, no queue, no thread."""+ import tools.tts_tool as tts_tool++ probe = []+ monkeypatch.setattr(tts_tool, "_import_sounddevice",+ lambda: probe.append(1) or types.ModuleType("sounddevice"))++ cli = _StreamingTTSArming().make_cli()+ cli._voice_tts = False+ turn = _StreamingTTSArming().make_turn()++ cli._chat_setup_turn_audio(turn, "hello", False)+ assert turn.use_streaming_tts is False+ assert turn.text_queue is None+ assert probe == []diff --git a/tests/tools/test_voice_silence_threshold_stop.py b/tests/tools/test_voice_silence_threshold_stop.pynew file mode 100644index 00000000000..2623bade7be--- /dev/null+++ b/tests/tools/test_voice_silence_threshold_stop.py@@ -0,0 +1,95 @@+"""Bug-fix regression tests for #84046: ``AudioRecorder.stop()`` must apply the CONFIGURED+silence threshold (``self._silence_threshold``, wired from ``voice.silence_threshold`` by the+CLI before each recording), not the hardcoded ``SILENCE_RMS_THRESHOLD`` default of 200 —+otherwise a low-threshold setup (e.g. 80 for a quiet mic that peaks at RMS ~160) auto-stops on+speech and then discards the valid recording as "too quiet".++numpy is absent from the test environment, so captured frames are faked as dicts that carry+just the attributes ``stop()`` touches (``__len__``, concatenation). This is a behavior+contract on the threshold, not on any waveform shape.+"""++import pytest++from tools.voice_mode import AudioRecorder, SILENCE_RMS_THRESHOLD+++class _Frame:+ """Minimal frame stand-in: length + concatenation + bytes, everything stop()+ and _write_wav touch. A constant-PCM stand-in would need numpy to build;+ plain zero bytes exercise the write path the same way the old silence+ fixture did."""++ def __init__(self, n):+ self._n = n++ def __len__(self):+ return self._n++ def tobytes(self):+ return b"\x00\x00" * self._n+++class _FakeAudio:+ def concatenate(self, frames, axis=0):+ assert axis == 0+ assert len(frames) == 1+ return frames[0]+++def mock_audio(monkeypatch, tmp_path):+ monkeypatch.setattr("tools.voice_mode._import_audio", lambda: (None, _FakeAudio()))+ monkeypatch.setattr("tools.voice_mode._TEMP_DIR", str(tmp_path))+ return _FakeAudio()+++def _arm(recorder, *, frames, peak_rms):+ """Put the recorder into the state a live capture leaves behind, without+ opening a real InputStream: recording flag on, frames + peak RMS loaded."""+ recorder._recording = True+ recorder._frames = list(frames)+ recorder._peak_rms = peak_rms+++class TestStopUsesConfiguredSilenceThreshold:++ def test_stop_keeps_recording_above_configured_threshold(self, mock_audio):+ """peak RMS above the CONFIGURED threshold (but below the 200 default) is+ valid speech and must be returned, not discarded as too quiet."""+ recorder = AudioRecorder()+ recorder._silence_threshold = 80 # the user's voice.silence_threshold+ _arm(recorder, frames=[_Frame(16000)], peak_rms=160) # above 80, below 200++ assert recorder.stop() is not None++ def test_stop_discards_recording_below_configured_threshold(self, mock_audio):+ """peak RMS below the CONFIGURED threshold is still silence and must be+ discarded — lowering the floor never lets noise through."""+ recorder = AudioRecorder()+ recorder._silence_threshold = 80+ _arm(recorder, frames=[_Frame(16000)], peak_rms=40) # below 80++ assert recorder.stop() is None++ def test_stop_threshold_tracks_reconfigured_threshold_between_recordings(self, mock_audio):+ """The discard gate follows the live attribute: the same peak RMS that was+ discarded under threshold 80 is kept after the CLI re-wires it to 60 before+ the next recording (per-recording reconfiguration, cli_voice_mixin)."""+ recorder = AudioRecorder()+ recorder._silence_threshold = 80+ _arm(recorder, frames=[_Frame(16000)], peak_rms=70)+ assert recorder.stop() is None # below 80: discarded++ recorder._silence_threshold = 60+ _arm(recorder, frames=[_Frame(16000)], peak_rms=70)+ assert recorder.stop() is not None # above 60: kept++ def test_stop_still_discards_below_default_threshold_without_config(self, mock_audio):+ """With no config override the constructor default (200) still applies: RMS+ 160 stays a silent recording. Pins the default against the custom floor."""+ recorder = AudioRecorder()+ assert recorder._silence_threshold == SILENCE_RMS_THRESHOLD+ _arm(recorder, frames=[_Frame(16000)], peak_rms=160)++ assert recorder.stop() is Nonediff --git a/tools/voice_mode.py b/tools/voice_mode.pyindex d2d0f5eebaf..7e604637bdb 100644--- a/tools/voice_mode.py+++ b/tools/voice_mode.py@@ -843,10 +843,13 @@ class AudioRecorder(_RecorderBase):if len(audio_data) < int(self._sample_rate * 0.3):logger.debug("Recording too short (%d samples), discarding", len(audio_data))return None- # Peak RMS, not the average (which trailing silence dilutes).- if self._peak_rms < SILENCE_RMS_THRESHOLD:+ # Peak RMS, not the average (which trailing silence dilutes). Same+ # configured floor as the VAD above — the hardcoded module default+ # here discarded valid speech on low-threshold setups (mic peaking+ # at RMS ~160 with voice.silence_threshold: 80, #84046).+ if self._peak_rms < self._silence_threshold:logger.info("Recording too quiet (peak RMS=%d < %d), discarding",- self._peak_rms, SILENCE_RMS_THRESHOLD)+ self._peak_rms, self._silence_threshold)return Nonereturn self._write_wav(audio_data, sample_rate=self._sample_rate)