The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(voice): thread max_recording_seconds through the TUI path, add behavior coverage
Solitud1nemaf7205bea5bc
diff --git a/cli.py b/cli.pyindex 084bf0a93ad..63ced237953 100644--- a/cli.py+++ b/cli.py@@ -11768,14 +11768,16 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):)# voice.max_recording_seconds — hard cap on a single recording's length.# Same numeric guard as the silence params (bool excluded: a hand-edited- # ``max_recording_seconds: true`` must not become ``1``). <= 0 disables- # the cap. Previously this documented key was never read, so the setting- # had no effect (dead config); wiring it here makes it take effect.+ # ``max_recording_seconds: true`` must not become ``1`` — it falls back+ # to the documented 120 default, mirroring the silence-param handling).+ # An explicit numeric value <= 0 disables the cap. Previously this+ # documented key was never read (dead config); wiring it here makes it+ # take effect._max_rec = voice_cfg.get("max_recording_seconds")self._voice_recorder._max_recording_seconds = (- _max_rec- if isinstance(_max_rec, (int, float)) and not isinstance(_max_rec, bool) and _max_rec > 0- else 0.0+ (_max_rec if _max_rec > 0 else 0.0)+ if isinstance(_max_rec, (int, float)) and not isinstance(_max_rec, bool)+ else 120.0)def _on_silence():diff --git a/hermes_cli/voice.py b/hermes_cli/voice.pyindex e0bd3efcfe6..224136c4646 100644--- a/hermes_cli/voice.py+++ b/hermes_cli/voice.py@@ -374,6 +374,7 @@ def start_continuous(silence_threshold: int = 200,silence_duration: float = 3.0,auto_restart: bool = True,+ max_recording_seconds: float = 0.0,) -> bool:"""Start a VAD-driven continuous recording loop.@@ -391,6 +392,10 @@ def start_continuous(``on_status`` is called with ``"listening"`` / ``"transcribing"`` /``"idle"`` so the UI can show a live indicator.++ ``max_recording_seconds`` is the hard cap on a single recording's length+ (``voice.max_recording_seconds``); any non-positive or non-numeric value+ disables the cap, preserving the previous unbounded behaviour."""global _continuous_active, _continuous_recorder, _continuous_auto_restartglobal _continuous_on_transcript, _continuous_on_status, _continuous_on_silent_limit@@ -416,6 +421,15 @@ def start_continuous(_continuous_recorder._silence_threshold = silence_threshold_continuous_recorder._silence_duration = silence_duration+ # Same numeric-with-bool-excluded guard as the CLI wiring in+ # cli.py:_voice_start_recording — <= 0 (or garbage) disables the cap.+ _continuous_recorder._max_recording_seconds = (+ max_recording_seconds+ if isinstance(max_recording_seconds, (int, float))+ and not isinstance(max_recording_seconds, bool)+ and max_recording_seconds > 0+ else 0.0+ )rec = _continuous_recorder_debug(diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex 8aafbb0f404..83f9127fc2c 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -1314,6 +1314,55 @@ def test_voice_record_start_handles_non_dict_voice_cfg(monkeypatch):assert captured["auto_restart"] is False+def test_voice_record_start_forwards_max_recording_seconds(monkeypatch):+ """voice.max_recording_seconds must reach start_continuous from the TUI.++ The CLI wiring alone doesn't cover TUI recordings: the gateway forwards+ recorder params explicitly, so a missing kwarg here silently leaves the+ cap dead in the TUI while CLI tests stay green. Semantics mirror the+ silence params: non-numeric / bool / missing falls back to the documented+ 120 default, an explicit numeric value <= 0 disables the cap.+ """+ captured: dict = {}++ def fake_start_continuous(**kwargs):+ captured.update(kwargs)++ monkeypatch.setitem(+ sys.modules,+ "hermes_cli.voice",+ types.SimpleNamespace(+ start_continuous=fake_start_continuous, stop_continuous=lambda: None+ ),+ )+ monkeypatch.setenv("HERMES_VOICE", "1")++ for cfg, expected in (+ ({"max_recording_seconds": 45}, 45), # explicit cap forwarded as-is+ ({"max_recording_seconds": 0}, 0.0), # explicit 0 = disabled+ ({"max_recording_seconds": -5}, 0.0), # negative = disabled+ ({}, 120.0), # missing = documented default+ ({"max_recording_seconds": True}, 120.0), # bool must not become 1s cap+ ({"max_recording_seconds": "long"}, 120.0), # garbage = documented default+ ):+ captured.clear()+ monkeypatch.setattr(server, "_load_cfg", lambda c=cfg: {"voice": c})++ resp = server.dispatch(+ {+ "id": "voice-record-cap",+ "method": "voice.record",+ "params": {"action": "start"},+ }+ )++ assert "result" in resp, f"voice.record raised for cfg={cfg!r}: {resp.get('error')}"+ assert resp["result"]["status"] == "recording"+ assert (+ captured["max_recording_seconds"] == expected+ ), f"cfg={cfg!r} forwarded {captured.get('max_recording_seconds')!r}, expected {expected!r}"++def test_voice_record_stop_forces_transcription(monkeypatch):captured: dict = {}diff --git a/tests/tools/test_voice_cli_integration.py b/tests/tools/test_voice_cli_integration.pyindex d098000452d..eeac640d7e1 100644--- a/tests/tools/test_voice_cli_integration.py+++ b/tests/tools/test_voice_cli_integration.py@@ -917,6 +917,59 @@ class TestVoiceBeepConfigReal:mock_beep.assert_not_called()+class TestMaxRecordingSecondsConfigReal:+ """voice.max_recording_seconds must reach the recorder from config.++ Regression for the dead-config fix: the predicate alone can stay green+ while the CLI wiring regresses, so pin the actual assignment made by+ ``_voice_start_recording`` for the valid / disabled / corrupted cases.+ """++ def _start_with_voice_cfg(self, voice_cfg):+ with patch("cli._cprint"), \+ patch("cli.threading.Thread", return_value=MagicMock(start=MagicMock())), \+ patch("tools.voice_mode.play_beep"), \+ patch("tools.voice_mode.create_audio_recorder") as mock_create, \+ patch(+ "tools.voice_mode.check_voice_requirements",+ return_value={+ "available": True,+ "audio_available": True,+ "stt_available": True,+ "details": "OK",+ "missing_packages": [],+ },+ ), \+ patch("hermes_cli.config.load_config", return_value={"voice": voice_cfg}):+ recorder = MagicMock()+ recorder.supports_silence_autostop = True+ mock_create.return_value = recorder++ cli = _make_voice_cli()+ cli._voice_start_recording()++ return recorder++ def test_configured_cap_reaches_recorder(self):+ recorder = self._start_with_voice_cfg({"max_recording_seconds": 45})+ assert recorder._max_recording_seconds == 45++ def test_non_positive_value_disables_cap(self):+ recorder = self._start_with_voice_cfg({"max_recording_seconds": 0})+ assert recorder._max_recording_seconds == 0.0++ def test_bool_falls_back_to_documented_default(self):+ # bool is a subclass of int — ``max_recording_seconds: true`` must not+ # become a 1-second cap; it falls back to the documented 120 default,+ # mirroring the silence-param corruption handling.+ recorder = self._start_with_voice_cfg({"max_recording_seconds": True})+ assert recorder._max_recording_seconds == 120.0++ def test_garbage_falls_back_to_documented_default(self):+ recorder = self._start_with_voice_cfg({"max_recording_seconds": "long"})+ assert recorder._max_recording_seconds == 120.0++class TestDisableVoiceModeReal:"""Tests _disable_voice_mode with real CLI instance."""diff --git a/tests/tools/test_voice_mode.py b/tests/tools/test_voice_mode.pyindex 2a4024fb9a7..79c9aba04de 100644--- a/tests/tools/test_voice_mode.py+++ b/tests/tools/test_voice_mode.py@@ -1431,6 +1431,92 @@ class TestSilenceDetection:recorder.cancel()+# ============================================================================+# Max recording length cap (voice.max_recording_seconds)+# ============================================================================++class TestMaxRecordingCap:+ """The hard cap must auto-stop through the real InputStream-callback+ path — not just the predicate — and fire the one-shot callback exactly+ once, independent of the silence-detection branches."""++ def _get_stream_callback(self, mock_sd):+ callback = mock_sd.InputStream.call_args.kwargs.get("callback")+ if callback is None:+ callback = mock_sd.InputStream.call_args[1]["callback"]+ return callback++ def test_cap_fires_one_shot_callback_during_continuous_speech(self, mock_sd):+ np = pytest.importorskip("numpy")+ import threading++ mock_sd.InputStream.return_value = MagicMock()++ from tools.voice_mode import AudioRecorder++ recorder = AudioRecorder()+ recorder._max_recording_seconds = 0.1+ # Park the other auto-stop branches far away so only the cap can fire:+ # loud frames keep the silence branch off, and max_wait covers the+ # no-speech branch.+ recorder._silence_duration = 60.0+ recorder._max_wait = 60.0++ fires = []+ fired = threading.Event()++ def on_stop():+ fires.append(1)+ fired.set()++ recorder.start(on_silence_stop=on_stop)+ callback = self._get_stream_callback(mock_sd)++ loud_frame = np.full((1600, 1), 5000, dtype="int16")+ callback(loud_frame, 1600, None, None)+ assert not fired.is_set(), "cap must not fire before the limit elapses"++ # Cross the cap while the user is STILL speaking — the silence branch+ # can never fire here, so a hit proves the cap path.+ time.sleep(0.12)+ callback(loud_frame, 1600, None, None)+ assert fired.wait(timeout=1.0) is True++ # One-shot: the handler cleared _on_silence_stop, further frames past+ # the cap must not fire again.+ assert recorder._on_silence_stop is None+ callback(loud_frame, 1600, None, None)+ time.sleep(0.05)+ assert len(fires) == 1++ recorder.cancel()++ def test_disabled_cap_never_fires_on_duration(self, mock_sd):+ np = pytest.importorskip("numpy")+ import threading++ mock_sd.InputStream.return_value = MagicMock()++ from tools.voice_mode import AudioRecorder++ recorder = AudioRecorder()+ recorder._max_recording_seconds = 0.0 # disabled (previous behaviour)+ recorder._silence_duration = 60.0+ recorder._max_wait = 60.0++ fired = threading.Event()+ recorder.start(on_silence_stop=lambda: fired.set())+ callback = self._get_stream_callback(mock_sd)++ loud_frame = np.full((1600, 1), 5000, dtype="int16")+ callback(loud_frame, 1600, None, None)+ time.sleep(0.12)+ callback(loud_frame, 1600, None, None)++ assert fired.wait(timeout=0.2) is False+ recorder.cancel()++# ============================================================================# Playback interrupt# ============================================================================diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex ace39ce9e52..e35e528a02c 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -17768,6 +17768,16 @@ def _(rid, params: dict) -> dict:if isinstance(duration, (int, float)) and not isinstance(duration, bool)else 3.0)+ # voice.max_recording_seconds — hard cap on a single recording's+ # length. Same guard as the silence params: non-numeric / bool /+ # missing falls back to the documented 120 default, while an+ # explicit numeric value <= 0 disables the cap (0.0).+ max_rec = voice_cfg.get("max_recording_seconds")+ safe_max_rec = (+ (max_rec if max_rec > 0 else 0.0)+ if isinstance(max_rec, (int, float)) and not isinstance(max_rec, bool)+ else 120.0+ )started = start_continuous(on_transcript=lambda t: _voice_emit("voice.transcript", {"text": t}),on_status=lambda s: _voice_emit("voice.status", {"state": s}),@@ -17777,6 +17787,7 @@ def _(rid, params: dict) -> dict:silence_threshold=safe_threshold,silence_duration=safe_duration,auto_restart=False,+ max_recording_seconds=safe_max_rec,)if started is False:return _ok(rid, {"status": "busy"})