From b2f8b6b57735860517a97fc6fd6084d3707e72fc Mon Sep 17 00:00:00 2001 From: Michael Hansen Date: Fri, 20 Nov 2026 23:33:20 -0600 Subject: [PATCH] Use timer list entities for voice timers (#193493) Co-authored-by: Claude Opus 5.5 Co-authored-by: Paulus Schoutsen --- homeassistant/components/intent/timers.py | 462 ++++++--- .../components/timer_list/__init__.py | 9 + .../conversation/test_default_agent.py | 2 + tests/components/intent/test_llm.py | 2 + tests/components/intent/test_timer_lists.py | 923 ++++++++++++++++++ tests/components/intent/test_timers.py | 32 +- tests/helpers/test_llm.py | 2 + 7 files changed, 1259 insertions(+), 173 deletions(-) create mode 100644 tests/components/intent/test_timer_lists.py diff --git a/homeassistant/components/intent/timers.py b/homeassistant/components/intent/timers.py index f0bdaa7dc727..e38cee166398 100644 --- a/homeassistant/components/intent/timers.py +++ b/homeassistant/components/intent/timers.py @@ -3,6 +3,7 @@ import asyncio from collections.abc import Callable from dataclasses import dataclass +from datetime import datetime, timedelta from enum import StrEnum import logging import time @@ -11,15 +12,30 @@ from typing import Any, override import probatio from propcache.api import cached_property +from homeassistant.auth.permissions import AbstractPermissions +from homeassistant.auth.permissions.const import ( + CAT_ENTITIES, + POLICY_CONTROL, + POLICY_READ, +) +from homeassistant.components.timer_list import ( + DOMAIN as TIMER_LIST_DOMAIN, + TimerItem, + TimerListEntity, + TimerStatus, + async_get_timer_list_entity, +) from homeassistant.const import ATTR_DEVICE_ID, ATTR_ID, ATTR_NAME from homeassistant.core import Context, HomeAssistant, callback +from homeassistant.exceptions import Unauthorized, UnknownUser from homeassistant.helpers import ( area_registry as ar, config_validation as cv, device_registry as dr, + entity_registry as er, intent, ) -from homeassistant.util import ulid as ulid_util +from homeassistant.util import dt as dt_util, ulid as ulid_util from .const import TIMER_DATA @@ -161,6 +177,25 @@ class TimerInfo: self.updated_at = time.monotonic_ns() self.is_active = False + def to_timer_item(self, now: datetime, monotonic_now: int) -> TimerItem: + """Snapshot a legacy timer using UTC timestamps.""" + remaining = timedelta(seconds=self.seconds_left) + return TimerItem( + timer_id=self.id, + name=self.name, + status=TimerStatus.ACTIVE if self.is_active else TimerStatus.PAUSED, + created_duration=timedelta( + hours=self.start_hours or 0, + minutes=self.start_minutes or 0, + seconds=self.start_seconds or 0, + ), + created_at=now + - timedelta(microseconds=(monotonic_now - self.created_at) // 1000), + total_duration=timedelta(seconds=self.created_seconds), + finishes_at=now + remaining if self.is_active else None, + paused_remaining=remaining if not self.is_active else None, + ) + class TimerEventType(StrEnum): """Event type in timer handler.""" @@ -343,7 +378,7 @@ class TimerManager: except asyncio.CancelledError: pass # expected when timer is updated - def cancel_timer(self, timer_id: str) -> None: + async def async_cancel_timer(self, timer_id: str) -> None: """Cancel a timer.""" timer = self.timers.pop(timer_id, None) if timer is None: @@ -365,12 +400,13 @@ class TimerManager: timer.device_id, ) - def add_time(self, timer_id: str, seconds: int) -> None: - """Add time to a timer.""" + async def async_add_time(self, timer_id: str, duration: timedelta) -> None: + """Add time to a timer, or remove it if duration is negative.""" timer = self.timers.get(timer_id) if timer is None: raise TimerNotFoundError + seconds = round(duration.total_seconds()) if seconds == 0: # Don't bother cancelling and recreating the timer task return @@ -404,11 +440,7 @@ class TimerManager: timer.device_id, ) - def remove_time(self, timer_id: str, seconds: int) -> None: - """Remove time from a timer.""" - self.add_time(timer_id, -seconds) - - def pause_timer(self, timer_id: str) -> None: + async def async_pause_timer(self, timer_id: str) -> None: """Pauses a timer.""" timer = self.timers.get(timer_id) if timer is None: @@ -432,7 +464,7 @@ class TimerManager: timer.device_id, ) - def unpause_timer(self, timer_id: str) -> None: + async def async_unpause_timer(self, timer_id: str) -> None: """Unpause a timer.""" timer = self.timers.get(timer_id) if timer is None: @@ -515,11 +547,25 @@ class TimerManager: @callback def async_device_supports_timers(hass: HomeAssistant, device_id: str) -> bool: - """Return True if device has been registered to handle timer events.""" + """Return True if a device has a timer list or handles timer events.""" timer_manager: TimerManager | None = hass.data.get(TIMER_DATA) if timer_manager is None: return False - return timer_manager.is_timer_device(device_id) + return timer_manager.is_timer_device(device_id) or bool( + _async_get_device_timer_list_entity_ids(hass, device_id) + ) + + +@callback +def _async_get_device_timer_list_entity_ids( + hass: HomeAssistant, device_id: str +) -> list[str]: + """Find a device's enabled timer lists in the entity registry.""" + return [ + entry.entity_id + for entry in er.async_entries_for_device(er.async_get(hass), device_id) + if entry.domain == TIMER_LIST_DOMAIN + ] @callback @@ -537,35 +583,182 @@ def async_register_timer_handler( # ----------------------------------------------------------------------------- -class FindTimerFilter(StrEnum): - """Type of filter to apply when finding a timer.""" +@dataclass(frozen=True, kw_only=True) +class _VoiceTimer: + """A timer that voice commands can act on. - ONLY_ACTIVE = "only_active" - ONLY_INACTIVE = "only_inactive" + The timer lives in a timer list entity or, for a device that registered a + timer handler instead, in the timer manager. + """ + + item: TimerItem + device_id: str | None + area_id: str | None + area_name: str | None + """Normalized name of the area.""" + floor_id: str | None + language: str + owner: TimerManager | TimerListEntity + + @property + def name_normalized(self) -> str: + """Return normalized timer name.""" + return _normalize_name(self.item.name or "") + + def as_speech_dict(self, now: datetime) -> dict[str, Any]: + """Format timer status for a voice response.""" + item = self.item + total_seconds = round(item.remaining_at(now).total_seconds()) + if isinstance(self.owner, TimerManager): + # Preserve the units used to start legacy timers. + legacy_timer = self.owner.timers[item.timer_id] + start_hours = legacy_timer.start_hours or 0 + start_minutes = legacy_timer.start_minutes or 0 + start_seconds = legacy_timer.start_seconds or 0 + else: + start_minutes, start_seconds = divmod( + round(item.created_duration.total_seconds()), 60 + ) + start_hours, start_minutes = divmod(start_minutes, 60) + + minutes, seconds = divmod(total_seconds, 60) + hours, minutes = divmod(minutes, 60) + + # Get lower-precision time for feedback + rounded_hours, rounded_minutes, rounded_seconds = _round_time( + hours, minutes, seconds + ) + + return { + ATTR_ID: item.timer_id, + ATTR_NAME: item.name or "", + ATTR_DEVICE_ID: self.device_id or "", + "language": self.language, + "start_hours": start_hours, + "start_minutes": start_minutes, + "start_seconds": start_seconds, + "is_active": item.status == TimerStatus.ACTIVE, + "hours_left": hours, + "minutes_left": minutes, + "seconds_left": seconds, + "rounded_hours_left": rounded_hours, + "rounded_minutes_left": rounded_minutes, + "rounded_seconds_left": rounded_seconds, + "total_seconds_left": total_seconds, + } + + async def async_cancel(self) -> None: + """Cancel the timer.""" + await self.owner.async_cancel_timer(self.item.timer_id) + + async def async_add_time(self, seconds: int) -> None: + """Add time to a timer, or remove it if seconds is negative.""" + await self.owner.async_add_time(self.item.timer_id, timedelta(seconds=seconds)) + + async def async_pause(self) -> None: + """Pause the timer.""" + await self.owner.async_pause_timer(self.item.timer_id) + + async def async_unpause(self) -> None: + """Unpause the timer.""" + await self.owner.async_unpause_timer(self.item.timer_id) -def _find_timer( - hass: HomeAssistant, - device_id: str | None, - slots: dict[str, Any], - find_filter: FindTimerFilter | None = None, -) -> TimerInfo: - """Match a single timer with constraints or raise an error.""" +async def _async_get_user_permissions( + intent_obj: intent.Intent, +) -> AbstractPermissions | None: + """Return the caller's permissions, if the intent has a user context.""" + if not (user_id := intent_obj.context.user_id): + return None + if (user := await intent_obj.hass.auth.async_get_user(user_id)) is None: + raise UnknownUser(context=intent_obj.context, user_id=user_id) + return user.permissions + + +async def _async_get_voice_timers( + intent_obj: intent.Intent, permission: str +) -> list[_VoiceTimer]: + """Return active and paused timers accessible to the caller.""" + hass = intent_obj.hass + permissions = await _async_get_user_permissions(intent_obj) timer_manager: TimerManager = hass.data[TIMER_DATA] - - # Ignore delayed command timers - matching_timers: list[TimerInfo] = [ - t for t in timer_manager.timers.values() if not t.conversation_command + now = dt_util.utcnow() + monotonic_now = time.monotonic_ns() + timers = [ + _VoiceTimer( + item=timer.to_timer_item(now, monotonic_now), + owner=timer_manager, + device_id=timer.device_id, + area_id=timer.area_id, + area_name=timer.area_name, + floor_id=timer.floor_id, + language=timer.language, + ) + for timer in timer_manager.timers.values() + if not timer.conversation_command ] + + for entry in er.async_get(hass).entities.values(): + if ( + entry.domain == TIMER_LIST_DOMAIN + and not entry.disabled + and ( + permissions is None + or permissions.check_entity(entry.entity_id, permission) + ) + ): + timers.extend( + _async_get_timer_list_voice_timers(hass, entry, intent_obj.language) + ) + + return timers + + +@callback +def _async_get_timer_list_voice_timers( + hass: HomeAssistant, entity_entry: er.RegistryEntry, language: str +) -> list[_VoiceTimer]: + """Return the active and paused timers of a timer list.""" + area_id = er.async_get_effective_area_id(hass, entity_entry) + + area_name: str | None = None + floor_id: str | None = None + if area_id and (area := ar.async_get(hass).async_get_area(area_id)): + area_name = _normalize_name(area.name) + floor_id = area.floor_id + + if (entity := async_get_timer_list_entity(hass, entity_entry.entity_id)) is None: + return [] + + return [ + _VoiceTimer( + item=item, + owner=entity, + device_id=entity_entry.device_id, + area_id=area_id, + area_name=area_name, + floor_id=floor_id, + language=language, + ) + for item in entity.timers + if item.status in (TimerStatus.ACTIVE, TimerStatus.PAUSED) + ] + + +async def _async_find_timer( + intent_obj: intent.Intent, + slots: dict[str, Any], + status: TimerStatus | None = None, +) -> _VoiceTimer: + """Match a single timer with constraints or raise an error.""" + hass = intent_obj.hass + device_id = intent_obj.device_id + matching_timers = await _async_get_voice_timers(intent_obj, POLICY_CONTROL) has_filter = False - if find_filter: - # Filter by active state + if status is not None: has_filter = True - if find_filter == FindTimerFilter.ONLY_ACTIVE: - matching_timers = [t for t in matching_timers if t.is_active] - elif find_filter == FindTimerFilter.ONLY_INACTIVE: - matching_timers = [t for t in matching_timers if not t.is_active] + matching_timers = [t for t in matching_timers if t.item.status == status] if len(matching_timers) == 1: # Only 1 match @@ -598,30 +791,14 @@ def _find_timer( return matching_timers[0] # Use starting time to disambiguate - start_hours: int | None = None - if "start_hours" in slots: - start_hours = int(slots["start_hours"]["value"]) - - start_minutes: int | None = None - if "start_minutes" in slots: - start_minutes = int(slots["start_minutes"]["value"]) - - start_seconds: int | None = None - if "start_seconds" in slots: - start_seconds = int(slots["start_seconds"]["value"]) - - if ( - (start_hours is not None) - or (start_minutes is not None) - or (start_seconds is not None) - ): + start_total_seconds: int | None = None + if _has_start_time(slots): has_filter = True + start_total_seconds = _get_total_seconds(slots, "start_") matching_timers = [ t for t in matching_timers - if (t.start_hours == start_hours) - and (t.start_minutes == start_minutes) - and (t.start_seconds == start_seconds) + if round(t.item.created_duration.total_seconds()) == start_total_seconds ] if len(matching_timers) == 1: @@ -669,29 +846,23 @@ def _find_timer( raise MultipleTimersMatchedError _LOGGER.warning( - "Timer not found: name=%s, area=%s, hours=%s," - " minutes=%s, seconds=%s, device_id=%s", + "Timer not found: name=%s, area=%s, start_seconds=%s, device_id=%s", name, area_name, - start_hours, - start_minutes, - start_seconds, + start_total_seconds, device_id, ) raise TimerNotFoundError -def _find_timers( - hass: HomeAssistant, device_id: str | None, slots: dict[str, Any] -) -> list[TimerInfo]: +async def _async_find_timers( + intent_obj: intent.Intent, slots: dict[str, Any], permission: str +) -> list[_VoiceTimer]: """Match multiple timers with constraints or raise an error.""" - timer_manager: TimerManager = hass.data[TIMER_DATA] - - # Ignore delayed command timers - matching_timers: list[TimerInfo] = [ - t for t in timer_manager.timers.values() if not t.conversation_command - ] + hass = intent_obj.hass + device_id = intent_obj.device_id + matching_timers = await _async_get_voice_timers(intent_obj, permission) # Filter by name first name: str | None = None @@ -718,29 +889,12 @@ def _find_timers( return matching_timers # Use starting time to filter, if present - start_hours: int | None = None - if "start_hours" in slots: - start_hours = int(slots["start_hours"]["value"]) - - start_minutes: int | None = None - if "start_minutes" in slots: - start_minutes = int(slots["start_minutes"]["value"]) - - start_seconds: int | None = None - if "start_seconds" in slots: - start_seconds = int(slots["start_seconds"]["value"]) - - if ( - (start_hours is not None) - or (start_minutes is not None) - or (start_seconds is not None) - ): + if _has_start_time(slots): + start_total_seconds = _get_total_seconds(slots, "start_") matching_timers = [ t for t in matching_timers - if (t.start_hours == start_hours) - and (t.start_minutes == start_minutes) - and (t.start_seconds == start_seconds) + if round(t.item.created_duration.total_seconds()) == start_total_seconds ] if not matching_timers: # No matches @@ -764,7 +918,7 @@ def _find_timers( if area is None: return matching_timers - def area_floor_sort(timer: TimerInfo) -> int: + def area_floor_sort(timer: _VoiceTimer) -> int: """Sort by area, then floor.""" if timer.area_id == area.id: return -2 @@ -784,17 +938,24 @@ def _normalize_name(name: str) -> str: return name.strip().casefold() -def _get_total_seconds(slots: dict[str, Any]) -> int: +def _has_start_time(slots: dict[str, Any]) -> bool: + """Return True if the slots name the duration a timer was started with.""" + return any( + key in slots for key in ("start_hours", "start_minutes", "start_seconds") + ) + + +def _get_total_seconds(slots: dict[str, Any], prefix: str = "") -> int: """Return the total number of seconds from hours/minutes/seconds slots.""" total_seconds = 0 - if "hours" in slots: - total_seconds += 60 * 60 * int(slots["hours"]["value"]) + if f"{prefix}hours" in slots: + total_seconds += 60 * 60 * int(slots[f"{prefix}hours"]["value"]) - if "minutes" in slots: - total_seconds += 60 * int(slots["minutes"]["value"]) + if f"{prefix}minutes" in slots: + total_seconds += 60 * int(slots[f"{prefix}minutes"]["value"]) - if "seconds" in slots: - total_seconds += int(slots["seconds"]["value"]) + if f"{prefix}seconds" in slots: + total_seconds += int(slots[f"{prefix}seconds"]["value"]) return total_seconds @@ -870,8 +1031,20 @@ class StartTimerIntentHandler(intent.IntentHandler): if "conversation_command" in slots: conversation_command = slots["conversation_command"]["value"].strip() - if (not conversation_command) and ( - not ( + timer_list: TimerListEntity | None = None + if intent_obj.device_id: + for entity_id in _async_get_device_timer_list_entity_ids( + hass, intent_obj.device_id + ): + if ( + timer_list := async_get_timer_list_entity(hass, entity_id) + ) is not None: + break + + if ( + (not conversation_command) + and (timer_list is None) + and not ( intent_obj.device_id and timer_manager.is_timer_device(intent_obj.device_id) ) @@ -901,6 +1074,22 @@ class StartTimerIntentHandler(intent.IntentHandler): if "seconds" in slots: seconds = int(slots["seconds"]["value"]) + if (not conversation_command) and (timer_list is not None): + permissions = await _async_get_user_permissions(intent_obj) + if permissions is not None and not permissions.check_entity( + timer_list.entity_id, POLICY_CONTROL + ): + raise Unauthorized( + context=intent_obj.context, + entity_id=timer_list.entity_id, + permission=POLICY_CONTROL, + perm_category=CAT_ENTITIES, + ) + await timer_list.async_create_timer( + name=name, duration=timedelta(seconds=_get_total_seconds(slots)) + ) + return intent_obj.create_response() + timer_manager.start_timer( intent_obj.device_id, hours, @@ -972,12 +1161,10 @@ class CancelTimerIntentHandler(intent.IntentHandler): @override async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse: """Handle the intent.""" - hass = intent_obj.hass - timer_manager: TimerManager = hass.data[TIMER_DATA] slots = self.async_validate_slots(intent_obj.slots) - timer = _find_timer(hass, intent_obj.device_id, slots) - timer_manager.cancel_timer(timer.id) + timer = await _async_find_timer(intent_obj, slots) + await timer.async_cancel() return intent_obj.create_response() @@ -993,13 +1180,11 @@ class CancelAllTimersIntentHandler(intent.IntentHandler): @override async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse: """Handle the intent.""" - hass = intent_obj.hass - timer_manager: TimerManager = hass.data[TIMER_DATA] slots = self.async_validate_slots(intent_obj.slots) canceled = 0 - for timer in _find_timers(hass, intent_obj.device_id, slots): - timer_manager.cancel_timer(timer.id) + for timer in await _async_find_timers(intent_obj, slots, POLICY_CONTROL): + await timer.async_cancel() canceled += 1 response = intent_obj.create_response() @@ -1027,13 +1212,11 @@ class IncreaseTimerIntentHandler(intent.IntentHandler): @override async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse: """Handle the intent.""" - hass = intent_obj.hass - timer_manager: TimerManager = hass.data[TIMER_DATA] slots = self.async_validate_slots(intent_obj.slots) total_seconds = _get_total_seconds(slots) - timer = _find_timer(hass, intent_obj.device_id, slots) - timer_manager.add_time(timer.id, total_seconds) + timer = await _async_find_timer(intent_obj, slots) + await timer.async_add_time(total_seconds) return intent_obj.create_response() @@ -1052,13 +1235,11 @@ class DecreaseTimerIntentHandler(intent.IntentHandler): @override async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse: """Handle the intent.""" - hass = intent_obj.hass - timer_manager: TimerManager = hass.data[TIMER_DATA] slots = self.async_validate_slots(intent_obj.slots) total_seconds = _get_total_seconds(slots) - timer = _find_timer(hass, intent_obj.device_id, slots) - timer_manager.remove_time(timer.id, total_seconds) + timer = await _async_find_timer(intent_obj, slots) + await timer.async_add_time(-total_seconds) return intent_obj.create_response() @@ -1076,14 +1257,10 @@ class PauseTimerIntentHandler(intent.IntentHandler): @override async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse: """Handle the intent.""" - hass = intent_obj.hass - timer_manager: TimerManager = hass.data[TIMER_DATA] slots = self.async_validate_slots(intent_obj.slots) - timer = _find_timer( - hass, intent_obj.device_id, slots, find_filter=FindTimerFilter.ONLY_ACTIVE - ) - timer_manager.pause_timer(timer.id) + timer = await _async_find_timer(intent_obj, slots, status=TimerStatus.ACTIVE) + await timer.async_pause() return intent_obj.create_response() @@ -1101,14 +1278,10 @@ class UnpauseTimerIntentHandler(intent.IntentHandler): @override async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse: """Handle the intent.""" - hass = intent_obj.hass - timer_manager: TimerManager = hass.data[TIMER_DATA] slots = self.async_validate_slots(intent_obj.slots) - timer = _find_timer( - hass, intent_obj.device_id, slots, find_filter=FindTimerFilter.ONLY_INACTIVE - ) - timer_manager.unpause_timer(timer.id) + timer = await _async_find_timer(intent_obj, slots, status=TimerStatus.PAUSED) + await timer.async_unpause() return intent_obj.create_response() @@ -1126,42 +1299,13 @@ class TimerStatusIntentHandler(intent.IntentHandler): @override async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse: """Handle the intent.""" - hass = intent_obj.hass slots = self.async_validate_slots(intent_obj.slots) - statuses: list[dict[str, Any]] = [] - for timer in _find_timers(hass, intent_obj.device_id, slots): - total_seconds = timer.seconds_left - - minutes, seconds = divmod(total_seconds, 60) - hours, minutes = divmod(minutes, 60) - - # Get lower-precision time for feedback - rounded_hours, rounded_minutes, rounded_seconds = _round_time( - hours, minutes, seconds - ) - - statuses.append( - { - ATTR_ID: timer.id, - ATTR_NAME: timer.name or "", - ATTR_DEVICE_ID: timer.device_id or "", - "language": timer.language, - "start_hours": timer.start_hours or 0, - "start_minutes": timer.start_minutes or 0, - "start_seconds": timer.start_seconds or 0, - "is_active": timer.is_active, - "hours_left": hours, - "minutes_left": minutes, - "seconds_left": seconds, - "rounded_hours_left": rounded_hours, - "rounded_minutes_left": rounded_minutes, - "rounded_seconds_left": rounded_seconds, - "total_seconds_left": total_seconds, - } - ) - + timers = await _async_find_timers(intent_obj, slots, POLICY_READ) + now = dt_util.utcnow() response = intent_obj.create_response() - response.async_set_speech_slots({"timers": statuses}) + response.async_set_speech_slots( + {"timers": [timer.as_speech_dict(now) for timer in timers]} + ) return response diff --git a/homeassistant/components/timer_list/__init__.py b/homeassistant/components/timer_list/__init__.py index 4bdd2e31258e..c563f6e16ffb 100644 --- a/homeassistant/components/timer_list/__init__.py +++ b/homeassistant/components/timer_list/__init__.py @@ -50,6 +50,7 @@ __all__ = [ "TimerListEventType", "TimerListServices", "TimerStatus", + "async_get_timer_list_entity", ] _LOGGER = logging.getLogger(__name__) @@ -74,6 +75,14 @@ def entity_became_available(event: Event[EventStateChangedData]) -> bool: return old_state is None or old_state.state == STATE_UNAVAILABLE +@callback +def async_get_timer_list_entity( + hass: HomeAssistant, entity_id: str +) -> TimerListEntity | None: + """Return the timer list entity for an entity ID.""" + return hass.data[DATA_COMPONENT].get_entity(entity_id) + + async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Timer list component.""" component = hass.data[DATA_COMPONENT] = EntityComponent[TimerListEntity]( diff --git a/tests/components/conversation/test_default_agent.py b/tests/components/conversation/test_default_agent.py index 352a14358bae..cc096c7751ff 100644 --- a/tests/components/conversation/test_default_agent.py +++ b/tests/components/conversation/test_default_agent.py @@ -50,6 +50,7 @@ from homeassistant.components.intent import ( async_register_timer_handler, ) from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN +from homeassistant.components.timer_list import DOMAIN as TIMER_LIST_DOMAIN from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, @@ -98,6 +99,7 @@ class OrderBeerIntentHandler(intent.IntentHandler): async def init_components(hass: HomeAssistant) -> None: """Initialize relevant components with empty configs.""" assert await async_setup_component(hass, "homeassistant", {}) + assert await async_setup_component(hass, TIMER_LIST_DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {}) assert await async_setup_component(hass, "intent", {}) diff --git a/tests/components/intent/test_llm.py b/tests/components/intent/test_llm.py index a3f3e677a490..48aeaa0af622 100644 --- a/tests/components/intent/test_llm.py +++ b/tests/components/intent/test_llm.py @@ -14,6 +14,7 @@ from homeassistant.components.intent import llm as intent_llm from homeassistant.components.intent.timers import async_register_timer_handler from homeassistant.components.media_player import MediaPlayerDeviceClass from homeassistant.components.switch import SwitchDeviceClass +from homeassistant.components.timer_list import DOMAIN as TIMER_LIST_DOMAIN from homeassistant.components.valve import ValveDeviceClass from homeassistant.const import SERVICE_TURN_ON from homeassistant.core import Context, HomeAssistant, callback @@ -28,6 +29,7 @@ LLM_AGENT_ID = "conversation.test_llm_agent" async def setup_integrations(hass: HomeAssistant) -> None: """Set up the integrations and expose a cover.""" assert await async_setup_component(hass, "homeassistant", {}) + assert await async_setup_component(hass, TIMER_LIST_DOMAIN, {}) assert await async_setup_component(hass, "intent", {}) assert await async_setup_component(hass, "llm", {}) hass.states.async_set(COVER_ENTITY_ID, "open", {"friendly_name": "Test Cover"}) diff --git a/tests/components/intent/test_timer_lists.py b/tests/components/intent/test_timer_lists.py new file mode 100644 index 000000000000..17033c408a27 --- /dev/null +++ b/tests/components/intent/test_timer_lists.py @@ -0,0 +1,923 @@ +"""Tests for intent timers kept in timer list entities.""" + +from collections.abc import Generator, Iterable +from copy import deepcopy +from dataclasses import dataclass +from datetime import timedelta +from typing import Any +from unittest.mock import Mock + +from freezegun.api import FrozenDateTimeFactory +import pytest +from pytest_homeassistant.common import ( + MockConfigEntry, + MockModule, + MockPlatform, + MockUser, + mock_config_flow, + mock_integration, + mock_platform, +) + +from homeassistant.auth.permissions.const import POLICY_CONTROL, POLICY_READ +from homeassistant.components.intent import ( + DOMAIN, + TimerEventType, + TimerInfo, + async_device_supports_timers, + async_register_timer_handler, +) +from homeassistant.components.intent.timers import ( + TIMER_DATA, + MultipleTimersMatchedError, + TimerManager, + TimerNotFoundError, +) +from homeassistant.components.timer_list import ( + DOMAIN as TIMER_LIST_DOMAIN, + InMemoryTimerListEntity, + TimerListEntity, + TimerStatus, +) +from homeassistant.config_entries import ConfigEntry, ConfigFlow +from homeassistant.const import Platform +from homeassistant.core import Context, HomeAssistant, callback +from homeassistant.exceptions import Unauthorized, UnknownUser +from homeassistant.helpers import ( + area_registry as ar, + device_registry as dr, + entity_registry as er, + floor_registry as fr, + intent, +) +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.setup import async_setup_component + +TEST_DOMAIN = "test" +KITCHEN = "kitchen" +LIVING_ROOM = "living_room" +BEDROOM = "bedroom" + + +class DeviceTimerList(InMemoryTimerListEntity): + """Timer list of a test device.""" + + _attr_has_entity_name = True + _attr_name = "Timers" + + def __init__(self, device: str) -> None: + """Initialize the timer list.""" + super().__init__() + self._attr_unique_id = f"{device}-timers" + self._attr_device_info = DeviceInfo( + identifiers={(TEST_DOMAIN, device)}, name=device + ) + + +@dataclass +class TimerDevice: + """A test device and its timer list.""" + + device_id: str + timer_list: TimerListEntity + + +class MockFlow(ConfigFlow): + """Config flow of the test integration.""" + + +@pytest.fixture(autouse=True) +def config_flow_fixture(hass: HomeAssistant) -> Generator[None]: + """Mock the config flow of the test integration.""" + mock_platform(hass, f"{TEST_DOMAIN}.config_flow") + with mock_config_flow(TEST_DOMAIN, MockFlow): + yield + + +async def _async_setup_timer_lists( + hass: HomeAssistant, timer_lists: Iterable[TimerListEntity] +) -> None: + """Set up a test integration providing timer lists.""" + + async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + await hass.config_entries.async_forward_entry_setups( + entry, [Platform.TIMER_LIST] + ) + + async def async_setup_entry_platform( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, + ) -> None: + async_add_entities(timer_lists) + + mock_integration(hass, MockModule(TEST_DOMAIN, async_setup_entry=async_setup_entry)) + mock_platform( + hass, + f"{TEST_DOMAIN}.{Platform.TIMER_LIST}", + MockPlatform(async_setup_entry=async_setup_entry_platform), + ) + entry = MockConfigEntry(domain=TEST_DOMAIN) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + +@pytest.fixture +async def init_components(hass: HomeAssistant) -> None: + """Initialize required components for tests.""" + assert await async_setup_component(hass, "homeassistant", {}) + assert await async_setup_component(hass, TIMER_LIST_DOMAIN, {}) + assert await async_setup_component(hass, "conversation", {}) + assert await async_setup_component(hass, DOMAIN, {}) + + +@pytest.fixture +async def devices( + hass: HomeAssistant, + init_components: None, + area_registry: ar.AreaRegistry, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + floor_registry: fr.FloorRegistry, +) -> dict[str, TimerDevice]: + """Set up kitchen and living room devices with a timer list each. + + The kitchen and living room are on the first floor. + """ + timer_lists = { + KITCHEN: DeviceTimerList(KITCHEN), + LIVING_ROOM: DeviceTimerList(LIVING_ROOM), + } + await _async_setup_timer_lists(hass, timer_lists.values()) + + floor = floor_registry.async_create("First floor") + devices: dict[str, TimerDevice] = {} + for name, timer_list in timer_lists.items(): + area = area_registry.async_create( + name.replace("_", " "), floor_id=floor.floor_id + ) + entity_entry = entity_registry.async_get(timer_list.entity_id) + assert entity_entry is not None + assert entity_entry.device_id is not None + device_registry.async_update_device(entity_entry.device_id, area_id=area.id) + devices[name] = TimerDevice(entity_entry.device_id, timer_list) + + return devices + + +async def _handle( + hass: HomeAssistant, + intent_type: str, + device_id: str | None, + *, + context: Context | None = None, + **slots: Any, +) -> intent.IntentResponse: + """Handle a timer intent from a device.""" + return await intent.async_handle( + hass, + "test", + intent_type, + {name: {"value": value} for name, value in slots.items()}, + device_id=device_id, + context=context, + ) + + +async def _create_timer( + timer_device: TimerDevice, *, minutes: int = 5, name: str | None = None +) -> str: + """Create a timer directly on a device's timer list.""" + return await timer_device.timer_list.async_create_timer( + name=name, duration=timedelta(minutes=minutes) + ) + + +def _statuses(timer_device: TimerDevice) -> list[TimerStatus]: + """Return the status of each timer on a device.""" + return [timer.status for timer in timer_device.timer_list.timers] + + +async def test_start_timer( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test a timer is created on the timer list of the requesting device.""" + kitchen = devices[KITCHEN] + + result = await _handle( + hass, + intent.INTENT_START_TIMER, + kitchen.device_id, + name="pizza", + minutes=1, + seconds=30, + ) + + assert result.response_type is intent.IntentResponseType.ACTION_DONE + timers = kitchen.timer_list.timers + assert len(timers) == 1 + assert timers[0].name == "pizza" + assert timers[0].created_duration == timedelta(seconds=90) + assert devices[LIVING_ROOM].timer_list.timers == [] + assert not hass.data[TIMER_DATA].timers + + +async def test_delayed_command_uses_timer_manager( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test a delayed command is not added to the device's timer list.""" + kitchen = devices[KITCHEN] + + result = await _handle( + hass, + intent.INTENT_START_TIMER, + kitchen.device_id, + minutes=5, + conversation_command="what time is it", + ) + + assert result.response_type is intent.IntentResponseType.ACTION_DONE + assert kitchen.timer_list.timers == [] + timer_manager: TimerManager = hass.data[TIMER_DATA] + assert [timer.device_id for timer in timer_manager.timers.values()] == [ + kitchen.device_id + ] + + +async def test_timer_list_preferred_over_handler( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test a device with a timer list does not use its timer handler.""" + kitchen = devices[KITCHEN] + events: list[TimerEventType] = [] + + @callback + def handle_timer(event_type: TimerEventType, timer: TimerInfo) -> None: + events.append(event_type) + + async_register_timer_handler(hass, kitchen.device_id, handle_timer) + + await _handle(hass, intent.INTENT_START_TIMER, kitchen.device_id, minutes=5) + + assert events == [] + assert len(kitchen.timer_list.timers) == 1 + assert not hass.data[TIMER_DATA].timers + + +async def test_cancel_timer( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test cancelling the only timer, from another device.""" + kitchen = devices[KITCHEN] + await _create_timer(kitchen) + + await _handle(hass, intent.INTENT_CANCEL_TIMER, devices[LIVING_ROOM].device_id) + + assert _statuses(kitchen) == [TimerStatus.CANCELLED] + + +@pytest.mark.parametrize( + ("slots", "expected_kitchen", "expected_living_room"), + [ + pytest.param( + {"area": "Kitchen"}, + [TimerStatus.CANCELLED], + [TimerStatus.ACTIVE], + id="area", + ), + pytest.param( + {"start_minutes": 5}, + [TimerStatus.CANCELLED], + [TimerStatus.ACTIVE], + id="start_time", + ), + pytest.param( + {"start_seconds": 600}, + [TimerStatus.ACTIVE], + [TimerStatus.CANCELLED], + id="start_time_in_other_units", + ), + pytest.param( + {"name": "Pizza"}, + [TimerStatus.CANCELLED], + [TimerStatus.ACTIVE], + id="name", + ), + ], +) +async def test_cancel_timer_on_other_device( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + slots: dict[str, Any], + expected_kitchen: list[TimerStatus], + expected_living_room: list[TimerStatus], +) -> None: + """Test a timer on any device can be cancelled by area, start time or name.""" + await _create_timer(devices[KITCHEN], minutes=5, name="pizza") + await _create_timer(devices[LIVING_ROOM], minutes=10) + + await _handle(hass, intent.INTENT_CANCEL_TIMER, None, **slots) + + assert _statuses(devices[KITCHEN]) == expected_kitchen + assert _statuses(devices[LIVING_ROOM]) == expected_living_room + + +@pytest.mark.parametrize("requesting_device", [KITCHEN, LIVING_ROOM]) +async def test_requesting_device_disambiguates( + hass: HomeAssistant, devices: dict[str, TimerDevice], requesting_device: str +) -> None: + """Test the requesting device's own timer wins when several match.""" + await _create_timer(devices[KITCHEN]) + await _create_timer(devices[LIVING_ROOM]) + + await _handle( + hass, + intent.INTENT_CANCEL_TIMER, + devices[requesting_device].device_id, + start_minutes=5, + ) + + for name, timer_device in devices.items(): + expected = ( + TimerStatus.CANCELLED if name == requesting_device else TimerStatus.ACTIVE + ) + assert _statuses(timer_device) == [expected] + + +async def test_area_disambiguates( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + device_registry: dr.DeviceRegistry, + area_registry: ar.AreaRegistry, +) -> None: + """Test a timer in the requesting device's area wins when several match.""" + kitchen_area = area_registry.async_get_area_by_name("kitchen") + assert kitchen_area is not None + other_entry = MockConfigEntry(domain="other") + other_entry.add_to_hass(hass) + satellite = device_registry.async_get_or_create( + config_entry_id=other_entry.entry_id, identifiers={("other", "satellite")} + ) + device_registry.async_update_device(satellite.id, area_id=kitchen_area.id) + await _create_timer(devices[KITCHEN]) + await _create_timer(devices[LIVING_ROOM]) + + await _handle(hass, intent.INTENT_CANCEL_TIMER, satellite.id) + + assert _statuses(devices[KITCHEN]) == [TimerStatus.CANCELLED] + assert _statuses(devices[LIVING_ROOM]) == [TimerStatus.ACTIVE] + + +async def test_floor_disambiguates( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + device_registry: dr.DeviceRegistry, + area_registry: ar.AreaRegistry, + floor_registry: fr.FloorRegistry, +) -> None: + """Test a timer on the requesting device's floor wins when several match.""" + other_floor = floor_registry.async_create("Second floor") + bedroom_area = area_registry.async_create(BEDROOM, floor_id=other_floor.floor_id) + device_registry.async_update_device( + devices[LIVING_ROOM].device_id, area_id=bedroom_area.id + ) + other_entry = MockConfigEntry(domain="other") + other_entry.add_to_hass(hass) + satellite = device_registry.async_get_or_create( + config_entry_id=other_entry.entry_id, identifiers={("other", "satellite")} + ) + hallway = area_registry.async_create( + "hallway", + floor_id=floor_registry.async_get_floor_by_name("First floor").floor_id, + ) + device_registry.async_update_device(satellite.id, area_id=hallway.id) + await _create_timer(devices[KITCHEN]) + await _create_timer(devices[LIVING_ROOM]) + + await _handle(hass, intent.INTENT_CANCEL_TIMER, satellite.id) + + assert _statuses(devices[KITCHEN]) == [TimerStatus.CANCELLED] + assert _statuses(devices[LIVING_ROOM]) == [TimerStatus.ACTIVE] + + +async def test_entity_area_overrides_device_area( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + entity_registry: er.EntityRegistry, + area_registry: ar.AreaRegistry, +) -> None: + """Test the timer list's own area is used over its device's area.""" + bedroom_area = area_registry.async_create(BEDROOM) + entity_registry.async_update_entity( + devices[LIVING_ROOM].timer_list.entity_id, area_id=bedroom_area.id + ) + await _create_timer(devices[KITCHEN]) + await _create_timer(devices[LIVING_ROOM]) + + await _handle(hass, intent.INTENT_CANCEL_TIMER, None, area=BEDROOM) + + assert _statuses(devices[KITCHEN]) == [TimerStatus.ACTIVE] + assert _statuses(devices[LIVING_ROOM]) == [TimerStatus.CANCELLED] + + +async def test_multiple_timers_matched( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test an error when several timers match and nothing tells them apart.""" + await _create_timer(devices[KITCHEN]) + await _create_timer(devices[LIVING_ROOM]) + + with pytest.raises(MultipleTimersMatchedError): + await _handle(hass, intent.INTENT_CANCEL_TIMER, None) + + +async def test_timer_not_found( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test finished and cancelled timers are not matched.""" + kitchen = devices[KITCHEN] + timer_id = await _create_timer(kitchen) + await kitchen.timer_list.async_cancel_timer(timer_id) + + with pytest.raises(TimerNotFoundError): + await _handle(hass, intent.INTENT_CANCEL_TIMER, kitchen.device_id) + + +async def test_cancel_all_timers( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test cancelling the timers of every device and of the timer manager.""" + legacy_events: list[TimerEventType] = [] + + @callback + def handle_timer(event_type: TimerEventType, timer: TimerInfo) -> None: + legacy_events.append(event_type) + + async_register_timer_handler(hass, "legacy_device", handle_timer) + await _handle(hass, intent.INTENT_START_TIMER, "legacy_device", minutes=5) + await _create_timer(devices[KITCHEN]) + await _create_timer(devices[LIVING_ROOM]) + + result = await _handle(hass, intent.INTENT_CANCEL_ALL_TIMERS, None) + + assert result.speech_slots == {"canceled": 3} + assert _statuses(devices[KITCHEN]) == [TimerStatus.CANCELLED] + assert _statuses(devices[LIVING_ROOM]) == [TimerStatus.CANCELLED] + assert legacy_events == [TimerEventType.STARTED, TimerEventType.CANCELLED] + + +async def test_cancel_all_timers_in_area( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test cancelling all timers of an area.""" + await _create_timer(devices[KITCHEN], minutes=5) + await _create_timer(devices[KITCHEN], minutes=10) + await _create_timer(devices[LIVING_ROOM]) + + result = await _handle(hass, intent.INTENT_CANCEL_ALL_TIMERS, None, area="kitchen") + + assert result.speech_slots == {"canceled": 2, "area": "kitchen"} + assert _statuses(devices[KITCHEN]) == [TimerStatus.CANCELLED] * 2 + assert _statuses(devices[LIVING_ROOM]) == [TimerStatus.ACTIVE] + + +@pytest.mark.usefixtures("freezer") +@pytest.mark.parametrize( + ("intent_type", "seconds", "expected_remaining"), + [ + pytest.param(intent.INTENT_INCREASE_TIMER, 30, 330, id="increase"), + pytest.param(intent.INTENT_DECREASE_TIMER, 30, 270, id="decrease"), + ], +) +async def test_change_timer( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + intent_type: str, + seconds: int, + expected_remaining: int, +) -> None: + """Test adding and removing time on a timer list timer.""" + kitchen = devices[KITCHEN] + await _create_timer(kitchen) + + await _handle(hass, intent_type, kitchen.device_id, seconds=seconds) + + timer = kitchen.timer_list.timers[0] + assert timer.status == TimerStatus.ACTIVE + assert timer.finishes_at is not None + assert timer.finishes_at - timer.created_at == timedelta(seconds=expected_remaining) + + +async def test_pause_unpause_timer( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test pausing and resuming a timer list timer.""" + kitchen = devices[KITCHEN] + await _create_timer(kitchen) + + await _handle(hass, intent.INTENT_PAUSE_TIMER, kitchen.device_id) + assert _statuses(kitchen) == [TimerStatus.PAUSED] + + await _handle(hass, intent.INTENT_UNPAUSE_TIMER, kitchen.device_id) + assert _statuses(kitchen) == [TimerStatus.ACTIVE] + + +async def test_timer_status( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + freezer: FrozenDateTimeFactory, +) -> None: + """Test reporting the status of timer list timers, own device first.""" + kitchen = devices[KITCHEN] + living_room = devices[LIVING_ROOM] + living_room_id = await _create_timer(living_room, minutes=90, name="roast") + kitchen_id = await _create_timer(kitchen, minutes=5) + await kitchen.timer_list.async_pause_timer(kitchen_id) + freezer.tick(timedelta(minutes=2, seconds=5)) + + result = await _handle(hass, intent.INTENT_TIMER_STATUS, kitchen.device_id) + + assert result.speech_slots == { + "timers": [ + { + "id": kitchen_id, + "name": "", + "device_id": kitchen.device_id, + "language": "en", + "start_hours": 0, + "start_minutes": 5, + "start_seconds": 0, + "is_active": False, + "hours_left": 0, + "minutes_left": 5, + "seconds_left": 0, + "rounded_hours_left": 0, + "rounded_minutes_left": 5, + "rounded_seconds_left": 0, + "total_seconds_left": 300, + }, + { + "id": living_room_id, + "name": "roast", + "device_id": living_room.device_id, + "language": "en", + "start_hours": 1, + "start_minutes": 30, + "start_seconds": 0, + "is_active": True, + "hours_left": 1, + "minutes_left": 27, + "seconds_left": 55, + "rounded_hours_left": 1, + "rounded_minutes_left": 30, + "rounded_seconds_left": 0, + "total_seconds_left": 5275, + }, + ] + } + + +@pytest.mark.usefixtures("init_components") +async def test_timer_list_without_device(hass: HomeAssistant) -> None: + """Test timers of a timer list that has no device are matched by name.""" + timer_list = InMemoryTimerListEntity() + timer_list._attr_unique_id = "oven" + timer_list.entity_id = "timer_list.oven" + await _async_setup_timer_lists(hass, [timer_list]) + await timer_list.async_create_timer(name="oven", duration=timedelta(minutes=20)) + + await _handle(hass, intent.INTENT_CANCEL_TIMER, None, name="oven") + + assert [timer.status for timer in timer_list.timers] == [TimerStatus.CANCELLED] + + +async def test_device_supports_timers( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Test a device with a timer list supports timers.""" + assert async_device_supports_timers(hass, devices[KITCHEN].device_id) + assert not async_device_supports_timers(hass, "other_device") + + +@pytest.mark.usefixtures("init_components") +@pytest.mark.parametrize( + ("slots", "start_time", "duration"), + [ + pytest.param({"minutes": 5}, (0, 5, 0), 300, id="minutes"), + pytest.param({"minutes": 90}, (0, 90, 0), 5400, id="over-60-minutes"), + pytest.param({"seconds": 90}, (0, 0, 90), 90, id="over-60-seconds"), + ], +) +async def test_legacy_timer_status_after_changes( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + slots: dict[str, int], + start_time: tuple[int, int, int], + duration: int, +) -> None: + """Test legacy timer snapshots preserve remaining time and original units.""" + device_id = "legacy_device" + async_register_timer_handler(hass, device_id, Mock()) + await _handle(hass, intent.INTENT_START_TIMER, device_id, **slots) + freezer.tick(timedelta(seconds=30)) + + result = await _handle(hass, intent.INTENT_TIMER_STATUS, device_id) + timer = result.speech_slots["timers"][0] + assert timer["total_seconds_left"] == duration - 30 + assert timer["is_active"] is True + + await _handle( + hass, + intent.INTENT_INCREASE_TIMER, + device_id, + start_seconds=duration, + minutes=1, + ) + result = await _handle( + hass, intent.INTENT_TIMER_STATUS, device_id, start_seconds=duration + ) + timer = result.speech_slots["timers"][0] + assert ( + timer["start_hours"], + timer["start_minutes"], + timer["start_seconds"], + ) == start_time + assert timer["total_seconds_left"] == duration + 30 + + await _handle(hass, intent.INTENT_PAUSE_TIMER, device_id) + freezer.tick(timedelta(minutes=10)) + result = await _handle(hass, intent.INTENT_TIMER_STATUS, device_id) + timer = result.speech_slots["timers"][0] + assert timer["total_seconds_left"] == duration + 30 + assert timer["is_active"] is False + + await _handle(hass, intent.INTENT_UNPAUSE_TIMER, device_id) + freezer.tick(timedelta(seconds=15)) + result = await _handle(hass, intent.INTENT_TIMER_STATUS, device_id) + timer = result.speech_slots["timers"][0] + assert timer["total_seconds_left"] == duration + 15 + assert timer["is_active"] is True + + +@pytest.mark.usefixtures("init_components") +async def test_unregistered_timer_list_is_not_matched(hass: HomeAssistant) -> None: + """Test voice commands do not discover timer lists outside the registry.""" + timer_list = InMemoryTimerListEntity() + timer_list.entity_id = "timer_list.unregistered" + await _async_setup_timer_lists(hass, [timer_list]) + await timer_list.async_create_timer(name="oven", duration=timedelta(minutes=20)) + + with pytest.raises(TimerNotFoundError): + await _handle(hass, intent.INTENT_CANCEL_TIMER, None, name="oven") + + assert [timer.status for timer in timer_list.timers] == [TimerStatus.ACTIVE] + + +async def test_unloaded_timer_list_is_not_matched( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + entity_registry: er.EntityRegistry, +) -> None: + """Test registry entries without loaded entities do not prevent matching.""" + entity_registry.async_get_or_create( + Platform.TIMER_LIST, TEST_DOMAIN, "unloaded", suggested_object_id="unloaded" + ) + await _create_timer(devices[KITCHEN], name="oven") + + await _handle(hass, intent.INTENT_CANCEL_TIMER, None, name="oven") + + assert _statuses(devices[KITCHEN]) == [TimerStatus.CANCELLED] + + +@pytest.mark.usefixtures("init_components") +async def test_start_timer_skips_unloaded_timer_list( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: + """Test an unloaded registry entry does not hide a device's loaded timer list.""" + entry = MockConfigEntry(domain=TEST_DOMAIN) + entry.add_to_hass(hass) + device = device_registry.async_get_or_create( + config_entry_id=entry.entry_id, identifiers={(TEST_DOMAIN, KITCHEN)} + ) + entity_registry.async_get_or_create( + Platform.TIMER_LIST, TEST_DOMAIN, "unloaded", device_id=device.id + ) + timer_list = DeviceTimerList(KITCHEN) + await _async_setup_timer_lists(hass, [timer_list]) + + await _handle(hass, intent.INTENT_START_TIMER, device.id, minutes=5) + + assert len(timer_list.timers) == 1 + assert timer_list.timers[0].created_duration == timedelta(minutes=5) + + +async def test_timer_status_permissions( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Only report lists the caller can read, including read-only lists.""" + kitchen = devices[KITCHEN] + living_room = devices[LIVING_ROOM] + kitchen_id = await _create_timer(kitchen) + await _create_timer(living_room) + user = MockUser().add_to_hass(hass) + user.mock_policy( + { + "entities": { + "entity_ids": { + kitchen.timer_list.entity_id: {POLICY_READ: True}, + living_room.timer_list.entity_id: {POLICY_CONTROL: True}, + } + } + } + ) + + result = await _handle( + hass, + intent.INTENT_TIMER_STATUS, + living_room.device_id, + context=Context(user_id=user.id), + ) + + assert [timer["id"] for timer in result.speech_slots["timers"]] == [kitchen_id] + + +@pytest.mark.parametrize("can_control", [False, True]) +@pytest.mark.parametrize( + ("intent_type", "slots", "expected_status", "expected_duration"), + [ + (intent.INTENT_CANCEL_TIMER, {}, TimerStatus.CANCELLED, 300), + (intent.INTENT_PAUSE_TIMER, {}, TimerStatus.PAUSED, 300), + (intent.INTENT_UNPAUSE_TIMER, {}, TimerStatus.ACTIVE, 300), + (intent.INTENT_INCREASE_TIMER, {"seconds": 30}, TimerStatus.ACTIVE, 330), + (intent.INTENT_DECREASE_TIMER, {"seconds": 30}, TimerStatus.ACTIVE, 270), + ], +) +async def test_timer_mutation_permissions( + hass: HomeAssistant, + devices: dict[str, TimerDevice], + can_control: bool, + freezer: FrozenDateTimeFactory, + intent_type: str, + slots: dict[str, Any], + expected_status: TimerStatus, + expected_duration: int, +) -> None: + """Mutations require control and exclude other lists before matching.""" + kitchen = devices[KITCHEN] + living_room = devices[LIVING_ROOM] + for device in devices.values(): + timer_id = await _create_timer(device, name="pizza") + if intent_type == intent.INTENT_UNPAUSE_TIMER: + await device.timer_list.async_pause_timer(timer_id) + original_kitchen = deepcopy(kitchen.timer_list.timers) + original_living_room = deepcopy(living_room.timer_list.timers) + user = MockUser().add_to_hass(hass) + user.mock_policy( + { + "entities": { + "entity_ids": { + kitchen.timer_list.entity_id: { + POLICY_READ: True, + POLICY_CONTROL: can_control, + }, + living_room.timer_list.entity_id: {POLICY_READ: True}, + } + } + } + ) + + if can_control: + await _handle( + hass, + intent_type, + living_room.device_id, + name="pizza", + context=Context(user_id=user.id), + **slots, + ) + timer = kitchen.timer_list.timers[0] + assert timer.status == expected_status + if timer.finishes_at is not None: + assert timer.finishes_at - timer.created_at == timedelta( + seconds=expected_duration + ) + else: + with pytest.raises(TimerNotFoundError): + await _handle( + hass, + intent_type, + kitchen.device_id, + name="pizza", + context=Context(user_id=user.id), + **slots, + ) + assert kitchen.timer_list.timers == original_kitchen + + assert living_room.timer_list.timers == original_living_room + + +async def test_cancel_all_timer_permissions( + hass: HomeAssistant, devices: dict[str, TimerDevice] +) -> None: + """Cancel only the lists the caller can control.""" + kitchen = devices[KITCHEN] + living_room = devices[LIVING_ROOM] + await _create_timer(kitchen) + await _create_timer(living_room) + user = MockUser().add_to_hass(hass) + user.mock_policy( + { + "entities": { + "entity_ids": { + kitchen.timer_list.entity_id: {POLICY_CONTROL: True}, + living_room.timer_list.entity_id: {POLICY_READ: True}, + } + } + } + ) + + result = await _handle( + hass, + intent.INTENT_CANCEL_ALL_TIMERS, + None, + context=Context(user_id=user.id), + ) + + assert result.speech_slots == {"canceled": 1} + assert _statuses(kitchen) == [TimerStatus.CANCELLED] + assert _statuses(living_room) == [TimerStatus.ACTIVE] + + +@pytest.mark.parametrize("can_control", [False, True]) +async def test_start_timer_permissions( + hass: HomeAssistant, devices: dict[str, TimerDevice], can_control: bool +) -> None: + """Creating a timer requires control, even if the device has a legacy handler.""" + kitchen = devices[KITCHEN] + handler = Mock() + async_register_timer_handler(hass, kitchen.device_id, handler) + user = MockUser().add_to_hass(hass) + user.mock_policy( + { + "entities": { + "entity_ids": { + kitchen.timer_list.entity_id: { + POLICY_READ: True, + POLICY_CONTROL: can_control, + }, + } + } + } + ) + + if can_control: + await _handle( + hass, + intent.INTENT_START_TIMER, + kitchen.device_id, + minutes=5, + context=Context(user_id=user.id), + ) + assert _statuses(kitchen) == [TimerStatus.ACTIVE] + else: + with pytest.raises(intent.IntentUnexpectedError) as err: + await _handle( + hass, + intent.INTENT_START_TIMER, + kitchen.device_id, + minutes=5, + context=Context(user_id=user.id), + ) + assert isinstance(err.value.__cause__, Unauthorized) + assert not kitchen.timer_list.timers + + handler.assert_not_called() + + +@pytest.mark.parametrize( + "intent_type", [intent.INTENT_START_TIMER, intent.INTENT_TIMER_STATUS] +) +async def test_timer_unknown_user( + hass: HomeAssistant, devices: dict[str, TimerDevice], intent_type: str +) -> None: + """An unknown user must not gain unrestricted access.""" + kitchen = devices[KITCHEN] + await _create_timer(kitchen) + original_timers = deepcopy(kitchen.timer_list.timers) + slots = {"minutes": 5} if intent_type == intent.INTENT_START_TIMER else {} + + with pytest.raises(intent.IntentUnexpectedError) as err: + await _handle( + hass, + intent_type, + kitchen.device_id, + context=Context(user_id="unknown-user"), + **slots, + ) + + assert isinstance(err.value.__cause__, UnknownUser) + assert kitchen.timer_list.timers == original_timers diff --git a/tests/components/intent/test_timers.py b/tests/components/intent/test_timers.py index 5315cd512216..b311e233beaa 100644 --- a/tests/components/intent/test_timers.py +++ b/tests/components/intent/test_timers.py @@ -2,6 +2,7 @@ import asyncio from collections.abc import Callable +from datetime import timedelta import logging from unittest.mock import AsyncMock, MagicMock, patch @@ -23,6 +24,7 @@ from homeassistant.components.intent.timers import ( async_device_supports_timers, async_register_timer_handler, ) +from homeassistant.components.timer_list import DOMAIN as TIMER_LIST_DOMAIN from homeassistant.const import ATTR_DEVICE_ID, ATTR_NAME from homeassistant.core import Context, HomeAssistant, callback from homeassistant.helpers import ( @@ -41,6 +43,7 @@ DELAYED_COMMAND_ERROR = "Sorry, I am not aware of any device called lights" async def init_components(hass: HomeAssistant) -> None: """Initialize required components for tests.""" assert await async_setup_component(hass, "homeassistant", {}) + assert await async_setup_component(hass, TIMER_LIST_DOMAIN, {}) assert await async_setup_component(hass, "conversation", {}) assert await async_setup_component(hass, DOMAIN, {}) @@ -1000,19 +1003,19 @@ async def test_timer_not_found(hass: HomeAssistant) -> None: timer_manager = TimerManager(hass) with pytest.raises(TimerNotFoundError): - timer_manager.cancel_timer("does-not-exist") + await timer_manager.async_cancel_timer("does-not-exist") with pytest.raises(TimerNotFoundError): - timer_manager.add_time("does-not-exist", 1) + await timer_manager.async_add_time("does-not-exist", timedelta(seconds=1)) with pytest.raises(TimerNotFoundError): - timer_manager.remove_time("does-not-exist", 1) + await timer_manager.async_add_time("does-not-exist", timedelta(seconds=-1)) with pytest.raises(TimerNotFoundError): - timer_manager.pause_timer("does-not-exist") + await timer_manager.async_pause_timer("does-not-exist") with pytest.raises(TimerNotFoundError): - timer_manager.unpause_timer("does-not-exist") + await timer_manager.async_unpause_timer("does-not-exist") async def test_timer_manager_pause_unpause(hass: HomeAssistant) -> None: @@ -1038,22 +1041,22 @@ async def test_timer_manager_pause_unpause(hass: HomeAssistant) -> None: # Pause handle_timer.reset_mock() - timer_manager.pause_timer(timer_id) + await timer_manager.async_pause_timer(timer_id) handle_timer.assert_called_once() # Pausing again does not call handler handle_timer.reset_mock() - timer_manager.pause_timer(timer_id) + await timer_manager.async_pause_timer(timer_id) handle_timer.assert_not_called() # Unpause handle_timer.reset_mock() - timer_manager.unpause_timer(timer_id) + await timer_manager.async_unpause_timer(timer_id) handle_timer.assert_called_once() # Unpausing again does not call handler handle_timer.reset_mock() - timer_manager.unpause_timer(timer_id) + await timer_manager.async_unpause_timer(timer_id) handle_timer.assert_not_called() @@ -1090,15 +1093,15 @@ async def test_timers_not_supported(hass: HomeAssistant) -> None: unregister() # All operations on the timer should not crash - timer_manager.add_time(timer_id, 1) + await timer_manager.async_add_time(timer_id, timedelta(seconds=1)) - timer_manager.remove_time(timer_id, 1) + await timer_manager.async_add_time(timer_id, timedelta(seconds=-1)) - timer_manager.pause_timer(timer_id) + await timer_manager.async_pause_timer(timer_id) - timer_manager.unpause_timer(timer_id) + await timer_manager.async_unpause_timer(timer_id) - timer_manager.cancel_timer(timer_id) + await timer_manager.async_cancel_timer(timer_id) async def test_timer_status_with_names(hass: HomeAssistant, init_components) -> None: @@ -1820,6 +1823,7 @@ async def test_async_device_supports_timers(hass: HomeAssistant) -> None: assert not async_device_supports_timers(hass, device_id) # After intent initialization + assert await async_setup_component(hass, TIMER_LIST_DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {}) assert not async_device_supports_timers(hass, device_id) diff --git a/tests/helpers/test_llm.py b/tests/helpers/test_llm.py index 4bbad24bcfd9..737847d225a1 100644 --- a/tests/helpers/test_llm.py +++ b/tests/helpers/test_llm.py @@ -16,6 +16,7 @@ from homeassistant.components import llm as llm_component from homeassistant.components.homeassistant.exposed_entities import async_expose_entity from homeassistant.components.intent import async_register_timer_handler from homeassistant.components.script import ScriptConfig +from homeassistant.components.timer_list import DOMAIN as TIMER_LIST_DOMAIN from homeassistant.const import EntityStateAttribute from homeassistant.core import Context, HomeAssistant, State from homeassistant.exceptions import HomeAssistantError, Unauthorized @@ -710,6 +711,7 @@ async def test_assist_api_prompt( floor_registry: fr.FloorRegistry, ) -> None: """Test prompt for the assist API.""" + assert await async_setup_component(hass, TIMER_LIST_DOMAIN, {}) assert await async_setup_component(hass, "homeassistant", {}) assert await async_setup_component(hass, "intent", {}) context = Context()