diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index fc5fe4ffe23c..4dff1e456f0f 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -510,6 +510,18 @@ class ResultStream: """Get the future that returns the cache.""" return asyncio.Future() + @callback + def _async_mark_used(self) -> None: + """Keep the stream available now that its result is about to be used. + + A pipeline creates its stream when the run starts, for example before + waiting for a wake word, which can be longer ago than the memory cache + keeps an unused stream around. + """ + self.last_used = monotonic() + self._manager.token_to_stream[self.token] = self + self._manager.token_to_stream_cleanup.schedule() + @callback def async_set_message(self, message: str) -> None: """Set message to be generated. @@ -518,6 +530,7 @@ class ResultStream: """ if self._result_cache.done(): return + self._async_mark_used() self._result_cache.set_result( self._manager.async_cache_message_in_memory( engine=self.engine, @@ -536,6 +549,7 @@ class ResultStream: """ if self._result_cache.done(): return + self._async_mark_used() self._result_cache.set_result( self._manager.async_cache_message_stream_in_memory( engine=self.engine, @@ -563,6 +577,7 @@ class ResultStream: def async_override_result(self, media_path: str | Path) -> None: """Override the TTS stream with a different media path.""" + self._async_mark_used() self._override_media_path = Path(media_path) @property diff --git a/tests/components/tts/test_init.py b/tests/components/tts/test_init.py index 3382c63f69b0..32f665268bb5 100644 --- a/tests/components/tts/test_init.py +++ b/tests/components/tts/test_init.py @@ -1,7 +1,7 @@ """The tests for the TTS component.""" import asyncio -from collections.abc import AsyncGenerator +from collections.abc import AsyncGenerator, Callable from http import HTTPStatus import io from pathlib import Path @@ -25,6 +25,7 @@ from homeassistant.components.media_player import ( MediaType, ) from homeassistant.components.tts import DOMAIN +from homeassistant.components.tts.const import DEFAULT_TIME_MEMORY from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN from homeassistant.core import HomeAssistant @@ -48,6 +49,7 @@ from .common import ( from tests.common import ( MockModule, + async_fire_time_changed, async_mock_service, load_fixture_bytes, mock_integration, @@ -2084,6 +2086,66 @@ async def test_stream(hass: HomeAssistant, mock_tts_entity: MockTTSEntity) -> No assert result_data == data +async def _message_stream() -> AsyncGenerator[str]: + """Stream a message.""" + yield "beer" + + +@pytest.mark.parametrize( + "set_message", + [ + pytest.param(lambda stream: stream.async_set_message("beer"), id="message"), + pytest.param( + lambda stream: stream.async_set_message_stream(_message_stream()), + id="message_stream", + ), + ], +) +async def test_stream_set_message_after_memory_cache_age( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_tts_entity: MockTTSEntity, + set_message: Callable[[tts.ResultStream], None], +) -> None: + """Test a stream created long before its message is set can still be fetched. + + A pipeline creates its stream when the run starts, for example before + waiting for the wake word, which can be long before the message is known. + """ + await mock_config_entry_setup(hass, mock_tts_entity) + stream = tts.async_create_stream(hass, mock_tts_entity.entity_id) + + freezer.tick(DEFAULT_TIME_MEMORY + 2) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + set_message(stream) + + assert tts.async_get_stream(hass, stream.token) is stream + result_data = b"".join([chunk async for chunk in stream.async_stream_result()]) + assert result_data + + +async def test_stream_override_result_after_memory_cache_age( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_tts_entity: MockTTSEntity, + tmp_path: Path, +) -> None: + """Test a stream overridden long after it was created can still be fetched.""" + await mock_config_entry_setup(hass, mock_tts_entity) + stream = tts.async_create_stream(hass, mock_tts_entity.entity_id) + + freezer.tick(DEFAULT_TIME_MEMORY + 2) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + # The Assist pipeline overrides the result for its local acknowledgment + stream.async_override_result(tmp_path / "acknowledge.mp3") + + assert tts.async_get_stream(hass, stream.token) is stream + + async def test_result_stream_message_set_idempotent( hass: HomeAssistant, mock_tts_entity: MockTTSEntity ) -> None: