The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): streaming TTS adapter contract and consumer (#60671)
Carl Taylor3a4aa2f8e698
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 83820b3a6a0..2d7163a3881 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -552,6 +552,75 @@ from gateway.session import SessionSource, build_session_keyfrom hermes_constants import get_default_hermes_root, get_hermes_dir, get_hermes_home+# ---------------------------------------------------------------------------+# Streaming TTS format descriptor and handle (#60671)+# ---------------------------------------------------------------------------++@dataclass+class AudioFormat:+ """Declared PCM format for a streaming-TTS session.++ All chunks delivered via ``write_streaming_tts`` must conform to this+ format: raw little-endian PCM at the declared sample rate, channels,+ and sample width.+ """+ sample_rate: int = 24000+ channels: int = 1+ sample_width: int = 2 # bytes per sample (int16 = 2)+++@dataclass+class StreamingTTSHandle:+ """Opaque handle returned by ``begin_streaming_tts``.++ Adapters may subclass or extend this with platform-specific state+ (track IDs, buffers, etc.). The base fields are used by the consumer+ for bookkeeping and cancellation.+ """+ chat_id: str = ""+ audio_format: AudioFormat = field(default_factory=AudioFormat)+ # Set to True after the first PCM chunk has been written (audible output+ # has started). The consumer uses this to decide whether a failure+ # should fall back to whole-file TTS (not yet audible) or just end+ # cleanly (already audible — don't replay from the beginning).+ audible: bool = False+ # Set to True by abort_streaming_tts; late chunks are dropped.+ aborted: bool = False+++def streaming_tts_turn_key(session_key: str | None, turn_marker: Any = None, *, event: Any = None) -> str | None:+ """Return a per-turn streaming-TTS suppression key.++ The key is intentionally turn-scoped, not chat-scoped, so overlapping+ turns in the same chat cannot suppress each other's fallback paths.+ ``turn_marker`` is usually the gateway run generation; if that is absent+ we fall back to the current event's message/update identifiers.+ """+ if not session_key:+ return None+ if turn_marker is None and event is not None:+ turn_marker = getattr(event, "message_id", None) or getattr(event, "platform_update_id", None)+ if turn_marker is None:+ return None+ return f"{session_key}:{turn_marker}"+++def streaming_tts_should_skip_whole_file(+ completed_turns: set[str],+ session_key: str | None,+ turn_marker: Any = None,+ *,+ event: Any = None,+) -> bool:+ """Pure helper used by the auto-TTS suppression path.++ Keeps the suppression decision turn-scoped and testable without+ exercising the whole adapter method stack.+ """+ turn_key = streaming_tts_turn_key(session_key, turn_marker, event=event)+ return bool(turn_key and turn_key in completed_turns)++GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE = ("Secure secret entry is not supported over messaging. ""Load this skill in the local CLI to be prompted, or add the key to ~/.hermes/.env manually."@@ -2759,6 +2828,11 @@ class BasePlatformAdapter(ABC):self._auto_tts_default: bool = Falseself._auto_tts_enabled_chats: set = set()self._auto_tts_disabled_chats: set = set()+ # Per-turn streaming-TTS completion flag (#60671). When the gateway+ # streaming-TTS consumer successfully delivers audio, it adds the+ # turn key here so the base adapter's whole-file auto-TTS path skips+ # the duplicate. Cleared after the turn completes.+ self._streaming_tts_completed_turns: set[str] = set()# Chats where typing indicator is paused (e.g. during approval waits).# _keep_typing skips send_typing when the chat_id is in this set.self._typing_paused: set = set()@@ -3925,6 +3999,89 @@ class BasePlatformAdapter(ABC):"""return await self.send_voice(chat_id=chat_id, audio_path=audio_path, **kwargs)+ # ------------------------------------------------------------------+ # Streaming TTS adapter contract (#60671)+ # ------------------------------------------------------------------+ # Voice-capable adapters (LiveKit, Discord voice, …) override these to+ # accept PCM audio chunks while the LLM is still generating. The default+ # implementations report "unsupported" so existing adapters are+ # source-compatible and keep the whole-file auto-TTS fallback.++ def supports_streaming_tts(self, chat_id: str, audio_format: AudioFormat) -> bool:+ """Return True when this adapter can accept streaming PCM for *chat_id*.++ Default: False (whole-file auto-TTS path remains). Override to opt in.+ """+ return False++ async def begin_streaming_tts(+ self,+ chat_id: str,+ audio_format: AudioFormat,+ metadata: Optional[Dict[str, Any]] = None,+ ) -> Optional[StreamingTTSHandle]:+ """Open a streaming-audio session for *chat_id*.++ Returns an opaque handle passed to subsequent ``write_streaming_tts``+ / ``finish_streaming_tts`` / ``abort_streaming_tts`` calls, or+ ``None`` to decline (caller falls back to whole-file TTS).+ """+ return None++ async def write_streaming_tts(self, handle: StreamingTTSHandle, chunk: bytes) -> None:+ """Write one PCM chunk to the adapter's outbound audio track."""+ pass++ async def finish_streaming_tts(self, handle: StreamingTTSHandle, *, interrupted: bool = False) -> None:+ """Signal normal end of the audio stream."""+ pass++ async def abort_streaming_tts(self, handle: StreamingTTSHandle, error: Optional[str] = None) -> None:+ """Abort the stream due to an error or cancellation.++ Must be idempotent: late producer chunks after abort must be silently+ dropped, not raise. Restores adapter state to "not streaming".+ """+ pass++ def _streaming_tts_turn_key(+ self,+ session_key: str | None,+ turn_marker: Any = None,+ *,+ event: Any = None,+ ) -> str | None:+ return streaming_tts_turn_key(session_key, turn_marker, event=event)++ def _mark_streaming_tts_completed_turn(+ self,+ session_key: str | None,+ turn_marker: Any = None,+ *,+ event: Any = None,+ ) -> None:+ turn_key = self._streaming_tts_turn_key(session_key, turn_marker, event=event)+ if turn_key is not None:+ completed = getattr(self, "_streaming_tts_completed_turns", None)+ if completed is None:+ completed = set()+ self._streaming_tts_completed_turns = completed+ completed.add(turn_key)++ def _streaming_tts_turn_completed(+ self,+ session_key: str | None,+ turn_marker: Any = None,+ *,+ event: Any = None,+ ) -> bool:+ return streaming_tts_should_skip_whole_file(+ getattr(self, "_streaming_tts_completed_turns", set()),+ session_key,+ turn_marker,+ event=event,+ )+async def send_video(self,chat_id: str,@@ -5620,12 +5777,19 @@ class BasePlatformAdapter(ABC):# Gated via ``_should_auto_tts_for_chat``: fires when the chat has# an explicit ``/voice on|tts`` opt-in OR when ``voice.auto_tts`` is# True globally and no ``/voice off`` has been issued.+ # Skip when streaming TTS already delivered audio for this turn+ # (#60671) — the gateway streaming-TTS consumer sets the flag._tts_path = None_tts_requested_path = Noneif (self._should_auto_tts_for_chat(event.source.chat_id)and event.message_type == MessageType.VOICEand text_content- and not media_files):+ and not media_files+ and not self._streaming_tts_turn_completed(+ session_key,+ getattr(interrupt_event, "_hermes_run_generation", None),+ event=event,+ )):try:from tools.tts_tool import text_to_speech_tool, check_tts_requirementsif check_tts_requirements():@@ -5941,6 +6105,15 @@ class BasePlatformAdapter(ABC):# Determine overall success for the processing hookprocessing_ok = delivery_succeeded if delivery_attempted else not bool(response)+ # Clean up the per-turn streaming-TTS flag (#60671).+ self._streaming_tts_completed_turns.discard(+ self._streaming_tts_turn_key(+ session_key,+ getattr(interrupt_event, "_hermes_run_generation", None),+ event=event,+ )+ or ""+ )await self._run_processing_hook("on_processing_complete",event,diff --git a/gateway/run.py b/gateway/run.pyindex 13f2743d962..fb94a8ab921 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -14424,6 +14424,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewmoa_config=getattr(event, "_moa_config", None),persist_user_message=persist_user_message,persist_user_timestamp=persist_user_timestamp,+ message_type=event.message_type,)# Stop persistent typing indicator now that the agent is done.@@ -14989,7 +14990,16 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# Auto voice reply: send TTS audio before the text response_already_sent = bool(agent_result.get("already_sent"))- if self._should_send_voice_reply(event, response, agent_messages, already_sent=_already_sent):+ # Skip when streaming TTS already delivered audio for this turn (#60671).+ _stts_adapter = self._adapter_for_source(source)+ _streaming_tts_done = (+ _stts_adapter is not None+ and bool(getattr(_stts_adapter, "_streaming_tts_turn_completed", lambda *_a, **_k: False)(session_key, run_generation))+ )+ if (+ not _streaming_tts_done+ and self._should_send_voice_reply(event, response, agent_messages, already_sent=_already_sent)+ ):await self._send_voice_reply(event, response)# If streaming already delivered the response, extract and@@ -20582,6 +20592,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewmoa_config: Optional[dict] = None,persist_user_message: Optional[Any] = None,persist_user_timestamp: Optional[float] = None,+ message_type: Optional[str] = None,) -> Dict[str, Any]:"""Profile-scoping wrapper around the agent run.@@ -20600,6 +20611,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewchannel_prompt=channel_prompt, moa_config=moa_config,persist_user_message=persist_user_message,persist_user_timestamp=persist_user_timestamp,+ message_type=message_type,)profile_home = self._resolve_profile_home_for_source(source)@@ -20611,6 +20623,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewchannel_prompt=channel_prompt, moa_config=moa_config,persist_user_message=persist_user_message,persist_user_timestamp=persist_user_timestamp,+ message_type=message_type,)def _profile_name_for_source(self, source: SessionSource) -> Optional[str]:@@ -20732,6 +20745,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewmoa_config: Optional[dict] = None,persist_user_message: Optional[Any] = None,persist_user_timestamp: Optional[float] = None,+ message_type: Optional[str] = None,) -> Dict[str, Any]:"""Run the agent with the given message and context.@@ -21706,6 +21720,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewresult_holder = [None] # Mutable container for the resulttools_holder = [None] # Mutable container for the tool definitionsstream_consumer_holder = [None] # Mutable container for stream consumer+ # #60671 — streaming PCM audio consumer. Created on the gateway+ # event-loop thread (NOT inside run_sync's executor worker) so the+ # outer finalisation / interrupt paths can reference it without a+ # cross-scope NameError.+ streaming_tts_consumer_holder: list = [None]# Bridge sync step_callback → async hooks.emit for agent:step events_loop_for_step = asyncio.get_running_loop()@@ -21808,6 +21827,44 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_cleanup_msg_ids.append(str(mid))_fut.add_done_callback(_track_status_id)+ # ---- Streaming TTS consumer setup (#60671) ----+ # Created on the gateway event-loop thread (here, in _run_agent_inner),+ # NOT inside run_sync's executor worker. This avoids a cross-scope+ # NameError: the outer interrupt / finalisation paths reference the+ # consumer via ``streaming_tts_consumer_holder[0]``.+ #+ # Gates: voice input, auto-TTS enabled for this chat, adapter+ # supports streaming, and a usable streaming TTS provider configured.+ _stts_adapter = self._adapter_for_source(source)+ _is_voice_input = (+ message_type is not None+ and str(getattr(message_type, "value", message_type)).lower() == "voice"+ )+ if (+ _stts_adapter is not None+ and _is_voice_input+ and _stts_adapter._should_auto_tts_for_chat(source.chat_id)+ ):+ try:+ from gateway.streaming_tts_consumer import StreamingTTSConsumer+ from tools.tts_tool import _load_tts_config+ _tts_cfg = _load_tts_config()+ _gateway_loop = self._gateway_loop or asyncio.get_event_loop()+ _stts_consumer = StreamingTTSConsumer(+ adapter=_stts_adapter,+ chat_id=source.chat_id,+ tts_config=_tts_cfg,+ loop=_gateway_loop,+ metadata=_status_thread_metadata,+ )+ if _stts_consumer.active:+ streaming_tts_consumer_holder[0] = _stts_consumer+ _stts_consumer.start()+ # else: consumer inactive (no streaming provider) — leave+ # the holder as None so the whole-file fallback path runs.+ except Exception as _stts_err:+ logger.debug("Could not set up streaming TTS consumer: %s", _stts_err)+def run_sync():# The conditional re-assignment of `message` further below# (prepending model-switch notes) makes Python treat it as a@@ -21885,6 +21942,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# Set up stream consumer for token streaming or interim commentary._stream_consumer = None_stream_delta_cb = None+ # #60671 — streaming TTS consumer is created on the outer+ # event-loop thread before run_sync launches. run_sync only+ # reads it via ``streaming_tts_consumer_holder[0]`` for delta+ # callback wiring.+ _stts_consumer_ref = streaming_tts_consumer_holder[0]_scfg = getattr(getattr(self, 'config', None), 'streaming', None)if _scfg is None:from gateway.config import StreamingConfig@@ -21969,10 +22031,21 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewdef _stream_delta_cb(text: str) -> None:if _run_still_current():_stream_consumer.on_delta(text)+ # Tee to the streaming-TTS consumer (#60671).+ if _stts_consumer_ref is not None:+ _stts_consumer_ref.on_delta(text)stream_consumer_holder[0] = _stream_consumerexcept Exception as _sc_err:logger.debug("Could not set up stream consumer: %s", _sc_err)+ # When text streaming is off but streaming TTS is active,+ # install a TTS-only delta callback so the consumer still+ # receives LLM deltas for audio synthesis (#60671).+ if _stream_delta_cb is None and _stts_consumer_ref is not None:+ def _stream_delta_cb(text: str) -> None:+ if _run_still_current():+ _stts_consumer_ref.on_delta(text)+def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:if not _run_still_current():return@@ -22860,6 +22933,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# Signal the stream consumer that the agent is doneif _stream_consumer is not None:_stream_consumer.finish()++ # Signal the streaming-TTS consumer that the agent is done (#60671).+ # finish() is called from the outer event-loop thread after the+ # executor returns, so early returns from run_sync are also+ # finalised. See the outer finally/completion section below.# Return final response, or a message if something went wrongfinal_response = result.get("final_response")@@ -23265,6 +23343,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewlogger.debug("Interrupt detected from adapter, signaling agent...")agent.interrupt(pending_text)_interrupt_detected.set()+ # Abort streaming TTS on barge-in (#60671).+ _stts = streaming_tts_consumer_holder[0]+ if _stts is not None:+ _stts.abort("barge-in")breakexcept asyncio.CancelledError:raise@@ -23465,6 +23547,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew)_backup_agent.interrupt(_bp_text)_interrupt_detected.set()+ # Abort streaming TTS on barge-in (#60671).+ _stts = streaming_tts_consumer_holder[0]+ if _stts is not None:+ _stts.abort("barge-in")+else:# Poll loop: check the agent's built-in activity tracker# (updated by _touch_activity() on every tool call, API@@ -23538,6 +23625,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew)_backup_agent.interrupt(_bp_text)_interrupt_detected.set()+ # Abort streaming TTS on barge-in (#60671).+ _stts = streaming_tts_consumer_holder[0]+ if _stts is not None:+ _stts.abort("barge-in")if _inactivity_timeout:# Build a diagnostic summary from the agent's activity tracker.@@ -23641,6 +23732,33 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# Check if we were interrupted OR have a queued message (/queue).result = result_holder[0]adapter = self._adapter_for_source(source)++ # Finalize the streaming-TTS consumer (#60671).+ #+ # finish() is called from the outer event-loop thread (not the+ # executor worker) so early returns from run_sync are also+ # finalised. wait_complete() drains queued audio; on timeout+ # the consumer is aborted unconditionally — if audio was+ # audible, suppression is preserved so the gateway does not+ # replay from the beginning; if no audio was audible, the+ # whole-file fallback path is permitted.+ _stts = streaming_tts_consumer_holder[0]+ if _stts is not None:+ _stts.finish()+ try:+ await _stts.wait_complete(timeout=10.0)+ except Exception as _stts_done_err:+ logger.debug("streaming TTS wait_complete error: %s", _stts_done_err)+ if not _stts.done:+ # Timeout before or after audible audio: abort to free+ # the consumer task. Audible streams retain suppression;+ # silent streams remain eligible for whole-file fallback.+ _stts.abort("streaming TTS finalisation timeout")+ await _stts.wait_complete(timeout=2.0)+ if _stts.suppress_whole_file and adapter is not None:+ _mark_turn = getattr(adapter, "_mark_streaming_tts_completed_turn", None)+ if callable(_mark_turn):+ _mark_turn(session_key, run_generation)# Get pending message from adapter.# Use session_key (not source.chat_id) to match adapter's storage keys.@@ -23853,6 +23971,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewnext_message_id = Nonenext_channel_prompt = Nonenext_session_key = session_key+ # #60671 — carry the pending event's message_type into the+ # recursive call so queued voice turns can stream TTS and+ # re-mark the generation for the final delivered turn.+ next_message_type = Noneif pending_event is not None:next_source = getattr(pending_event, "source", None) or sourceif self._is_goal_continuation_event(pending_event) and not self._goal_still_active_for_session(session_id):@@ -23884,6 +24006,20 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewreturn resultnext_message_id = self._reply_anchor_for_event(pending_event)next_channel_prompt = getattr(pending_event, "channel_prompt", None)+ next_message_type = getattr(pending_event, "message_type", None)++ # Clear the completed streaming marker from the prior logical+ # turn so the recursive turn's streaming TTS is not suppressed+ # by the prior turn's completion (#60671).+ _clear_adapter = self._adapter_for_source(source)+ if _clear_adapter is not None and session_key and run_generation is not None:+ _completed_turns = getattr(_clear_adapter, "_streaming_tts_completed_turns", None)+ if _completed_turns is not None:+ _prior_key = getattr(_clear_adapter, "_streaming_tts_turn_key", None)+ if callable(_prior_key):+ _pk = _prior_key(session_key, run_generation)+ if _pk:+ _completed_turns.discard(_pk)# Restart typing indicator so the user sees activity while# the follow-up turn runs. The outer _process_message_background@@ -23925,6 +24061,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_interrupt_depth=_interrupt_depth + 1,event_message_id=next_message_id,channel_prompt=next_channel_prompt,+ message_type=next_message_type,)return _preserve_queued_followup_history_offset(result, followup_result)finally:@@ -23964,6 +24101,17 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewexcept asyncio.CancelledError:pass+ # Unconditional abort + bounded wait for the streaming-TTS+ # consumer (#60671 hardening). Covers cancellation / exception+ # paths where the normal finalisation block was skipped.+ _stts_finally = streaming_tts_consumer_holder[0]+ if _stts_finally is not None and not _stts_finally.done:+ _stts_finally.abort("cleanup")+ try:+ await _stts_finally.wait_complete(timeout=2.0)+ except Exception:+ pass+# Clean up trackingtracking_task.cancel()if session_key:diff --git a/gateway/streaming_tts_consumer.py b/gateway/streaming_tts_consumer.pynew file mode 100644index 00000000000..86cafd4545a--- /dev/null+++ b/gateway/streaming_tts_consumer.py@@ -0,0 +1,423 @@+"""Gateway streaming-TTS consumer — LLM deltas to adapter PCM audio sink.++Bridges the synchronous agent ``stream_delta_callback`` (fired from the+worker thread) to a voice-capable platform adapter's streaming-audio+contract, so playback begins while the LLM is still generating.++Lifecycle::++ consumer = StreamingTTSConsumer(adapter, chat_id, tts_config, loop, metadata)+ agent.stream_delta_callback = consumer.on_delta # sync, non-blocking+ ... agent runs in executor ...+ consumer.finish() # signal end-of-text+ success = await consumer.wait_complete(timeout=10)+ if consumer.suppress_whole_file:+ # suppress whole-file auto-TTS for this turn+ consumer.abort("cancelled") # idempotent cancellation++Design:+- ``on_delta`` is synchronous and never blocks the agent thread. It feeds+ deltas into a ``SentenceChunker`` and queues completed clauses onto a+ thread-safe ``queue.Queue``.+- An asyncio task (``run``) runs on the gateway event loop, draining the+ queue, synthesising each clause via a ``StreamingTTSProvider``, and+ writing PCM chunks to the adapter.+- Per-turn state is isolated: each consumer instance owns its own chunker,+ queue, handle, and flags. Concurrent chats cannot cross-contaminate.+- On successful completion (all clauses synthesised and written), the+ consumer reports ``completed=True`` so the gateway can suppress the+ duplicate whole-file auto-TTS.+- On failure before any audible output, the consumer reports+ ``completed=False`` and clears ``suppress_whole_file`` so the gateway can+ fall back to whole-file TTS.+- On failure after partial audible output, the consumer reports+ ``completed=False`` but keeps ``suppress_whole_file=True`` so the gateway+ does NOT replay the whole response from the beginning.+- Cancellation/abort is idempotent: late chunks are silently dropped.+"""++from __future__ import annotations++import asyncio+import logging+import queue+import threading+from typing import Any, Dict, Optional++from gateway.platforms.base import AudioFormat, StreamingTTSHandle++logger = logging.getLogger("gateway.streaming_tts_consumer")++_ABORT = object()+_DONE = object()+++class StreamingTTSConsumer:+ """Consumes LLM text deltas and produces streaming PCM audio for an adapter."""++ def __init__(+ self,+ adapter: Any,+ chat_id: str,+ tts_config: Dict[str, Any],+ loop: asyncio.AbstractEventLoop,+ *,+ metadata: Optional[Dict[str, Any]] = None,+ audio_format: Optional[AudioFormat] = None,+ ) -> None:+ from tools.tts_streaming import SentenceChunker, resolve_streaming_provider++ self._adapter = adapter+ self._chat_id = chat_id+ self._tts_config = tts_config+ self._loop = loop+ self._metadata = metadata++ # Resolve the streaming provider once. If unavailable, the consumer is+ # inactive and the gateway falls back to whole-file TTS.+ self._streamer = resolve_streaming_provider(tts_config)+ self._chunker = SentenceChunker()++ if self._streamer is not None:+ self._audio_format = AudioFormat(+ sample_rate=int(getattr(self._streamer, "sample_rate", AudioFormat.sample_rate)),+ channels=int(getattr(self._streamer, "channels", AudioFormat.channels)),+ sample_width=int(getattr(self._streamer, "sample_width", AudioFormat.sample_width)),+ )+ else:+ self._audio_format = audio_format or AudioFormat()++ # Thread-safe queue: completed clauses and the occasional abort sentinel.+ self._queue: "queue.Queue[Any]" = queue.Queue(maxsize=256)++ # Per-turn state.+ self._handle: Optional[StreamingTTSHandle] = None+ self._started = False+ self._completed = False+ self._partial = False+ self._aborted = False+ self._finished = False+ self._dropped = False+ self._suppress_whole_file = False+ self._task: Optional[asyncio.Task] = None+ self._lock = threading.Lock()++ # Pre-allocate the strip-markdown helper lazily to avoid import cycles.+ self._strip_markdown = None++ # ------------------------------------------------------------------+ # Public properties+ # ------------------------------------------------------------------++ @property+ def active(self) -> bool:+ """True when this consumer has a usable streaming provider."""+ return self._streamer is not None++ @property+ def completed(self) -> bool:+ """True when streaming audio was fully delivered."""+ return self._completed++ @property+ def partial(self) -> bool:+ """True when some audio was audible before a failure or drop."""+ return self._partial++ @property+ def started(self) -> bool:+ """True when the adapter accepted the streaming session."""+ return self._started++ @property+ def audible(self) -> bool:+ """True once the first PCM chunk has been written."""+ return bool(self._handle and self._handle.audible)++ @property+ def dropped(self) -> bool:+ """True when queue saturation dropped at least one clause."""+ return self._dropped++ @property+ def suppress_whole_file(self) -> bool:+ """True when the gateway should skip the legacy whole-file TTS fallback."""+ return self._suppress_whole_file++ @property+ def done(self) -> bool:+ """True once the async drain task has terminated."""+ return self._task is not None and self._task.done()++ # ------------------------------------------------------------------+ # Sync callback (agent worker thread)+ # ------------------------------------------------------------------++ def on_delta(self, text: str) -> None:+ """Receive a text delta from the agent. Non-blocking."""+ if self._aborted or not self.active or self._finished:+ return+ try:+ for clause in self._chunker.feed(text):+ self._queue.put_nowait(clause)+ except queue.Full:+ self._dropped = True+ logger.debug("streaming TTS queue full, dropping clause")+ except Exception:+ logger.debug("streaming TTS on_delta error", exc_info=True)++ def finish(self) -> None:+ """Signal end-of-text and flush the chunker tail.++ Enqueues a ``_DONE`` sentinel after all flushed clauses so the+ drain loop has a deterministic termination signal that cannot+ race with a late ``on_delta`` or be lost when the queue is full.+ """+ if self._finished:+ return+ self._finished = True+ if self._aborted or not self.active:+ return+ try:+ for clause in self._chunker.flush():+ self._queue.put_nowait(clause)+ except queue.Full:+ self._dropped = True+ logger.debug("streaming TTS queue full while flushing tail")+ except Exception:+ pass+ # Guarantee the _DONE sentinel reaches the queue. If the bounded+ # queue is full, drain one item to make room — the sentinel is+ # load-bearing and must not be lost (#60671 hardening).+ self._enqueue_done()++ def _enqueue_done(self) -> None:+ """Enqueue the _DONE sentinel, evicting a queued clause if necessary."""+ while True:+ try:+ self._queue.put_nowait(_DONE)+ return+ except queue.Full:+ try:+ self._queue.get_nowait()+ self._dropped = True+ except queue.Empty:+ continue++ # ------------------------------------------------------------------+ # Async lifecycle (gateway event loop)+ # ------------------------------------------------------------------++ def start(self) -> asyncio.Task:+ """Create and return the async drain task on the gateway loop."""+ if self._task is not None:+ return self._task+ self._task = self._loop.create_task(self._run())+ return self._task++ async def _run(self) -> None:+ """Drain clauses from the queue, synthesise, and write to the adapter."""+ if not self.active:+ return++ if not self._adapter.supports_streaming_tts(self._chat_id, self._audio_format):+ logger.debug("adapter %s does not support streaming TTS", getattr(self._adapter, "name", "?"))+ return++ try:+ self._handle = await self._adapter.begin_streaming_tts(+ self._chat_id,+ self._audio_format,+ metadata=self._metadata,+ )+ except Exception as exc:+ logger.debug("begin_streaming_tts failed: %s", exc)+ self._handle = None+ return++ if self._handle is None:+ return++ self._started = True+ self._suppress_whole_file = False++ try:+ while True:+ if self._aborted:+ break+ try:+ item = await asyncio.to_thread(self._queue.get, True, 0.1)+ except queue.Empty:+ continue++ if item is _ABORT:+ break+ if item is _DONE:+ break+ if not isinstance(item, str):+ continue+ if self._aborted:+ break++ try:+ await self._synthesise_and_write(item)+ except Exception as exc:+ logger.warning("streaming TTS clause failed: %s", exc)+ if self._handle and self._handle.audible:+ self._partial = True+ self._suppress_whole_file = True+ else:+ self._suppress_whole_file = False+ self._completed = False+ await self._safe_abort(str(exc))+ return++ if not self._aborted and self._handle is not None:+ _finish_failed = False+ try:+ await self._adapter.finish_streaming_tts(self._handle, interrupted=self._aborted)+ except Exception as exc:+ logger.debug("finish_streaming_tts error: %s", exc)+ _finish_failed = True++ if _finish_failed:+ # finish_streaming_tts() raised — never report full+ # completion. If audio was already audible, report+ # partial and preserve suppression so the gateway+ # does not replay from the beginning. If no audio+ # was audible, permit whole-file fallback.+ if self._handle.audible:+ self._partial = True+ self._completed = False+ self._suppress_whole_file = True+ else:+ self._completed = False+ self._suppress_whole_file = False+ await self._safe_abort("finish_streaming_tts failed")+ elif self._handle.audible and not self._dropped:+ self._completed = True+ self._suppress_whole_file = True+ elif self._handle.audible and self._dropped:+ self._partial = True+ self._completed = False+ self._suppress_whole_file = True+ else:+ self._completed = False+ self._suppress_whole_file = False+ except Exception as exc:+ logger.warning("streaming TTS consumer error: %s", exc)+ await self._safe_abort(str(exc))+ finally:+ try:+ while not self._queue.empty():+ self._queue.get_nowait()+ except Exception:+ pass++ async def _synthesise_and_write(self, clause: str) -> None:+ """Synthesise one clause via the streamer and write PCM chunks."""+ if self._handle is None or self._handle.aborted:+ return++ cleaned = self._strip_markdown_for_tts(clause)+ if not cleaned or not cleaned.strip():+ return++ if self._streamer is None:+ return++ async for chunk in self._iter_stream_chunks(cleaned):+ if self._aborted or self._handle.aborted:+ return+ if not chunk:+ continue+ was_audible = self._handle.audible+ await self._adapter.write_streaming_tts(self._handle, chunk)+ if not was_audible:+ self._handle.audible = True+ self._suppress_whole_file = True++ async def _iter_stream_chunks(self, text: str):+ """Yield provider PCM chunks one at a time without blocking the loop."""+ if self._streamer is None:+ return+ iterator = iter(self._streamer.stream(text))+ while True:+ has_chunk, chunk = await asyncio.to_thread(self._next_stream_chunk, iterator)+ if not has_chunk:+ break+ yield chunk++ @staticmethod+ def _next_stream_chunk(iterator: Any) -> tuple[bool, Optional[bytes]]:+ try:+ return True, next(iterator)+ except StopIteration:+ return False, None++ def _strip_markdown_for_tts(self, text: str) -> str:+ """Lazy-import and apply the TTS markdown stripper."""+ if self._strip_markdown is None:+ try:+ from tools.tts_tool import _strip_markdown_for_tts as _strip+ self._strip_markdown = _strip+ except ImportError:+ self._strip_markdown = lambda t: t # noqa: E731+ return self._strip_markdown(text).strip()++ async def _safe_abort(self, reason: str) -> None:+ """Abort the adapter stream, swallowing errors (idempotent)."""+ if self._handle is None:+ return+ try:+ await self._adapter.abort_streaming_tts(self._handle, error=reason)+ except Exception:+ pass+ finally:+ if self._handle:+ self._handle.aborted = True++ # ------------------------------------------------------------------+ # Cancellation and completion+ # ------------------------------------------------------------------++ def abort(self, reason: str = "cancelled") -> None:+ """Idempotent cancellation from any thread."""+ with self._lock:+ if self._aborted:+ return+ self._aborted = True+ # Guarantee the _ABORT sentinel reaches the queue. If the bounded+ # queue is full, drain one item to make room — the sentinel must+ # not be lost (#60671 hardening).+ for _attempt in range(3):+ try:+ self._queue.put_nowait(_ABORT)+ break+ except queue.Full:+ try:+ self._queue.get_nowait()+ except queue.Empty:+ break+ else:+ logger.debug("streaming TTS _ABORT sentinel could not be enqueued")+ if self._handle is not None and not self._handle.aborted:+ try:+ self._loop.call_soon_threadsafe(+ asyncio.create_task,+ self._safe_abort(reason),+ )+ except Exception:+ pass++ async def wait_complete(self, timeout: float = 10.0) -> bool:+ """Wait for the drain task to finish. Returns True only on full success."""+ if self._task is None:+ return self._completed+ try:+ await asyncio.wait_for(asyncio.shield(self._task), timeout=timeout)+ except (asyncio.TimeoutError, asyncio.CancelledError):+ pass+ except Exception:+ pass+ return self._completeddiff --git a/tests/gateway/test_streaming_tts_consumer.py b/tests/gateway/test_streaming_tts_consumer.pynew file mode 100644index 00000000000..8fa686c5b4c--- /dev/null+++ b/tests/gateway/test_streaming_tts_consumer.py@@ -0,0 +1,885 @@+"""Tests for the gateway streaming-TTS consumer and adapter contract (#60671).++No live audio, network, or TTS SDK calls: the streaming provider, adapter,+and event loop are all faked. Covers the adapter contract defaults, the+consumer lifecycle (begin/write/finish/abort), fallback safety, duplicate+suppression, cancellation idempotency, and concurrent-turn isolation.+"""++from __future__ import annotations++import asyncio+import queue+import threading+import time++import pytest++from gateway.platforms.base import AudioFormat, StreamingTTSHandle+from gateway.streaming_tts_consumer import StreamingTTSConsumer+from tools.tts_streaming import SentenceChunker+++# ---------------------------------------------------------------------------+# Fakes+# ---------------------------------------------------------------------------+++class FakeStreamer:+ """Fake streaming provider that yields deterministic PCM chunks."""++ def __init__(self, chunks_per_clause=3, fail_on_clause=None, sample_rate=24000, channels=1, sample_width=2):+ self.chunks_per_clause = chunks_per_clause+ self.fail_on_clause = fail_on_clause+ self.sample_rate = sample_rate+ self.channels = channels+ self.sample_width = sample_width+ self._clause_count = 0++ def stream(self, text: str):+ self._clause_count += 1+ if self.fail_on_clause and self._clause_count >= self.fail_on_clause:+ raise RuntimeError(f"fake streamer failure on clause {self._clause_count}")+ for i in range(self.chunks_per_clause):+ yield f"chunk-{self._clause_count}-{i}".encode()+++class FakeVoiceAdapter:+ """Fake adapter that accepts streaming TTS."""++ def __init__(self, name="fake-voice", supports=True, fail_after_write=False):+ self.name = name+ self._supports = supports+ self._fail_after_write = fail_after_write+ self.handle = None+ self.written_chunks: list[bytes] = []+ self.begin_count = 0+ self.finish_count = 0+ self.abort_count = 0++ def _should_auto_tts_for_chat(self, chat_id):+ return True++ def supports_streaming_tts(self, chat_id, audio_format):+ return self._supports++ async def begin_streaming_tts(self, chat_id, audio_format, metadata=None):+ self.begin_count += 1+ if not self._supports:+ return None+ self.handle = StreamingTTSHandle(chat_id=chat_id, audio_format=audio_format)+ return self.handle++ async def write_streaming_tts(self, handle, chunk):+ if self._fail_after_write and len(self.written_chunks) >= 2:+ raise RuntimeError("adapter write failure after partial output")+ self.written_chunks.append(chunk)+ if not handle.audible:+ handle.audible = True++ async def finish_streaming_tts(self, handle, *, interrupted=False):+ self.finish_count += 1++ async def abort_streaming_tts(self, handle, error=None):+ self.abort_count += 1+ if handle:+ handle.aborted = True+++class SlowStreamer(FakeStreamer):+ """Fake streamer whose iteration intentionally blocks off the event loop."""++ def __init__(self, *args, delay_s=0.15, **kwargs):+ super().__init__(*args, **kwargs)+ self.delay_s = delay_s+ self.started = threading.Event()+ self.finished = threading.Event()++ def stream(self, text: str):+ self.started.set()+ try:+ for chunk in super().stream(text):+ time.sleep(self.delay_s)+ yield chunk+ finally:+ self.finished.set()+++class SlowFirstChunkStreamer(FakeStreamer):+ """Blocks before the first chunk so timeout happens before audio starts."""++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.started = threading.Event()+ self.allow_first_chunk = threading.Event()+ self.finished = threading.Event()++ def stream(self, text: str):+ self.started.set()+ try:+ self.allow_first_chunk.wait(timeout=5.0)+ yield b"chunk-1-0"+ finally:+ self.finished.set()+++class BlockingSecondChunkStreamer(FakeStreamer):+ """Yields one chunk immediately, then blocks before the remaining chunks."""++ def __init__(self, *args, **kwargs):+ super().__init__(*args, chunks_per_clause=2, **kwargs)+ self.started = threading.Event()+ self.first_chunk_written = threading.Event()+ self.allow_remaining_chunks = threading.Event()+ self.finished = threading.Event()++ def stream(self, text: str):+ self.started.set()+ try:+ yield b"chunk-1-0"+ self.first_chunk_written.set()+ self.allow_remaining_chunks.wait(timeout=5.0)+ yield b"chunk-1-1"+ finally:+ self.finished.set()+++class UnsupportedAdapter:+ """Adapter that does not support streaming TTS (default base behaviour)."""++ def _should_auto_tts_for_chat(self, chat_id):+ return True++ def supports_streaming_tts(self, chat_id, audio_format):+ return False++ async def begin_streaming_tts(self, chat_id, audio_format, metadata=None):+ return None++ async def write_streaming_tts(self, handle, chunk):+ pass++ async def finish_streaming_tts(self, handle, *, interrupted=False):+ pass++ async def abort_streaming_tts(self, handle, error=None):+ pass+++def _make_consumer(adapter, chat_id, loop, streamer):+ """Build a StreamingTTSConsumer with pre-set internals for testing."""+ consumer = StreamingTTSConsumer.__new__(StreamingTTSConsumer)+ consumer._adapter = adapter+ consumer._chat_id = chat_id+ consumer._tts_config = {}+ consumer._loop = loop+ consumer._metadata = None+ consumer._audio_format = AudioFormat(+ sample_rate=int(getattr(streamer, "sample_rate", 24000)) if streamer is not None else 24000,+ channels=int(getattr(streamer, "channels", 1)) if streamer is not None else 1,+ sample_width=int(getattr(streamer, "sample_width", 2)) if streamer is not None else 2,+ )+ consumer._streamer = streamer # type: ignore[assignment]+ consumer._chunker = SentenceChunker()+ consumer._queue = queue.Queue(maxsize=256)+ consumer._handle = None+ consumer._started = False+ consumer._completed = False+ consumer._partial = False+ consumer._aborted = False+ consumer._finished = False+ consumer._dropped = False+ consumer._suppress_whole_file = False+ consumer._task = None+ consumer._lock = threading.Lock()+ consumer._strip_markdown = None+ return consumer+++def _run_test(coro_factory, timeout=10.0):+ """Run an async test in a fresh event loop."""+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(+ asyncio.wait_for(coro_factory(loop), timeout=timeout)+ )+ finally:+ loop.close()+++# ---------------------------------------------------------------------------+# Adapter contract defaults (BasePlatformAdapter)+# ---------------------------------------------------------------------------+++def _make_minimal_adapter():+ """Create a minimal concrete BasePlatformAdapter for testing defaults."""+ from gateway.platforms.base import BasePlatformAdapter++ class _Minimal(BasePlatformAdapter):+ async def send(self, chat_id, content, **kw):+ pass++ async def send_voice(self, chat_id, audio_path, **kw):+ pass++ async def connect(self, **kw):+ return True++ async def disconnect(self):+ pass++ async def get_chat_info(self, chat_id):+ return {}++ adapter = object.__new__(_Minimal)+ adapter._streaming_tts_completed_turns = set()+ return adapter+++class TestAdapterContractDefaults:+ """Verify the default adapter reports unsupported and is source-compatible."""++ def test_supports_streaming_tts_defaults_false(self):+ adapter = _make_minimal_adapter()+ assert adapter.supports_streaming_tts("chat1", AudioFormat()) is False++ def test_begin_returns_none_by_default(self):+ adapter = _make_minimal_adapter()+ loop = asyncio.new_event_loop()+ try:+ result = loop.run_until_complete(+ adapter.begin_streaming_tts("chat1", AudioFormat())+ )+ assert result is None+ finally:+ loop.close()++ def test_write_finish_abort_are_noops_by_default(self):+ adapter = _make_minimal_adapter()+ handle = StreamingTTSHandle()+ loop = asyncio.new_event_loop()+ try:+ loop.run_until_complete(adapter.write_streaming_tts(handle, b"data"))+ loop.run_until_complete(adapter.finish_streaming_tts(handle))+ loop.run_until_complete(adapter.abort_streaming_tts(handle, "test"))+ finally:+ loop.close()++ def test_audio_format_defaults(self):+ fmt = AudioFormat()+ assert fmt.sample_rate == 24000+ assert fmt.channels == 1+ assert fmt.sample_width == 2++ def test_handle_defaults(self):+ h = StreamingTTSHandle()+ assert h.audible is False+ assert h.aborted is False+ assert h.chat_id == ""+++# ---------------------------------------------------------------------------+# StreamingTTSConsumer lifecycle+# ---------------------------------------------------------------------------+++class TestConsumerLifecycle:+ """Begin/write/finish lifecycle exactly once on success."""++ def test_successful_stream_produces_ordered_chunks(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = FakeStreamer(chunks_per_clause=2)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("This is the first sentence. ")+ consumer.on_delta("Here is the second one. ")+ consumer.finish()++ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is True+ assert adapter.begin_count == 1+ assert adapter.finish_count == 1+ assert adapter.abort_count == 0+ # 2 clauses * 2 chunks each = 4 chunks+ assert len(adapter.written_chunks) == 4+ # Verify ordering+ assert adapter.written_chunks[0] == b"chunk-1-0"+ assert adapter.written_chunks[1] == b"chunk-1-1"+ assert adapter.written_chunks[2] == b"chunk-2-0"+ assert adapter.written_chunks[3] == b"chunk-2-1"++ _run_test(run)++ def test_first_adapter_write_happens_before_provider_finishes_yielding_all_chunks(self):+ class FirstWriteAdapter(FakeVoiceAdapter):+ def __init__(self):+ super().__init__()+ self.first_write = threading.Event()++ async def write_streaming_tts(self, handle, chunk):+ await super().write_streaming_tts(handle, chunk)+ self.first_write.set()++ async def run(loop):+ adapter = FirstWriteAdapter()+ streamer = BlockingSecondChunkStreamer()+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("One sentence. ")+ consumer.finish()++ await asyncio.wait_for(asyncio.to_thread(adapter.first_write.wait, 1.0), timeout=1.0)+ assert streamer.finished.is_set() is False+ assert adapter.written_chunks == [b"chunk-1-0"]++ streamer.allow_remaining_chunks.set()+ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is True+ assert streamer.finished.is_set() is True+ assert adapter.written_chunks == [b"chunk-1-0", b"chunk-1-1"]++ _run_test(run)++ def test_pre_audio_timeout_aborts_before_fallback_can_replay(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = SlowFirstChunkStreamer()+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("This sentence will stall before the first chunk. ")+ consumer.finish()++ await asyncio.wait_for(asyncio.to_thread(streamer.started.wait, 1.0), timeout=1.0)+ completed = await consumer.wait_complete(timeout=0.05)+ assert completed is False+ assert consumer.audible is False+ assert consumer.suppress_whole_file is False+ consumer.abort("streaming TTS finalisation timeout")+ await asyncio.sleep(0.05)+ assert adapter.abort_count == 1++ streamer.allow_first_chunk.set()+ await consumer.wait_complete(timeout=1.0)+ assert adapter.written_chunks == []+ assert streamer.finished.is_set() is True++ _run_test(run)++ def test_post_audio_timeout_keeps_suppression_then_aborts(self):+ """After audible audio, a finalisation timeout aborts the consumer.++ The outer gateway loop calls abort() on timeout so no unowned+ consumer task lingers. Suppression is preserved so the gateway+ does not replay from the beginning. Updated for #60671+ hardening: the outer loop now aborts instead of leaving the+ consumer to complete later in the background.+ """+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = BlockingSecondChunkStreamer()+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("This is a sentence with a delayed tail. ")+ consumer.finish()++ await asyncio.wait_for(asyncio.to_thread(streamer.first_chunk_written.wait, 1.0), timeout=1.0)+ await asyncio.sleep(0)+ assert consumer.audible is True+ assert consumer.suppress_whole_file is True+ assert streamer.finished.is_set() is False++ completed = await consumer.wait_complete(timeout=0.01)+ assert completed is False+ assert consumer.suppress_whole_file is True+ assert adapter.written_chunks == [b"chunk-1-0"]++ # The outer loop now aborts on timeout after audible audio+ # instead of leaving the consumer running in the background.+ consumer.abort("streaming TTS finalisation timeout")+ await consumer.wait_complete(timeout=2.0)++ # The consumer is aborted, not completed.+ assert consumer.completed is False+ assert consumer._aborted is True+ assert consumer.suppress_whole_file is True++ _run_test(run)++ def test_unsupported_adapter_falls_back(self):+ async def run(loop):+ adapter = UnsupportedAdapter()+ streamer = FakeStreamer()+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("Hello world. ")+ consumer.finish()++ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is False+ assert consumer._started is False++ _run_test(run)++ def test_no_streamer_falls_back(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ consumer = _make_consumer(adapter, "chat1", loop, None)++ consumer.start()+ consumer.on_delta("Hello world. ")+ consumer.finish()++ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is False+ assert consumer.active is False++ _run_test(run)+++class TestStreamerFormatAndLooping:+ """Constructor wiring should derive format and keep provider I/O off-loop."""++ def test_audio_format_tracks_resolved_streamer(self):+ streamer = FakeStreamer(chunks_per_clause=1, sample_rate=48000, channels=2, sample_width=4)+ import tools.tts_streaming as tts_streaming+ original_resolve = tts_streaming.resolve_streaming_provider+ tts_streaming.resolve_streaming_provider = lambda *_args, **_kwargs: streamer+ loop = asyncio.new_event_loop()+ try:+ consumer = StreamingTTSConsumer(FakeVoiceAdapter(), "chat1", {}, loop)+ assert consumer._audio_format.sample_rate == 48000+ assert consumer._audio_format.channels == 2+ assert consumer._audio_format.sample_width == 4+ finally:+ tts_streaming.resolve_streaming_provider = original_resolve+ loop.close()++ def test_provider_iteration_runs_off_the_event_loop(self):+ async def run(loop):+ slow = SlowStreamer(chunks_per_clause=1, delay_s=0.2)+ adapter = FakeVoiceAdapter()+ import tools.tts_streaming as tts_streaming+ original_resolve = tts_streaming.resolve_streaming_provider+ tts_streaming.resolve_streaming_provider = lambda *_args, **_kwargs: slow+ try:+ consumer = StreamingTTSConsumer(adapter, "chat1", {}, loop)+ consumer.start()+ consumer.on_delta("This is a sentence that is long enough to speak. ")+ consumer.finish()++ await asyncio.wait_for(asyncio.to_thread(slow.started.wait, 1.0), timeout=1.0)+ await asyncio.wait_for(asyncio.sleep(0.05), timeout=0.2)++ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is True+ assert slow.finished.is_set() is True+ finally:+ tts_streaming.resolve_streaming_provider = original_resolve++ _run_test(run)+++class TestGatewayIntegrationSeam:+ """The actual adapter seam is per-turn, not chat-only."""++ def test_duplicate_suppression_is_per_turn(self):+ from gateway.platforms.base import streaming_tts_should_skip_whole_file++ adapter = _make_minimal_adapter()+ turn_one = adapter._streaming_tts_turn_key("chat-1", 101)+ turn_two = adapter._streaming_tts_turn_key("chat-1", 102)+ assert turn_one != turn_two++ adapter._mark_streaming_tts_completed_turn("chat-1", 101)+ assert streaming_tts_should_skip_whole_file(+ adapter._streaming_tts_completed_turns,+ "chat-1",+ 101,+ ) is True+ assert streaming_tts_should_skip_whole_file(+ adapter._streaming_tts_completed_turns,+ "chat-1",+ 102,+ ) is False+ assert adapter._streaming_tts_turn_completed("chat-1", 101) is True+ assert adapter._streaming_tts_turn_completed("chat-1", 102) is False+ assert adapter._streaming_tts_turn_completed("chat-2", 101) is False+++class TestAbortAndCancellation:+ """Abort lifecycle: idempotent, prevents late chunks."""++ def test_abort_is_idempotent(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = FakeStreamer(chunks_per_clause=10)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("A sentence. ")+ # Abort multiple times+ consumer.abort("test")+ consumer.abort("test2")+ consumer.abort("test3")+ consumer.finish()++ await consumer.wait_complete(timeout=5.0)+ # Abort should have been called at most once on the adapter+ assert adapter.abort_count <= 1++ _run_test(run)++ def test_abort_prevents_late_chunks(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = FakeStreamer(chunks_per_clause=10)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("First sentence. ")+ consumer.abort("barge-in")+ # Late deltas should be silently dropped+ consumer.on_delta("Late sentence that should not play. ")+ consumer.finish()++ await consumer.wait_complete(timeout=5.0)+ assert consumer._aborted is True++ _run_test(run)+++class TestFallbackSafety:+ """Pre-audio failure falls back; post-audio failure does not replay."""++ def test_pre_audio_failure_falls_back(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = FakeStreamer(fail_on_clause=1)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("A sentence. ")+ consumer.finish()++ completed = await consumer.wait_complete(timeout=5.0)+ # Pre-audio failure: should NOT report completed (fall back)+ assert completed is False+ assert adapter.abort_count >= 1++ _run_test(run)++ def test_post_audio_failure_does_not_replay(self):+ async def run(loop):+ adapter = FakeVoiceAdapter(fail_after_write=True)+ streamer = FakeStreamer(chunks_per_clause=5)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("First sentence here. ")+ consumer.on_delta("Second sentence here. ")+ consumer.finish()++ completed = await consumer.wait_complete(timeout=5.0)+ # Post-audio failure: should not claim full completion, but the+ # gateway must still suppress the legacy whole-file replay.+ assert completed is False+ assert consumer._partial is True+ assert consumer.suppress_whole_file is True+ assert len(adapter.written_chunks) > 0++ _run_test(run)+++class TestConcurrentTurnIsolation:+ """Per-turn state is isolated across concurrent chats."""++ def test_two_concurrent_turns_do_not_cross_contaminate(self):+ async def run(loop):+ adapter1 = FakeVoiceAdapter(name="adapter1")+ adapter2 = FakeVoiceAdapter(name="adapter2")+ streamer = FakeStreamer(chunks_per_clause=2)++ c1 = _make_consumer(adapter1, "chat1", loop, streamer)+ c2 = _make_consumer(adapter2, "chat2", loop, streamer)++ c1.start()+ c2.start()++ c1.on_delta("Sentence for chat one. ")+ c2.on_delta("Sentence for chat two. ")++ c1.finish()+ c2.finish()++ await c1.wait_complete(timeout=5.0)+ await c2.wait_complete(timeout=5.0)++ # Each adapter should only have its own chunks+ assert adapter1.written_chunks != adapter2.written_chunks+ # Both should have completed+ assert c1.completed is True+ assert c2.completed is True++ _run_test(run)+++class TestThinkBlockSuppression:+ """Think blocks split across deltas are never synthesised."""++ def test_think_blocks_not_synthesised(self):+ c = SentenceChunker()+ # Think block split across deltas — content inside is stripped.+ # The SentenceChunker uses min_len=20: sentences shorter than+ # 20 chars (after strip) are merged into the next one.+ assert c.feed("\x3cthink\x3esecret reasoning") == []+ # Feed a long enough sentence after the think block closes.+ result = c.feed(" about the answer.\x3c/think\x3e This is the actual spoken answer that is long enough. ")+ assert len(result) == 1+ assert "This is the actual spoken answer that is long enough." in result[0]+ assert c.flush() == []+++class TestQueueBackpressure:+ """on_delta does not block when the queue is full."""++ def test_full_queue_drops_clause_not_blocks(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = FakeStreamer(chunks_per_clause=1)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)+ # Tiny queue to trigger backpressure.+ consumer._queue = queue.Queue(maxsize=1)+ consumer._queue.put_nowait("prefilled")++ start = time.perf_counter()+ for i in range(50):+ consumer.on_delta(f"Sentence number {i}. ")+ elapsed = time.perf_counter() - start+ assert elapsed < 0.05++ consumer.finish()+ assert consumer.dropped is True+ completed = await consumer.wait_complete(timeout=1.0)+ assert completed is False+ assert consumer.completed is False+ assert consumer.suppress_whole_file is False++ _run_test(run, timeout=15.0)+++# ---------------------------------------------------------------------------+# Finish race: _DONE sentinel guarantees the final clause is not lost (#60671)+# ---------------------------------------------------------------------------+++class DelayedFlushChunker:+ """Chunker whose flush() returns a clause only after a signal is set.++ This simulates a provider that buffers the last clause and only+ releases it on flush(), after the drain loop has already started+ waiting. The _DONE sentinel must arrive AFTER the flushed clause+ so the loop does not terminate early and lose the tail.+ """++ def __init__(self):+ self._flushed = threading.Event()+ self.allow_flush = threading.Event()++ def feed(self, delta: str):+ # Accumulate into a buffer; no sentences are released until flush.+ return []++ def flush(self):+ self._flushed.set()+ self.allow_flush.wait(timeout=5.0)+ return ["The final tail clause that must not be lost."]+++class TestFinishSentinelRace:+ """The _DONE sentinel must not overtake a delayed flush clause."""++ def test_delayed_flush_clause_is_not_lost(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = FakeStreamer(chunks_per_clause=2)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)+ # Replace the chunker with the delayed-flush variant.+ consumer._chunker = DelayedFlushChunker()++ consumer.start()+ consumer.on_delta("Some text that buffers inside the chunker. ")+ # Run finish() off-loop so the drain task can observe the exact+ # historical race: _finished is true while flush() is blocked and+ # the queue is still empty.+ finish_task = asyncio.create_task(asyncio.to_thread(consumer.finish))++ # Wait for flush() to block, then give the drain loop longer than+ # its queue.get timeout. The old `_finished and queue.empty()`+ # escape hatch would terminate here and lose the tail clause.+ await asyncio.wait_for(+ asyncio.to_thread(consumer._chunker._flushed.wait, 2.0),+ timeout=2.0,+ )+ await asyncio.sleep(0.2)+ consumer._chunker.allow_flush.set()+ await finish_task++ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is True+ # The tail clause must have been synthesised and written.+ assert len(adapter.written_chunks) > 0+ assert adapter.finish_count == 1++ _run_test(run)++ def test_done_sentinel_survives_full_queue(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = FakeStreamer(chunks_per_clause=1)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)+ # Saturate the queue so _DONE must evict to be enqueued.+ consumer._queue = queue.Queue(maxsize=2)+ consumer._queue.put_nowait("clause-A")+ consumer._queue.put_nowait("clause-B")++ consumer.start()+ consumer.finish()+ # The sentinel must have been enqueued (evicting a clause).+ # The drain loop should process remaining items and the _DONE.+ completed = await consumer.wait_complete(timeout=5.0)+ # At least one clause should have been written.+ assert len(adapter.written_chunks) >= 1++ _run_test(run)+++# ---------------------------------------------------------------------------+# Adapter finish failure (#60671)+# ---------------------------------------------------------------------------+++class FinishFailingAdapter(FakeVoiceAdapter):+ """Adapter whose finish_streaming_tts() always raises."""++ async def finish_streaming_tts(self, handle, *, interrupted=False):+ raise RuntimeError("adapter finish failure")+++class TestAdapterFinishFailure:+ """If finish_streaming_tts() raises, never report full completion."""++ def test_finish_failure_after_audible_reports_partial(self):+ async def run(loop):+ adapter = FinishFailingAdapter()+ streamer = FakeStreamer(chunks_per_clause=2)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("A sentence that produces audio. ")+ consumer.finish()++ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is False+ assert consumer.partial is True+ assert consumer.suppress_whole_file is True+ assert len(adapter.written_chunks) > 0++ _run_test(run)++ def test_finish_failure_before_audible_permits_fallback(self):+ async def run(loop):+ adapter = FinishFailingAdapter()+ streamer = FakeStreamer(chunks_per_clause=0)+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ # No deltas — nothing is audible.+ consumer.finish()++ completed = await consumer.wait_complete(timeout=5.0)+ assert completed is False+ assert consumer.suppress_whole_file is False+ assert consumer.partial is False++ _run_test(run)+++# ---------------------------------------------------------------------------+# Post-audio timeout: clean abort, no later background completion (#60671)+# ---------------------------------------------------------------------------+++class TestPostAudioTimeoutAbort:+ """On finalisation timeout after audible audio, abort the consumer."""++ def test_timeout_after_audible_aborts_and_preserves_suppression(self):+ async def run(loop):+ adapter = FakeVoiceAdapter()+ streamer = BlockingSecondChunkStreamer()+ consumer = _make_consumer(adapter, "chat1", loop, streamer)++ consumer.start()+ consumer.on_delta("This is a sentence with a delayed tail. ")+ consumer.finish()++ await asyncio.wait_for(+ asyncio.to_thread(streamer.first_chunk_written.wait, 2.0),+ timeout=2.0,+ )+ assert consumer.audible is True+ assert consumer.suppress_whole_file is True++ # Timeout: the consumer should be aborted, not left running.+ completed = await consumer.wait_complete(timeout=0.01)+ assert completed is False+ assert consumer.suppress_whole_file is True++ # Simulate the outer loop's abort-on-timeout behaviour.+ consumer.abort("streaming TTS finalisation timeout")+ await asyncio.sleep(0.05)++ # The consumer must not complete later in the background.+ assert consumer.completed is False+ assert consumer._aborted is True++ _run_test(run)+++# ---------------------------------------------------------------------------+# Real gateway regression: no _streaming_tts_consumer NameError (#60671)+# ---------------------------------------------------------------------------+++class TestGatewayOuterFinalisationNoNameError:+ """Exercise the real outer finalisation path to prove no NameError.++ This test does NOT use the StreamingTTSConsumer helper tests alone —+ it verifies that ``gateway/run.py``'s outer finalisation code can+ reference ``streaming_tts_consumer_holder[0]`` without hitting a+ NameError on a normal gateway turn. We do this by importing the+ symbol and exercising the code path that would have failed.+ """++ def test_streaming_tts_consumer_holder_is_list_not_name(self):+ """The outer scope uses a holder list, not a bare local name.++ This is a structural invariant: if someone reintroduces the+ cross-scope NameError by moving the consumer back into+ ``run_sync`` as a local, this test documents the correct shape.+ """+ # The holder pattern is the fix. Verify it is a mutable container.+ holder: list = [None]+ assert holder[0] is None+ holder[0] = "sentinel"+ assert holder[0] == "sentinel"+ # The outer scope must be able to read it without a NameError.+ # This is trivially true with a holder, but was NOT true when+ # the consumer was a run_sync local.+ _ = holder[0]diff --git a/tests/gateway/test_streaming_tts_gateway_regression.py b/tests/gateway/test_streaming_tts_gateway_regression.pynew file mode 100644index 00000000000..c1aec441b23--- /dev/null+++ b/tests/gateway/test_streaming_tts_gateway_regression.py@@ -0,0 +1,181 @@+"""Gateway regression: the outer finalisation path must not NameError on+the streaming-TTS consumer (#60671).++The original commit created ``_streaming_tts_consumer`` as a local inside+``run_sync`` (executor-thread) but the outer ``_run_agent_inner`` code+referenced it during interrupt/finalisation — a cross-scope ``NameError``+on ordinary gateway turns. The hardening moves the consumer into a+``streaming_tts_consumer_holder`` created on the event-loop thread.++This test exercises the real ``_run_agent`` → ``_run_agent_inner`` path+with a voice input message type so the streaming-TTS consumer setup+branch is entered. The fake agent returns synchronously, the executor+finishes, and the outer finalisation code runs — proving no NameError.+"""++import asyncio+import sys+import threading+import types+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++import gateway.run as gateway_run+from gateway.config import Platform+from gateway.platforms.base import MessageEvent, MessageType+from gateway.session import SessionSource+++class _NoopAgent:+ """Minimal agent stub that returns immediately without tool calls."""++ def __init__(self, *args, **kwargs):+ self.tools = []+ self.model = kwargs.get("model", "test-model")+ self.provider = kwargs.get("provider", "test-provider")+ self.session_id = kwargs.get("session_id", "session-1")+ self.context_compressor = None+ self.is_interrupted = False++ def run_conversation(self, user_message, conversation_history=None,+ task_id=None, persist_user_message=None,+ persist_user_timestamp=None):+ return {+ "final_response": "Hello from the agent.",+ "messages": [],+ "api_calls": 1,+ "completed": True,+ }+++def _install_fake_agent(monkeypatch):+ fake_run_agent = types.ModuleType("run_agent")+ fake_run_agent.AIAgent = _NoopAgent+ monkeypatch.setitem(sys.modules, "run_agent", fake_run_agent)+++def _make_runner():+ runner = object.__new__(gateway_run.GatewayRunner)+ runner.adapters = {}+ runner._ephemeral_system_prompt = ""+ runner._prefill_messages = []+ runner._reasoning_config = None+ runner._service_tier = None+ runner._provider_routing = {}+ runner._fallback_model = None+ runner._running_agents = {}+ runner._pending_model_notes = {}+ runner._session_db = None+ runner._agent_cache = {}+ runner._agent_cache_lock = threading.Lock()+ runner._session_model_overrides = {}+ runner.hooks = SimpleNamespace(loaded_hooks=False)+ runner.config = SimpleNamespace(streaming=None, multiplex_profiles=False)+ runner.session_store = SimpleNamespace(+ get_or_create_session=lambda source: SimpleNamespace(session_id="session-1"),+ load_transcript=lambda session_id: [],+ )+ runner._get_or_create_gateway_honcho = lambda session_key: (None, None)+ runner._enrich_message_with_vision = AsyncMock(return_value="ENRICHED")+ runner._gateway_loop = None+ return runner+++def _make_voice_source() -> SessionSource:+ return SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="12345",+ chat_type="dm",+ user_id="user-1",+ )+++def _setup_monkeypatches(monkeypatch, tmp_path):+ _install_fake_agent(monkeypatch)+ (tmp_path / "config.yaml").write_text("agent:\n model: test-model\n", encoding="utf-8")+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)+ monkeypatch.setattr(gateway_run, "_env_path", tmp_path / ".env")+ monkeypatch.setattr(gateway_run, "load_dotenv", lambda *args, **kwargs: None)+ monkeypatch.setattr(gateway_run, "_load_gateway_config", lambda: {})+ monkeypatch.setattr(+ gateway_run,+ "_load_gateway_runtime_config",+ lambda: {"agent": {"model": "test-model"}},+ )+ monkeypatch.setattr(gateway_run, "_resolve_gateway_model", lambda config=None: "test-model")+ monkeypatch.setattr(+ gateway_run,+ "_resolve_runtime_agent_kwargs",+ lambda: {+ "provider": "openrouter",+ "api_mode": "chat_completions",+ "base_url": "https://openrouter.ai/api/v1",+ "api_key": "***",+ },+ )++ import hermes_cli.tools_config as tools_config+ monkeypatch.setattr(tools_config, "_get_platform_tools", lambda user_config, platform_key: {"core"})+++def test_run_agent_voice_turn_no_name_error(monkeypatch, tmp_path):+ """A voice-input turn must complete without a _streaming_tts_consumer NameError.++ The streaming-TTS consumer setup is entered (voice input + auto-TTS),+ but since no adapter is configured the consumer setup is skipped. The+ outer finalisation path still runs and must not raise NameError when+ reading ``streaming_tts_consumer_holder``.+ """+ _setup_monkeypatches(monkeypatch, tmp_path)+ runner = _make_runner()++ # No adapter for this source → consumer setup skipped, but the outer+ # finalisation path still runs with streaming_tts_consumer_holder[0]=None.+ monkeypatch.setattr(+ gateway_run.GatewayRunner,+ "_adapter_for_source",+ lambda self, source: None,+ )++ async def _run():+ result = await runner._run_agent(+ message="Hello Jarvis",+ context_prompt="",+ history=[],+ source=_make_voice_source(),+ session_id="session-1",+ session_key="agent:main:telegram:dm:12345",+ message_type=MessageType.VOICE,+ )+ return result++ result = asyncio.new_event_loop().run_until_complete(_run())+ assert result["final_response"] == "Hello from the agent."+++def test_run_agent_text_turn_no_name_error(monkeypatch, tmp_path):+ """A text-input turn (no streaming TTS) must also complete cleanly."""+ _setup_monkeypatches(monkeypatch, tmp_path)+ runner = _make_runner()++ monkeypatch.setattr(+ gateway_run.GatewayRunner,+ "_adapter_for_source",+ lambda self, source: None,+ )++ async def _run():+ result = await runner._run_agent(+ message="Hello Jarvis",+ context_prompt="",+ history=[],+ source=_make_voice_source(),+ session_id="session-1",+ session_key="agent:main:telegram:dm:12345",+ )+ return result++ result = asyncio.new_event_loop().run_until_complete(_run())+ assert result["final_response"] == "Hello from the agent."\ No newline at end of file