From cdba008084cd3d69bf30c8bb4d39be702a9c6a38 Mon Sep 17 00:00:00 2001 From: Artur Pragacz <49985303+arturpragacz@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:05:27 +0100 Subject: [PATCH] Add Voice support integration (#191156) Co-authored-by: Paulus Schoutsen Co-authored-by: Michael Hansen Co-authored-by: Claude Opus 5.5 --- .strict-typing | 1 + CODEOWNERS | 2 + .../components/assist_pipeline/manifest.json | 2 +- .../components/voice_support/__init__.py | 146 ++++ homeassistant/components/voice_support/app.py | 23 + .../components/voice_support/client.py | 135 +++ .../components/voice_support/config_flow.py | 388 +++++++++ .../components/voice_support/const.py | 5 + .../components/voice_support/manifest.json | 19 + .../components/voice_support/strings.json | 79 ++ homeassistant/generated/config_flows.py | 1 + homeassistant/generated/integrations.json | 12 + homeassistant/generated/labs.py | 7 + homeassistant/generated/zeroconf.py | 5 + mypy.ini | 10 + script/hassfest/quality_scale.py | 1 + tests/components/voice_support/__init__.py | 1 + tests/components/voice_support/conftest.py | 117 +++ tests/components/voice_support/test_client.py | 165 ++++ .../voice_support/test_config_flow.py | 812 ++++++++++++++++++ tests/components/voice_support/test_init.py | 472 ++++++++++ tests/snapshots/test_bootstrap.ambr | 2 + 22 files changed, 2404 insertions(+), 1 deletion(-) create mode 100644 homeassistant/components/voice_support/__init__.py create mode 100644 homeassistant/components/voice_support/app.py create mode 100644 homeassistant/components/voice_support/client.py create mode 100644 homeassistant/components/voice_support/config_flow.py create mode 100644 homeassistant/components/voice_support/const.py create mode 100644 homeassistant/components/voice_support/manifest.json create mode 100644 homeassistant/components/voice_support/strings.json create mode 100644 tests/components/voice_support/__init__.py create mode 100644 tests/components/voice_support/conftest.py create mode 100644 tests/components/voice_support/test_client.py create mode 100644 tests/components/voice_support/test_config_flow.py create mode 100644 tests/components/voice_support/test_init.py diff --git a/.strict-typing b/.strict-typing index 18aef683c4c6..9f7d5f6e053c 100644 --- a/.strict-typing +++ b/.strict-typing @@ -690,6 +690,7 @@ homeassistant.components.vivotek.* homeassistant.components.vizio.* homeassistant.components.vlc_telnet.* homeassistant.components.vodafone_station.* +homeassistant.components.voice_support.* homeassistant.components.volvo.* homeassistant.components.wake_on_lan.* homeassistant.components.wake_word.* diff --git a/CODEOWNERS b/CODEOWNERS index 470c0f50bdf8..bbe0cbf61a08 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -2149,6 +2149,8 @@ AGENTS.md @home-assistant/core /tests/components/vlc_telnet/ @rodripf @MartinHjelmare /homeassistant/components/vodafone_station/ @paoloantinori @chemelli74 /tests/components/vodafone_station/ @paoloantinori @chemelli74 +/homeassistant/components/voice_support/ @synesthesiam @arturpragacz +/tests/components/voice_support/ @synesthesiam @arturpragacz /homeassistant/components/voip/ @home-assistant/core @jaminh /tests/components/voip/ @home-assistant/core @jaminh /homeassistant/components/volkszaehler/ @StefanSchoof diff --git a/homeassistant/components/assist_pipeline/manifest.json b/homeassistant/components/assist_pipeline/manifest.json index d88e4352130e..8943e0b8cad0 100644 --- a/homeassistant/components/assist_pipeline/manifest.json +++ b/homeassistant/components/assist_pipeline/manifest.json @@ -3,7 +3,7 @@ "name": "Assist pipeline", "after_dependencies": ["repairs"], "codeowners": ["@synesthesiam", "@arturpragacz"], - "dependencies": ["conversation", "stt", "tts", "wake_word"], + "dependencies": ["conversation", "stt", "tts", "wake_word", "voice_support"], "documentation": "https://www.home-assistant.io/integrations/assist_pipeline", "integration_type": "system", "iot_class": "local_push", diff --git a/homeassistant/components/voice_support/__init__.py b/homeassistant/components/voice_support/__init__.py new file mode 100644 index 000000000000..6f83c6fae26f --- /dev/null +++ b/homeassistant/components/voice_support/__init__.py @@ -0,0 +1,146 @@ +"""The Voice support integration.""" + +from datetime import datetime, timedelta +import logging + +from homeassistant.components.hassio import AddonError +from homeassistant.components.labs import ( + EventLabsUpdatedData, + async_is_preview_feature_enabled, + async_subscribe_preview_feature, +) +from homeassistant.config_entries import SOURCE_SYSTEM, ConfigEntry +from homeassistant.const import CONF_HOST, CONF_PORT +from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.helpers import config_validation as cv, discovery_flow +from homeassistant.helpers.event import async_track_time_interval +from homeassistant.helpers.hassio import is_hassio +from homeassistant.helpers.typing import ConfigType +from homeassistant.util.hass_dict import HassKey + +from .app import get_app_manager +from .client import ( + API_VERSION, + CLIENT_ERRORS, + UnsupportedVersionError, + VoiceSupportClient, +) +from .const import CONF_INTEGRATION_CREATED_APP, DOMAIN + +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) + +INFO_REFRESH_INTERVAL = timedelta(minutes=5) + +PREVIEW_FEATURE_NEXT_GENERATION_VOICE = "next_generation_voice" + +DATA_CLIENT: HassKey[VoiceSupportClient] = HassKey(DOMAIN) + +_LOGGER = logging.getLogger(__name__) + + +@callback +def async_is_enabled(hass: HomeAssistant) -> bool: + """Whether the person has turned voice support on.""" + return async_is_preview_feature_enabled( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE + ) + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Set up voice support.""" + + async def _async_preview_feature_updated(event_data: EventLabsUpdatedData) -> None: + if event_data["enabled"]: + _async_provision(hass) + else: + for entry in hass.config_entries.async_entries(DOMAIN): + if entry.data.get(CONF_INTEGRATION_CREATED_APP): + await hass.config_entries.async_remove(entry.entry_id) + + async_subscribe_preview_feature( + hass, + DOMAIN, + PREVIEW_FEATURE_NEXT_GENERATION_VOICE, + _async_preview_feature_updated, + ) + _async_provision(hass) + return True + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Connect to the app at the entry's address.""" + client = VoiceSupportClient(hass, entry.data[CONF_HOST], entry.data[CONF_PORT]) + try: + await client.async_update_info() + except CLIENT_ERRORS as err: + raise ConfigEntryNotReady( + translation_domain=DOMAIN, + translation_key="cannot_connect", + translation_placeholders={"url": str(client.url)}, + ) from err + except UnsupportedVersionError as err: + raise ConfigEntryNotReady( + translation_domain=DOMAIN, + translation_key="unsupported_version", + translation_placeholders={ + "name": err.info.name, + "version": err.info.version, + "api_version": str(err.info.api_version), + "supported_api_version": str(API_VERSION), + }, + ) from err + finally: + if entry.data.get(CONF_INTEGRATION_CREATED_APP): + get_app_manager(hass).async_schedule_update_addon(catch_error=True) + + async def _async_refresh_info(_now: datetime) -> None: + try: + await client.async_update_info() + except (*CLIENT_ERRORS, UnsupportedVersionError) as err: + _LOGGER.debug("Cannot use the app at %s (%r)", client.url, err) + hass.config_entries.async_schedule_reload(entry.entry_id) + + entry.async_on_unload( + async_track_time_interval(hass, _async_refresh_info, INFO_REFRESH_INTERVAL) + ) + hass.data[DATA_CLIENT] = client + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Unload the entry.""" + hass.data.pop(DATA_CLIENT) + + +async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Uninstall the app along with the entry, if this integration installed it.""" + if not entry.data.get(CONF_INTEGRATION_CREATED_APP): + return + + app_manager = get_app_manager(hass) + try: + await app_manager.async_stop_addon() + await app_manager.async_create_backup() + await app_manager.async_uninstall_addon() + except AddonError as err: + _LOGGER.error(err) + + +@callback +def _async_provision(hass: HomeAssistant) -> None: + """Put what voice support needs in place, unless that is done or underway. + + On a Supervised system that is the app. Nothing happens on a system + without one: there the user says where the app runs. + """ + if not is_hassio(hass): + return + if not async_is_enabled(hass): + return + if hass.config_entries.async_has_entries(DOMAIN): + return + if hass.config_entries.flow.async_progress_by_handler(DOMAIN): + return + discovery_flow.async_create_flow( + hass, DOMAIN, context={"source": SOURCE_SYSTEM}, data={} + ) diff --git a/homeassistant/components/voice_support/app.py b/homeassistant/components/voice_support/app.py new file mode 100644 index 000000000000..192a9a14d555 --- /dev/null +++ b/homeassistant/components/voice_support/app.py @@ -0,0 +1,23 @@ +"""The Voice app, as a Home Assistant app managed by the Supervisor.""" + +import logging + +from homeassistant.components.hassio import AddonManager +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.singleton import singleton + +from .const import DOMAIN + +APP_NAME = "Voice" +APP_SLUG = "core_voice" + +DATA_APP_MANAGER = f"{DOMAIN}_app_manager" + +_LOGGER = logging.getLogger(__name__) + + +@singleton(DATA_APP_MANAGER) +@callback +def get_app_manager(hass: HomeAssistant) -> AddonManager: + """Get the app manager.""" + return AddonManager(hass, _LOGGER, APP_NAME, APP_SLUG) diff --git a/homeassistant/components/voice_support/client.py b/homeassistant/components/voice_support/client.py new file mode 100644 index 000000000000..9888edf25149 --- /dev/null +++ b/homeassistant/components/voice_support/client.py @@ -0,0 +1,135 @@ +"""Connect to the Voice app and read its capabilities.""" + +from dataclasses import dataclass, field +from json import JSONDecodeError +import logging +from typing import Any + +import aiohttp +import probatio +from yarl import URL + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.aiohttp_client import async_get_clientsession + +API_VERSION = 1 +INFO_TIMEOUT = 10 + +INFO_SCHEMA = probatio.Schema( + { + "name": str, + "version": str, + "api_version": int, + "wake_words": [ + { + "id": str, + probatio.Optional("phrase"): probatio.Any(str, None), + } + ], + }, + required=True, + extra=probatio.ALLOW_EXTRA, +) + +_LOGGER = logging.getLogger(__name__) + + +class InvalidResponseError(Exception): + """The app returned malformed information.""" + + +CLIENT_ERRORS = (aiohttp.ClientError, TimeoutError, InvalidResponseError) + + +class UnsupportedVersionError(Exception): + """The app speaks a protocol version this Home Assistant does not.""" + + def __init__(self, info: AppInfo) -> None: + """Initialize the error.""" + super().__init__( + f"{info.name} {info.version} speaks protocol version " + f"{info.api_version}, not {API_VERSION}" + ) + self.info = info + + +@dataclass(frozen=True) +class AppInfo: + """What the app says it is and what it can do.""" + + name: str + version: str + api_version: int + wake_words: dict[str, str | None] = field(default_factory=dict) + """Normalized wake word id -> the phrase said, when it gave one.""" + + @staticmethod + def from_json(data: dict[str, Any]) -> AppInfo: + """Read an /info response.""" + data = INFO_SCHEMA(data) + return AppInfo( + name=data["name"], + version=data["version"], + api_version=data["api_version"], + wake_words={ + normalize_wake_word(wake_word["id"]): wake_word.get("phrase") + for wake_word in data["wake_words"] + }, + ) + + +def normalize_wake_word(wake_word: str) -> str: + """Treat "Okay Nabu", "okay-nabu" and "okay_nabu" as one wake word.""" + lowered = wake_word.lower().replace("-", "_").replace(" ", "_") + return "".join(c for c in lowered if c.isalnum() or c == "_") + + +class VoiceSupportClient: + """The Voice app at one address and its capabilities.""" + + def __init__(self, hass: HomeAssistant, host: str, port: int) -> None: + """Set up a client for the app at this address.""" + self.hass = hass + self.url = URL.build(scheme="http", host=host, port=port) + self.info: AppInfo | None = None + + async def async_update_info(self) -> AppInfo: + """Ask the app what it is and what it can verify. + + Raises UnsupportedVersionError, besides CLIENT_ERRORS, for an app + that cannot be used. + """ + session = async_get_clientsession(self.hass) + try: + async with session.get( + self.url / "info", timeout=aiohttp.ClientTimeout(total=INFO_TIMEOUT) + ) as response: + response.raise_for_status() + try: + data = await response.json() + except JSONDecodeError as err: + raise InvalidResponseError( + "Invalid JSON from the Voice app" + ) from err + except CLIENT_ERRORS: + self.info = None + raise + + try: + info = AppInfo.from_json(data) + except probatio.Invalid as err: + self.info = None + raise InvalidResponseError("Invalid info from the Voice app") from err + + if info.api_version != API_VERSION: + self.info = None + raise UnsupportedVersionError(info) + + self.info = info + _LOGGER.debug( + "%s %s verifies: %s", + info.name, + info.version, + ", ".join(sorted(info.wake_words)) or "(nothing)", + ) + return info diff --git a/homeassistant/components/voice_support/config_flow.py b/homeassistant/components/voice_support/config_flow.py new file mode 100644 index 000000000000..41288649f24f --- /dev/null +++ b/homeassistant/components/voice_support/config_flow.py @@ -0,0 +1,388 @@ +"""Config flow for the Voice support integration.""" + +import asyncio +from collections.abc import Callable, Coroutine +import logging +from typing import TYPE_CHECKING, Any, override + +import probatio + +from homeassistant.components.hassio import AddonError, AddonState +from homeassistant.config_entries import ConfigEntryState, ConfigFlow, ConfigFlowResult +from homeassistant.const import CONF_HOST, CONF_PORT +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import issue_registry as ir +from homeassistant.helpers.hassio import is_hassio +from homeassistant.helpers.service_info.hassio import HassioServiceInfo +from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo + +from . import async_is_enabled +from .app import get_app_manager +from .client import CLIENT_ERRORS, AppInfo, UnsupportedVersionError, VoiceSupportClient +from .const import CONF_INTEGRATION_CREATED_APP, DOMAIN + +CONF_USE_APP = "use_app" + +DEFAULT_PORT = 10900 + +APP_START_INTERVAL = 5 +APP_START_ROUNDS = 40 + +ISSUE_APP_SETUP_FAILED = "app_setup_failed" + +_LOGGER = logging.getLogger(__name__) + +STEP_MANUAL_SCHEMA = probatio.Schema( + { + probatio.Required(CONF_HOST): str, + probatio.Required(CONF_PORT, default=DEFAULT_PORT): int, + } +) +STEP_ON_SUPERVISOR_SCHEMA = probatio.Schema( + {probatio.Optional(CONF_USE_APP, default=True): bool} +) + + +async def _async_get_info(hass: HomeAssistant, host: str, port: int) -> AppInfo: + """Ask the app at this address what it is.""" + return await VoiceSupportClient(hass, host, port).async_update_info() + + +class VoiceSupportConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for Voice support.""" + + VERSION = 1 + + def __init__(self) -> None: + """Set up flow instance.""" + self._host: str | None = None + self._port: int | None = None + self._info: AppInfo | None = None + self._running_in_background = False + self._integration_created_app = False + self._failure: str | None = None + self._install_task: asyncio.Task[None] | None = None + self._start_task: asyncio.Task[None] | None = None + + @override + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle the initial step.""" + if not async_is_enabled(self.hass): + return self.async_abort(reason="preview_feature_disabled") + if self._async_current_entries(): + return self.async_abort(reason="single_instance_allowed") + if is_hassio(self.hass): + return await self.async_step_on_supervisor() + return await self.async_step_manual() + + async def async_step_system( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Set the app up without a person in the loop.""" + if not async_is_enabled(self.hass): + return self.async_abort(reason="preview_feature_disabled") + if self._async_current_entries(): + return self.async_abort(reason="already_configured") + self._running_in_background = True + return await self.async_step_on_supervisor({CONF_USE_APP: True}) + + async def async_step_manual( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle a manual configuration.""" + errors: dict[str, str] = {} + if user_input is not None: + host: str = user_input[CONF_HOST] + port: int = user_input[CONF_PORT] + try: + self._info = await _async_get_info(self.hass, host, port) + except CLIENT_ERRORS: + errors["base"] = "cannot_connect" + except UnsupportedVersionError: + errors["base"] = "unsupported_version" + else: + self._host = host + self._port = port + return self._async_create_entry() + + return self.async_show_form( + step_id="manual", + data_schema=self.add_suggested_values_to_schema( + STEP_MANUAL_SCHEMA, user_input + ), + errors=errors, + ) + + async def async_step_on_supervisor( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle logic when on Supervisor host.""" + if user_input is not None: + if not user_input[CONF_USE_APP]: + return await self.async_step_manual() + + try: + app_info = await get_app_manager(self.hass).async_get_addon_info() + except AddonError as err: + _LOGGER.error(err) + return self._async_fail("app_info_failed") + + if app_info.state is AddonState.RUNNING: + return await self.async_step_finish_app_setup() + if app_info.state is AddonState.NOT_RUNNING: + return await self.async_step_start_app() + return await self.async_step_install_app() + + return self.async_show_form( + step_id="on_supervisor", data_schema=STEP_ON_SUPERVISOR_SCHEMA + ) + + async def async_step_install_app( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Install the Voice app.""" + if self._install_task is None: + self._install_task = get_app_manager( + self.hass + ).async_schedule_install_addon() + + if not self._running_in_background and not self._install_task.done(): + return self.async_show_progress( + step_id="install_app", + progress_action="install_app", + progress_task=self._install_task, + ) + + try: + await self._install_task + except AddonError as err: + _LOGGER.error(err) + return await self._async_progress_failed("app_install_failed") + finally: + self._install_task = None + + self._integration_created_app = True + return await self._async_progress_done(self.async_step_start_app) + + async def async_step_start_app( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Start the Voice app.""" + if self._start_task is None: + self._start_task = self.hass.async_create_task(self._async_start_app()) + + if not self._running_in_background and not self._start_task.done(): + return self.async_show_progress( + step_id="start_app", + progress_action="start_app", + progress_task=self._start_task, + ) + + try: + await self._start_task + except (AddonError, TimeoutError) as err: + _LOGGER.error(err) + return await self._async_progress_failed("app_start_failed") + except UnsupportedVersionError as err: + _LOGGER.error(err) + return await self._async_progress_failed("unsupported_version") + finally: + self._start_task = None + + return await self._async_progress_done(self.async_step_finish_app_setup) + + async def async_step_finish_app_setup( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Create the entry for the running app.""" + if self._info is None: + try: + await self._async_connect_app() + except AddonError as err: + _LOGGER.error(err) + return self._async_fail("app_get_discovery_info_failed") + except CLIENT_ERRORS: + return self._async_fail("cannot_connect") + except UnsupportedVersionError as err: + _LOGGER.error(err) + return self._async_fail("unsupported_version") + + return self._async_create_entry() + + async def async_step_app_failed( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Abort with what went wrong in the progress step before.""" + if TYPE_CHECKING: + assert self._failure is not None + return self._async_fail(self._failure) + + async def _async_progress_done( + self, next_step: Callable[[], Coroutine[Any, Any, ConfigFlowResult]] + ) -> ConfigFlowResult: + """Move on from a progress step, directly when nobody is watching.""" + if self._running_in_background: + return await next_step() + return self.async_show_progress_done( + next_step_id=next_step.__name__.removeprefix("async_step_") + ) + + async def _async_progress_failed(self, reason: str) -> ConfigFlowResult: + """Give up on a progress step, directly when nobody is watching.""" + if self._running_in_background: + return self._async_fail(reason) + self._failure = reason + return self.async_show_progress_done(next_step_id="app_failed") + + @callback + def _async_fail(self, reason: str) -> ConfigFlowResult: + """Abort, and leave a repair issue when nobody is watching the flow.""" + if self._running_in_background: + ir.async_create_issue( + self.hass, + DOMAIN, + ISSUE_APP_SETUP_FAILED, + is_fixable=False, + severity=ir.IssueSeverity.WARNING, + translation_key=ISSUE_APP_SETUP_FAILED, + ) + return self.async_abort(reason=reason) + + async def _async_start_app(self) -> None: + """Start the app and wait until it answers.""" + await get_app_manager(self.hass).async_schedule_start_addon() + + for _ in range(APP_START_ROUNDS): + await asyncio.sleep(APP_START_INTERVAL) + try: + await self._async_connect_app() + except (AddonError, *CLIENT_ERRORS) as err: + _LOGGER.debug( + "App not ready yet, waiting %s seconds: %s", + APP_START_INTERVAL, + err, + ) + continue + return + + raise TimeoutError("Timeout waiting for the Voice app to start") + + async def _async_connect_app(self) -> None: + """Find the app through its discovery info and ask what it is.""" + discovery_info = await get_app_manager( + self.hass + ).async_get_addon_discovery_info() + self._host = discovery_info["host"] + self._port = discovery_info["port"] + self._info = await _async_get_info(self.hass, self._host, self._port) + + @override + async def async_step_hassio( + self, discovery_info: HassioServiceInfo + ) -> ConfigFlowResult: + """Handle the app announcing itself through the Supervisor.""" + if not async_is_enabled(self.hass): + return self.async_abort(reason="preview_feature_disabled") + + host: str = discovery_info.config["host"] + port: int = discovery_info.config["port"] + if await self._async_update_existing_entry(host, port): + return self.async_abort(reason="already_configured") + + await self._async_handle_discovery_without_unique_id() + + try: + self._info = await _async_get_info(self.hass, host, port) + except CLIENT_ERRORS: + return self.async_abort(reason="cannot_connect") + except UnsupportedVersionError: + return self.async_abort(reason="unsupported_version") + + self._host = host + self._port = port + return self._async_create_entry() + + @override + async def async_step_zeroconf( + self, discovery_info: ZeroconfServiceInfo + ) -> ConfigFlowResult: + """Handle an app found on the network.""" + if not async_is_enabled(self.hass): + return self.async_abort(reason="preview_feature_disabled") + if discovery_info.port is None: + return self.async_abort(reason="cannot_connect") + + host = discovery_info.host + port = discovery_info.port + if await self._async_update_existing_entry(host, port): + return self.async_abort(reason="already_configured") + + await self._async_handle_discovery_without_unique_id() + + try: + self._info = await _async_get_info(self.hass, host, port) + except CLIENT_ERRORS: + return self.async_abort(reason="cannot_connect") + except UnsupportedVersionError: + return self.async_abort(reason="unsupported_version") + + self._host = host + self._port = port + self.context["title_placeholders"] = {"name": self._info.name} + return await self.async_step_zeroconf_confirm() + + async def async_step_zeroconf_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm the app found on the network.""" + if TYPE_CHECKING: + assert self._info is not None + assert self._host is not None + + if user_input is not None: + return self._async_create_entry() + + return self.async_show_form( + step_id="zeroconf_confirm", + description_placeholders={"name": self._info.name, "host": self._host}, + ) + + async def _async_update_existing_entry(self, host: str, port: int) -> bool: + """Point the entry at a rediscovered app, and say whether there was one. + + A different host is left alone: the person may have pointed the entry + at an app of their own. + """ + for entry in self._async_current_entries(include_ignore=True): + if entry.data.get(CONF_HOST) != host: + return True + updated = self.hass.config_entries.async_update_entry( + entry, data={**entry.data, CONF_PORT: port} + ) + if entry.state is ConfigEntryState.SETUP_RETRY or ( + updated and entry.state is ConfigEntryState.LOADED + ): + # The app is back, or moved: a retry need not wait out its backoff + self.hass.config_entries.async_schedule_reload(entry.entry_id) + return True + return False + + @callback + def _async_create_entry(self) -> ConfigFlowResult: + """Create the entry, and clear any complaint from an earlier attempt. + + Another flow may have made one in the meantime, and there is one client. + """ + if TYPE_CHECKING: + assert self._info is not None + assert self._host is not None + assert self._port is not None + if self._async_current_entries(): + return self.async_abort(reason="already_configured") + ir.async_delete_issue(self.hass, DOMAIN, ISSUE_APP_SETUP_FAILED) + data: dict[str, Any] = {CONF_HOST: self._host, CONF_PORT: self._port} + if self._integration_created_app: + data[CONF_INTEGRATION_CREATED_APP] = True + return self.async_create_entry(title=self._info.name, data=data) diff --git a/homeassistant/components/voice_support/const.py b/homeassistant/components/voice_support/const.py new file mode 100644 index 000000000000..bcdd5c2911d4 --- /dev/null +++ b/homeassistant/components/voice_support/const.py @@ -0,0 +1,5 @@ +"""Constants for the Voice support integration.""" + +DOMAIN = "voice_support" + +CONF_INTEGRATION_CREATED_APP = "integration_created_app" diff --git a/homeassistant/components/voice_support/manifest.json b/homeassistant/components/voice_support/manifest.json new file mode 100644 index 000000000000..936a2bf0eeac --- /dev/null +++ b/homeassistant/components/voice_support/manifest.json @@ -0,0 +1,19 @@ +{ + "domain": "voice_support", + "name": "Voice support", + "after_dependencies": ["hassio"], + "categories": ["ai_voice.voice_assistants"], + "codeowners": ["@synesthesiam", "@arturpragacz"], + "config_flow": true, + "connectivity": ["network"], + "documentation": "https://www.home-assistant.io/integrations/voice_support", + "integration_type": "service", + "iot_class": "local_push", + "preview_features": { + "next_generation_voice": { + "learn_more_url": "https://www.home-assistant.io/integrations/voice_support" + } + }, + "quality_scale": "internal", + "zeroconf": ["_voice-support._tcp.local."] +} diff --git a/homeassistant/components/voice_support/strings.json b/homeassistant/components/voice_support/strings.json new file mode 100644 index 000000000000..ee2af2756294 --- /dev/null +++ b/homeassistant/components/voice_support/strings.json @@ -0,0 +1,79 @@ +{ + "config": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_service%]", + "app_get_discovery_info_failed": "The Voice app is running but has not announced itself to Home Assistant yet.", + "app_info_failed": "Failed to get the Voice app info.", + "app_install_failed": "Failed to install the Voice app.", + "app_start_failed": "Failed to start the Voice app.", + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "preview_feature_disabled": "Turn on the Next-generation voice preview feature in Home Assistant Labs first.", + "single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]", + "unsupported_version": "The Voice app speaks a protocol version this Home Assistant does not. Update the app or Home Assistant." + }, + "error": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "unsupported_version": "[%key:component::voice_support::config::abort::unsupported_version%]" + }, + "flow_title": "{name}", + "progress": { + "install_app": "Please wait while the Voice app installation finishes. This can take several minutes.", + "start_app": "Please wait while the Voice app starts. This may take some seconds." + }, + "step": { + "install_app": { + "title": "The app installation has started" + }, + "manual": { + "data": { + "host": "[%key:common::config_flow::data::host%]", + "port": "[%key:common::config_flow::data::port%]" + }, + "data_description": { + "host": "The hostname or IP address of the Voice app.", + "port": "The port the Voice app listens on." + }, + "title": "Connect to the Voice app" + }, + "on_supervisor": { + "data": { + "use_app": "Use the official Voice app" + }, + "data_description": { + "use_app": "Home Assistant installs and starts the app for you if needed." + }, + "description": "Do you want to use the official Voice app?\n\nIf you are already running the Voice app in a custom container, natively etc., then do not select this option.", + "title": "Select connection method" + }, + "start_app": { + "title": "Starting app" + }, + "zeroconf_confirm": { + "description": "Do you want to connect to {name} at {host}?", + "title": "Discovered Voice app" + } + } + }, + "exceptions": { + "cannot_connect": { + "message": "Cannot connect to the Voice app at {url}." + }, + "unsupported_version": { + "message": "{name} {version} speaks protocol version {api_version}, but this Home Assistant needs version {supported_api_version}. Update the app or Home Assistant." + } + }, + "issues": { + "app_setup_failed": { + "description": "Home Assistant could not install or start the Voice app, which the next generation voice stack needs. Check the app in the app store, then restart Home Assistant to try again.", + "title": "The Voice app could not be set up" + } + }, + "preview_features": { + "next_generation_voice": { + "description": "Enables the next generation voice stack in Home Assistant. On a Home Assistant OS or Supervised system the app is installed for you when this feature is enabled.", + "disable_confirmation": "Next-generation voice will be turned off. If Home Assistant installed the Voice app, it will back up and uninstall the app and remove its integration entry.", + "enable_confirmation": "This feature is still in development and may change. On a Home Assistant OS or Supervised system the Voice app will be installed when this feature is enabled.", + "name": "Next-generation voice" + } + } +} diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 6beaab4d1091..83db4713ca70 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -921,6 +921,7 @@ FLOWS = { "vizio", "vlc_telnet", "vodafone_station", + "voice_support", "voip", "volkszaehler", "volumio", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index 2da31faa28c1..a28bdf7b469f 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -16374,6 +16374,18 @@ "config_flow": true, "iot_class": "local_polling" }, + "voice_support": { + "name": "Voice support", + "integration_type": "service", + "categories": [ + "ai_voice.voice_assistants" + ], + "connectivity": [ + "network" + ], + "config_flow": true, + "iot_class": "local_push" + }, "voicerss": { "name": "VoiceRSS", "integration_type": "hub", diff --git a/homeassistant/generated/labs.py b/homeassistant/generated/labs.py index 549a2030a2da..34d1b102e129 100644 --- a/homeassistant/generated/labs.py +++ b/homeassistant/generated/labs.py @@ -46,4 +46,11 @@ LABS_PREVIEW_FEATURES = { "report_issue_url": "https://github.com/home-assistant/core/issues/new?template=bug_report.yml&integration_link=https://www.home-assistant.io/integrations/teslemetry&integration_name=Teslemetry", }, }, + "voice_support": { + "next_generation_voice": { + "feedback_url": "", + "learn_more_url": "https://www.home-assistant.io/integrations/voice_support", + "report_issue_url": "", + }, + }, } diff --git a/homeassistant/generated/zeroconf.py b/homeassistant/generated/zeroconf.py index 164abbfb895a..8b6d01020154 100644 --- a/homeassistant/generated/zeroconf.py +++ b/homeassistant/generated/zeroconf.py @@ -1140,6 +1140,11 @@ ZEROCONF = { "domain": "vizio", }, ], + "_voice-support._tcp.local.": [ + { + "domain": "voice_support", + }, + ], "_waermeleser._tcp.local.": [ { "domain": "energieleser", diff --git a/mypy.ini b/mypy.ini index e022770af944..d73b5df45a6b 100644 --- a/mypy.ini +++ b/mypy.ini @@ -6654,6 +6654,16 @@ disallow_untyped_defs = true warn_return_any = true warn_unreachable = true +[mypy-homeassistant.components.voice_support.*] +check_untyped_defs = true +disallow_incomplete_defs = true +disallow_subclassing_any = true +disallow_untyped_calls = true +disallow_untyped_decorators = true +disallow_untyped_defs = true +warn_return_any = true +warn_unreachable = true + [mypy-homeassistant.components.volvo.*] check_untyped_defs = true disallow_incomplete_defs = true diff --git a/script/hassfest/quality_scale.py b/script/hassfest/quality_scale.py index bcf3378c972d..9063e79695e6 100644 --- a/script/hassfest/quality_scale.py +++ b/script/hassfest/quality_scale.py @@ -1993,6 +1993,7 @@ NO_QUALITY_SCALE = [ "trace", "usage_prediction", "vibration", + "voice_support", "web_rtc", "webhook", "websocket_api", diff --git a/tests/components/voice_support/__init__.py b/tests/components/voice_support/__init__.py new file mode 100644 index 000000000000..26cd2c7c604a --- /dev/null +++ b/tests/components/voice_support/__init__.py @@ -0,0 +1 @@ +"""Tests for the Voice support integration.""" diff --git a/tests/components/voice_support/conftest.py b/tests/components/voice_support/conftest.py new file mode 100644 index 000000000000..8445150bf041 --- /dev/null +++ b/tests/components/voice_support/conftest.py @@ -0,0 +1,117 @@ +"""Fixtures for the Voice support tests.""" + +from collections.abc import Generator +from typing import Any +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +from aiohasupervisor.models import Discovery +import pytest +from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.test_util.aiohttp import AiohttpClientMocker + +from homeassistant.components.labs import async_update_preview_feature +from homeassistant.components.voice_support import PREVIEW_FEATURE_NEXT_GENERATION_VOICE +from homeassistant.components.voice_support.app import APP_SLUG +from homeassistant.components.voice_support.const import DOMAIN +from homeassistant.const import CONF_HOST, CONF_PORT +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component + +HOST = "192.168.1.5" +PORT = 10900 +APP_HOST = "core-voice" +INFO_URL = f"http://{HOST}:{PORT}/info" +APP_INFO_URL = f"http://{APP_HOST}:{PORT}/info" + +INFO = { + "name": "Voice", + "version": "1.0.0", + "api_version": 1, + "wake_words": [{"id": "okay_nabu", "phrase": "okay nabu"}], +} + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Mock setting up a config entry, and unloading it.""" + with ( + patch( + "homeassistant.components.voice_support.async_setup_entry", + return_value=None, + ) as mock, + patch( + "homeassistant.components.voice_support.async_unload_entry", + return_value=None, + ), + ): + yield mock + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return an entry for an app the person runs.""" + return MockConfigEntry( + domain=DOMAIN, title="Voice", data={CONF_HOST: HOST, CONF_PORT: PORT} + ) + + +@pytest.fixture +async def labs(hass: HomeAssistant) -> None: + """Set up Labs, with the feature off.""" + assert await async_setup_component(hass, "labs", {}) + + +@pytest.fixture +async def preview_feature_enabled(hass: HomeAssistant, labs: None) -> None: + """Turn on the Labs feature.""" + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, True + ) + + +@pytest.fixture +def app_info(aioclient_mock: AiohttpClientMocker) -> dict[str, Any]: + """Make the app answer /info at both addresses it may have.""" + aioclient_mock.get(INFO_URL, json=INFO) + aioclient_mock.get(APP_INFO_URL, json=INFO) + return INFO + + +@pytest.fixture +def supervisor(hass: HomeAssistant) -> None: + """Run under the Supervisor.""" + hass.config.components.add("hassio") + + +@pytest.fixture(name="discovery_info") +def discovery_info_fixture() -> list[Discovery]: + """Return the app's discovery info.""" + return [ + Discovery( + addon=APP_SLUG, + service=DOMAIN, + uuid=uuid4(), + config={"host": APP_HOST, "port": PORT}, + ) + ] + + +@pytest.fixture(autouse=True) +def app_wait_time() -> Generator[None]: + """Make the app start loop run without delay.""" + with patch( + "homeassistant.components.voice_support.config_flow.APP_START_INTERVAL", 0 + ): + yield + + +@pytest.fixture +async def setup_integration( + hass: HomeAssistant, mock_config_entry: MockConfigEntry, app_info: dict[str, Any] +) -> MockConfigEntry: + """Set the entry up against an answering app.""" + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + return mock_config_entry diff --git a/tests/components/voice_support/test_client.py b/tests/components/voice_support/test_client.py new file mode 100644 index 000000000000..da9ddadd429f --- /dev/null +++ b/tests/components/voice_support/test_client.py @@ -0,0 +1,165 @@ +"""Test talking to the Voice app.""" + +from typing import Any + +import aiohttp +import pytest +from pytest_homeassistant.test_util.aiohttp import AiohttpClientMocker + +from homeassistant.components.voice_support.client import ( + AppInfo, + InvalidResponseError, + UnsupportedVersionError, + VoiceSupportClient, + normalize_wake_word, +) +from homeassistant.core import HomeAssistant + +from .conftest import HOST, INFO, INFO_URL, PORT + + +@pytest.mark.parametrize( + ("wake_word", "expected"), + [ + pytest.param("Okay Nabu", "okay_nabu", id="phrase"), + pytest.param("okay-nabu", "okay_nabu", id="dashes"), + pytest.param("okay_nabu", "okay_nabu", id="id"), + pytest.param("Hey, Jarvis!", "hey_jarvis", id="punctuation"), + ], +) +def test_normalize_wake_word(wake_word: str, expected: str) -> None: + """Test the spellings of a wake word come out the same.""" + assert normalize_wake_word(wake_word) == expected + + +@pytest.mark.parametrize( + ("host", "url"), + [ + pytest.param(HOST, INFO_URL, id="ipv4"), + pytest.param("2001:db8::1", f"http://[2001:db8::1]:{PORT}/info", id="ipv6"), + ], +) +async def test_update_info( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, host: str, url: str +) -> None: + """Test reading what the app says about itself.""" + aioclient_mock.get(url, json=INFO) + client = VoiceSupportClient(hass, host, PORT) + assert client.info is None + + info = await client.async_update_info() + + assert info.name == "Voice" + assert info.version == "1.0.0" + assert info.wake_words == {"okay_nabu": "okay nabu"} + assert client.info is info + + +async def test_update_info_wrong_api_version( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Test an app speaking another protocol version cannot be used.""" + aioclient_mock.get(INFO_URL, json={**INFO, "api_version": 2}) + client = VoiceSupportClient(hass, HOST, PORT) + client.info = AppInfo.from_json(INFO) + + with pytest.raises(UnsupportedVersionError) as err: + await client.async_update_info() + + assert err.value.info.api_version == 2 + assert str(err.value) == "Voice 1.0.0 speaks protocol version 2, not 1" + assert client.info is None + + +@pytest.mark.parametrize( + ("response", "error"), + [ + pytest.param( + {"exc": aiohttp.ClientError}, aiohttp.ClientError, id="unreachable" + ), + pytest.param({"status": 500}, aiohttp.ClientResponseError, id="error"), + pytest.param( + {"text": "not json", "headers": {"Content-Type": "application/json"}}, + InvalidResponseError, + id="garbage", + ), + pytest.param( + {"json": {"name": "Voice", "api_version": 1}}, + InvalidResponseError, + id="incomplete", + ), + pytest.param( + {"json": {**INFO, "wake_words": [{}]}}, + InvalidResponseError, + id="nameless_wake_word", + ), + pytest.param( + {"json": {**INFO, "wake_words": [{"id": None}]}}, + InvalidResponseError, + id="wake_word_id_not_text", + ), + *[ + pytest.param( + {"json": {**INFO, field: value}}, InvalidResponseError, id=name + ) + for field, value, name in ( + ("name", None, "invalid_name"), + ("version", 1, "invalid_version"), + ("api_version", "1", "invalid_api_version"), + ("wake_words", [None], "invalid_wake_word"), + ("wake_words", [{"id": "okay_nabu", "phrase": 42}], "invalid_phrase"), + ) + ], + pytest.param( + {"json": {**INFO, "wake_words": "okay nabu"}}, + InvalidResponseError, + id="wrong_type", + ), + ], +) +async def test_update_info_failure( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + response: dict[str, Any], + error: type[Exception], +) -> None: + """Test an app that cannot be read, or breaks the contract, is forgotten.""" + aioclient_mock.get(INFO_URL, **response) + client = VoiceSupportClient(hass, HOST, PORT) + client.info = AppInfo.from_json(INFO) + + with pytest.raises(error): + await client.async_update_info() + + assert client.info is None + + +@pytest.mark.parametrize("error", [AttributeError, KeyError, TypeError, ValueError]) +async def test_update_info_unexpected_error( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, error: type[Exception] +) -> None: + """Test errors outside response parsing are not handled as client failures.""" + aioclient_mock.get(INFO_URL, exc=error) + client = VoiceSupportClient(hass, HOST, PORT) + + with pytest.raises(error): + await client.async_update_info() + + +@pytest.mark.parametrize( + "wake_word", [{"id": "okay_nabu"}, {"id": "okay_nabu", "phrase": None}] +) +async def test_update_info_optional_phrase( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + wake_word: dict[str, str | None], +) -> None: + """Test optional phrases and extra response fields are accepted.""" + aioclient_mock.get( + INFO_URL, json={**INFO, "wake_words": [wake_word], "extra": True} + ) + client = VoiceSupportClient(hass, HOST, PORT) + + info = await client.async_update_info() + + assert info.wake_words == {"okay_nabu": None} diff --git a/tests/components/voice_support/test_config_flow.py b/tests/components/voice_support/test_config_flow.py new file mode 100644 index 000000000000..e33c3db6d440 --- /dev/null +++ b/tests/components/voice_support/test_config_flow.py @@ -0,0 +1,812 @@ +"""Test the Voice support config flow.""" + +import asyncio +from ipaddress import ip_address +from typing import Any +from unittest.mock import AsyncMock, call, patch + +from aiohasupervisor import SupervisorError +import aiohttp +import pytest +from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.test_util.aiohttp import AiohttpClientMocker + +from homeassistant.components.voice_support.app import APP_SLUG +from homeassistant.components.voice_support.config_flow import ( + CONF_USE_APP, + ISSUE_APP_SETUP_FAILED, +) +from homeassistant.components.voice_support.const import ( + CONF_INTEGRATION_CREATED_APP, + DOMAIN, +) +from homeassistant.config_entries import ( + SOURCE_HASSIO, + SOURCE_SYSTEM, + SOURCE_USER, + SOURCE_ZEROCONF, + ConfigEntryState, +) +from homeassistant.const import CONF_HOST, CONF_PORT +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType +from homeassistant.helpers import issue_registry as ir +from homeassistant.helpers.service_info.hassio import HassioServiceInfo +from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo + +from .conftest import APP_HOST, APP_INFO_URL, HOST, INFO, INFO_URL, PORT + +HASSIO_DATA = HassioServiceInfo( + config={"host": APP_HOST, "port": PORT}, + name="Voice", + slug=APP_SLUG, + uuid="1234", +) + +ZEROCONF_DATA = ZeroconfServiceInfo( + ip_address=ip_address(HOST), + ip_addresses=[ip_address(HOST)], + hostname="voice.local.", + name="Voice._voice-support._tcp.local.", + port=PORT, + properties={}, + type="_voice-support._tcp.local.", +) + +pytestmark = pytest.mark.usefixtures("mock_setup_entry") + + +@pytest.mark.usefixtures("labs") +async def test_user_flow_feature_off(hass: HomeAssistant) -> None: + """Test nothing can be set up until the feature is on.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "preview_feature_disabled" + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_manual_flow(hass: HomeAssistant) -> None: + """Test saying where the app runs.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "manual" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_HOST: HOST, CONF_PORT: PORT} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "Voice" + assert result["data"] == {CONF_HOST: HOST, CONF_PORT: PORT} + + +@pytest.mark.parametrize( + ("response", "reason"), + [ + pytest.param({"exc": aiohttp.ClientError}, "cannot_connect", id="unreachable"), + pytest.param({"json": {"name": "Voice"}}, "cannot_connect", id="malformed"), + pytest.param( + {"json": {**INFO, "api_version": 2}}, "unsupported_version", id="version" + ), + ], +) +@pytest.mark.usefixtures("preview_feature_enabled") +async def test_manual_flow_cannot_use_app( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + response: dict[str, Any], + reason: str, +) -> None: + """Test an app that does not answer, or cannot be used, can be tried again.""" + aioclient_mock.get(INFO_URL, **response) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_HOST: HOST, CONF_PORT: PORT} + ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": reason} + + aioclient_mock.clear_requests() + aioclient_mock.get(INFO_URL, json=INFO) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_HOST: HOST, CONF_PORT: PORT} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_manual_flows_at_once(hass: HomeAssistant) -> None: + """Test two people saying where the app runs do not make two entries.""" + first = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + second = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + result = await hass.config_entries.flow.async_configure( + first["flow_id"], {CONF_HOST: HOST, CONF_PORT: PORT} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + result = await hass.config_entries.flow.async_configure( + second["flow_id"], {CONF_HOST: HOST, CONF_PORT: PORT} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("preview_feature_enabled") +async def test_user_flow_single_instance( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test there is one app.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "single_instance_allowed" + + +@pytest.mark.usefixtures("supervisor", "preview_feature_enabled") +async def test_on_supervisor_without_app(hass: HomeAssistant) -> None: + """Test opting out of the app on Supervisor leads to manual setup.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "on_supervisor" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: False} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "manual" + + +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "app_info", + "addon_not_installed", + "get_addon_discovery_info", +) +async def test_app_not_installed( + hass: HomeAssistant, install_addon: AsyncMock, start_addon: AsyncMock +) -> None: + """Test installing and starting the app.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["step_id"] == "install_app" + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + assert install_addon.call_args == call(APP_SLUG) + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["step_id"] == "start_app" + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + assert start_addon.call_args == call(APP_SLUG) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "Voice" + assert result["data"] == { + CONF_HOST: APP_HOST, + CONF_PORT: PORT, + CONF_INTEGRATION_CREATED_APP: True, + } + + +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "app_info", + "addon_installed", + "get_addon_discovery_info", +) +async def test_app_installed_not_running( + hass: HomeAssistant, install_addon: AsyncMock, start_addon: AsyncMock +) -> None: + """Test starting an installed app.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["step_id"] == "start_app" + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + assert install_addon.call_count == 0 + assert start_addon.call_args == call(APP_SLUG) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"] == {CONF_HOST: APP_HOST, CONF_PORT: PORT} + + +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "app_info", + "addon_running", + "get_addon_discovery_info", +) +async def test_app_running( + hass: HomeAssistant, install_addon: AsyncMock, start_addon: AsyncMock +) -> None: + """Test using an already running app.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + + assert install_addon.call_count == 0 + assert start_addon.call_count == 0 + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"] == {CONF_HOST: APP_HOST, CONF_PORT: PORT} + + +@pytest.mark.parametrize( + ("discovery_failure", "info_response", "reason"), + [ + pytest.param( + SupervisorError(), + {"json": INFO}, + "app_get_discovery_info_failed", + id="info", + ), + pytest.param( + None, {"exc": aiohttp.ClientError}, "cannot_connect", id="unreachable" + ), + pytest.param( + None, + {"json": {**INFO, "api_version": 2}}, + "unsupported_version", + id="version", + ), + ], +) +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "addon_running", + "install_addon", + "start_addon", +) +async def test_app_running_cannot_be_used( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + get_addon_discovery_info: AsyncMock, + discovery_failure: Exception | None, + info_response: dict[str, Any], + reason: str, +) -> None: + """Test a running app that cannot be reached, or used, is reported.""" + get_addon_discovery_info.side_effect = discovery_failure + aioclient_mock.get(APP_INFO_URL, **info_response) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason + + +@pytest.mark.usefixtures( + "supervisor", "preview_feature_enabled", "addon_not_installed", "start_addon" +) +async def test_app_install_failed( + hass: HomeAssistant, install_addon: AsyncMock +) -> None: + """Test a failed installation is reported.""" + install_addon.side_effect = SupervisorError() + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + assert result["type"] is FlowResultType.SHOW_PROGRESS + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "app_install_failed" + + +@pytest.mark.usefixtures( + "supervisor", "preview_feature_enabled", "addon_installed", "install_addon" +) +async def test_app_start_failed(hass: HomeAssistant, start_addon: AsyncMock) -> None: + """Test a failed start is reported.""" + start_addon.side_effect = SupervisorError() + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + assert result["type"] is FlowResultType.SHOW_PROGRESS + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "app_start_failed" + + +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "addon_installed", + "install_addon", + "start_addon", + "get_addon_discovery_info", +) +async def test_app_start_unsupported_version( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Test an app that starts speaking another protocol version is reported.""" + aioclient_mock.get(APP_INFO_URL, json={**INFO, "api_version": 2}) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + assert result["type"] is FlowResultType.SHOW_PROGRESS + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_version" + + +@pytest.mark.usefixtures( + "supervisor", "preview_feature_enabled", "addon_installed", "install_addon" +) +async def test_app_start_timeout( + hass: HomeAssistant, start_addon: AsyncMock, get_addon_discovery_info: AsyncMock +) -> None: + """Test an app that never answers after starting is reported.""" + get_addon_discovery_info.return_value = [] + with patch( + "homeassistant.components.voice_support.config_flow.APP_START_ROUNDS", 2 + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "app_start_failed" + + +@pytest.mark.usefixtures("supervisor", "preview_feature_enabled", "addon_store_info") +async def test_app_info_failed( + hass: HomeAssistant, addon_store_info: AsyncMock +) -> None: + """Test the Supervisor not answering about the app is reported.""" + addon_store_info.side_effect = SupervisorError() + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USE_APP: True} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "app_info_failed" + + +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "app_info", + "addon_not_installed", + "get_addon_discovery_info", +) +async def test_system_flow( + hass: HomeAssistant, + install_addon: AsyncMock, + start_addon: AsyncMock, + issue_registry: ir.IssueRegistry, +) -> None: + """Test the app is set up with nobody watching, from install to entry.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SYSTEM} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert install_addon.call_args == call(APP_SLUG) + assert start_addon.call_args == call(APP_SLUG) + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 1 + assert entries[0].source == SOURCE_SYSTEM + assert entries[0].data == { + CONF_HOST: APP_HOST, + CONF_PORT: PORT, + CONF_INTEGRATION_CREATED_APP: True, + } + assert not issue_registry.issues + + +@pytest.mark.usefixtures("supervisor", "preview_feature_enabled") +async def test_system_flow_with_an_entry( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test nothing is set up behind the person's back when they have an app.""" + mock_config_entry.add_to_hass(hass) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SYSTEM} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("supervisor", "labs") +async def test_system_flow_feature_off(hass: HomeAssistant) -> None: + """Test the system flow does nothing with the feature off.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SYSTEM} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "preview_feature_disabled" + + +@pytest.mark.usefixtures( + "supervisor", "preview_feature_enabled", "addon_not_installed", "start_addon" +) +async def test_system_flow_failure_leaves_an_issue( + hass: HomeAssistant, + install_addon: AsyncMock, + issue_registry: ir.IssueRegistry, +) -> None: + """Test a silent flow that fails says so in Repairs.""" + install_addon.side_effect = SupervisorError() + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SYSTEM} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "app_install_failed" + assert not hass.config_entries.async_entries(DOMAIN) + issue = issue_registry.async_get_issue(DOMAIN, ISSUE_APP_SETUP_FAILED) + assert issue is not None + assert issue.translation_key == ISSUE_APP_SETUP_FAILED + + +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "app_info", + "addon_running", + "get_addon_discovery_info", +) +async def test_system_flow_success_clears_the_issue( + hass: HomeAssistant, issue_registry: ir.IssueRegistry +) -> None: + """Test a later success takes the complaint back.""" + ir.async_create_issue( + hass, + DOMAIN, + ISSUE_APP_SETUP_FAILED, + is_fixable=False, + severity=ir.IssueSeverity.WARNING, + translation_key=ISSUE_APP_SETUP_FAILED, + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SYSTEM} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert len(hass.config_entries.async_entries(DOMAIN)) == 1 + assert issue_registry.async_get_issue(DOMAIN, ISSUE_APP_SETUP_FAILED) is None + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_hassio_flow(hass: HomeAssistant) -> None: + """Test the app announcing itself gets an entry without a word.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_HASSIO}, data=HASSIO_DATA + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "Voice" + assert result["data"] == {CONF_HOST: APP_HOST, CONF_PORT: PORT} + + +@pytest.mark.usefixtures("labs") +async def test_hassio_flow_feature_off(hass: HomeAssistant) -> None: + """Test the app announcing itself is ignored with the feature off.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_HASSIO}, data=HASSIO_DATA + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "preview_feature_disabled" + + +@pytest.mark.parametrize( + ("response", "reason"), + [ + pytest.param({"exc": aiohttp.ClientError}, "cannot_connect", id="unreachable"), + pytest.param({"json": {"name": "Voice"}}, "cannot_connect", id="malformed"), + pytest.param( + {"json": {**INFO, "api_version": 2}}, "unsupported_version", id="version" + ), + ], +) +@pytest.mark.usefixtures("preview_feature_enabled") +async def test_hassio_flow_cannot_use_app( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + response: dict[str, Any], + reason: str, +) -> None: + """Test an announced app that does not answer, or cannot be used, gets no entry.""" + aioclient_mock.get(APP_INFO_URL, **response) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_HASSIO}, data=HASSIO_DATA + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason + + +@pytest.mark.usefixtures( + "supervisor", + "preview_feature_enabled", + "app_info", + "addon_not_installed", + "start_addon", + "get_addon_discovery_info", +) +async def test_hassio_flow_while_system_flow_runs( + hass: HomeAssistant, install_addon: AsyncMock +) -> None: + """Test the app announcing itself mid-setup does not start a second flow.""" + installing = hass.loop.create_future() + + async def _install(addon: str) -> None: + await installing + + install_addon.side_effect = _install + system_flow = hass.async_create_task( + hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_SYSTEM}) + ) + await asyncio.sleep(0) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_HASSIO}, data=HASSIO_DATA + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_in_progress" + + installing.set_result(None) + result = await system_flow + assert result["type"] is FlowResultType.CREATE_ENTRY + assert len(hass.config_entries.async_entries(DOMAIN)) == 1 + + +@pytest.mark.parametrize( + ("source", "data", "host"), + [ + pytest.param(SOURCE_HASSIO, HASSIO_DATA, APP_HOST, id="hassio"), + pytest.param(SOURCE_ZEROCONF, ZEROCONF_DATA, HOST, id="zeroconf"), + ], +) +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_discovery_updates_the_entry( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + source: str, + data: HassioServiceInfo | ZeroconfServiceInfo, + host: str, +) -> None: + """Test a rediscovered app with a new port updates and reloads the entry.""" + entry = MockConfigEntry( + domain=DOMAIN, title="Voice", data={CONF_HOST: host, CONF_PORT: PORT + 1} + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + assert mock_setup_entry.call_count == 1 + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": source}, data=data + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert entry.data == {CONF_HOST: host, CONF_PORT: PORT} + assert mock_setup_entry.call_count == 2 + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_discovery_reloads_a_retrying_entry(hass: HomeAssistant) -> None: + """Test the app coming back does not wait out the retry backoff.""" + entry = MockConfigEntry( + domain=DOMAIN, + title="Voice", + data={CONF_HOST: APP_HOST, CONF_PORT: PORT}, + state=ConfigEntryState.SETUP_RETRY, + ) + entry.add_to_hass(hass) + + with patch.object(hass.config_entries, "async_schedule_reload") as reload: + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_HASSIO}, data=HASSIO_DATA + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert reload.call_args == call(entry.entry_id) + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_discovery_leaves_an_unchanged_loaded_entry_alone( + hass: HomeAssistant, mock_setup_entry: AsyncMock +) -> None: + """Test the app announcing itself again at the same address is no reason to reload. + + The Supervisor re-sends every discovery at each start, and the client + keeps its own view of the app fresh. + """ + entry = MockConfigEntry( + domain=DOMAIN, title="Voice", data={CONF_HOST: APP_HOST, CONF_PORT: PORT} + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + assert mock_setup_entry.call_count == 1 + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_HASSIO}, data=HASSIO_DATA + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_setup_entry.call_count == 1 + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_discovery_leaves_another_host_alone( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test an entry pointed at an app of the person's own is not overwritten.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_HASSIO}, data=HASSIO_DATA + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config_entry.data == {CONF_HOST: HOST, CONF_PORT: PORT} + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_zeroconf_flow(hass: HomeAssistant) -> None: + """Test an app found on the network is confirmed before it is used.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DATA + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "zeroconf_confirm" + assert result["description_placeholders"] == {"name": "Voice", "host": HOST} + + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "Voice" + assert result["data"] == {CONF_HOST: HOST, CONF_PORT: PORT} + + +@pytest.mark.usefixtures("labs") +async def test_zeroconf_flow_feature_off(hass: HomeAssistant) -> None: + """Test an app found on the network is ignored with the feature off.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DATA + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "preview_feature_disabled" + + +@pytest.mark.usefixtures("preview_feature_enabled") +async def test_zeroconf_flow_no_port(hass: HomeAssistant) -> None: + """Test an announcement without a port is useless.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=ZeroconfServiceInfo( + ip_address=ip_address(HOST), + ip_addresses=[ip_address(HOST)], + hostname="voice.local.", + name="Voice._voice-support._tcp.local.", + port=None, + properties={}, + type="_voice-support._tcp.local.", + ), + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "cannot_connect" + + +@pytest.mark.parametrize( + ("response", "reason"), + [ + pytest.param({"exc": aiohttp.ClientError}, "cannot_connect", id="unreachable"), + pytest.param({"json": {"name": "Voice"}}, "cannot_connect", id="malformed"), + pytest.param( + {"json": {**INFO, "api_version": 2}}, "unsupported_version", id="version" + ), + ], +) +@pytest.mark.usefixtures("preview_feature_enabled") +async def test_zeroconf_flow_cannot_use_app( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + response: dict[str, Any], + reason: str, +) -> None: + """Test an app found on the network that cannot be used is dropped.""" + aioclient_mock.get(INFO_URL, **response) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DATA + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason + + +@pytest.mark.usefixtures("preview_feature_enabled", "app_info") +async def test_zeroconf_confirm_after_an_entry_appeared( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test confirming a stale discovery does not make a second entry.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DATA + ) + assert result["type"] is FlowResultType.FORM + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" diff --git a/tests/components/voice_support/test_init.py b/tests/components/voice_support/test_init.py new file mode 100644 index 000000000000..75e111e23405 --- /dev/null +++ b/tests/components/voice_support/test_init.py @@ -0,0 +1,472 @@ +"""Test setting up Voice support and asking for the app.""" + +import asyncio +from typing import Any +from unittest.mock import ANY, AsyncMock, call, patch + +from aiohasupervisor import SupervisorError +import aiohttp +import pytest +from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed +from pytest_homeassistant.test_util.aiohttp import AiohttpClientMocker + +from homeassistant.components.labs import async_update_preview_feature +from homeassistant.components.voice_support import ( + DATA_CLIENT, + INFO_REFRESH_INTERVAL, + PREVIEW_FEATURE_NEXT_GENERATION_VOICE, +) +from homeassistant.components.voice_support.client import AppInfo +from homeassistant.components.voice_support.const import ( + CONF_INTEGRATION_CREATED_APP, + DOMAIN, +) +from homeassistant.config_entries import SOURCE_SYSTEM, SOURCE_USER, ConfigEntryState +from homeassistant.const import CONF_HOST, CONF_PORT +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component +from homeassistant.util import dt as dt_util + +from .conftest import APP_HOST, INFO, INFO_URL, PORT + + +async def test_setup_entry( + hass: HomeAssistant, setup_integration: MockConfigEntry +) -> None: + """Test setup connects to the app and unload removes the client.""" + assert setup_integration.state is ConfigEntryState.LOADED + assert hass.data[DATA_CLIENT].info is not None + + await hass.config_entries.async_unload(setup_integration.entry_id) + await hass.async_block_till_done() + + assert setup_integration.state is ConfigEntryState.NOT_LOADED + assert DATA_CLIENT not in hass.data + + +@pytest.mark.parametrize( + ("response", "reason"), + [ + pytest.param({"exc": aiohttp.ClientError}, "cannot_connect", id="unreachable"), + pytest.param({"json": {"name": "Voice"}}, "cannot_connect", id="malformed"), + pytest.param( + {"json": {**INFO, "api_version": 2}}, "unsupported_version", id="version" + ), + ], +) +async def test_setup_entry_cannot_use_app( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + aioclient_mock: AiohttpClientMocker, + response: dict[str, Any], + reason: str, +) -> None: + """Test an app that does not answer, or cannot be used, leaves the entry retrying.""" + aioclient_mock.get(INFO_URL, **response) + mock_config_entry.add_to_hass(hass) + + assert not await hass.config_entries.async_setup(mock_config_entry.entry_id) + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + assert mock_config_entry.error_reason_translation_key == reason + + +async def test_info_refresh( + hass: HomeAssistant, + setup_integration: MockConfigEntry, + aioclient_mock: AiohttpClientMocker, +) -> None: + """Test app information is refreshed until the entry unloads.""" + client = hass.data[DATA_CLIENT] + assert aioclient_mock.call_count == 1 + + async_fire_time_changed(hass, dt_util.utcnow() + INFO_REFRESH_INTERVAL) + await hass.async_block_till_done() + assert aioclient_mock.call_count == 2 + assert client.info is not None + + await hass.config_entries.async_unload(setup_integration.entry_id) + aioclient_mock.clear_requests() + aioclient_mock.get(INFO_URL, json=INFO) + async_fire_time_changed(hass, dt_util.utcnow() + 2 * INFO_REFRESH_INTERVAL) + await hass.async_block_till_done() + assert aioclient_mock.call_count == 0 + + +@pytest.mark.parametrize( + ("response", "reason"), + [ + pytest.param({"exc": aiohttp.ClientError}, "cannot_connect", id="unreachable"), + pytest.param({"json": {"name": "Voice"}}, "cannot_connect", id="malformed"), + pytest.param( + {"json": {**INFO, "api_version": 2}}, "unsupported_version", id="version" + ), + ], +) +async def test_info_refresh_reloads_unusable_app( + hass: HomeAssistant, + setup_integration: MockConfigEntry, + aioclient_mock: AiohttpClientMocker, + response: dict[str, Any], + reason: str, +) -> None: + """Test an unusable app reloads the entry and recovers through setup retries.""" + client = hass.data[DATA_CLIENT] + aioclient_mock.clear_requests() + aioclient_mock.get(INFO_URL, **response) + + async_fire_time_changed(hass, dt_util.utcnow() + INFO_REFRESH_INTERVAL) + await hass.async_block_till_done() + + assert client.info is None + assert DATA_CLIENT not in hass.data + assert setup_integration.state is ConfigEntryState.SETUP_RETRY + assert setup_integration.error_reason_translation_key == reason + + aioclient_mock.clear_requests() + aioclient_mock.get(INFO_URL, json=INFO) + async_fire_time_changed(hass, dt_util.utcnow() + 2 * INFO_REFRESH_INTERVAL) + await hass.async_block_till_done() + + assert setup_integration.state is ConfigEntryState.LOADED + assert hass.data[DATA_CLIENT].info is not None + + +@pytest.mark.parametrize( + ("owned", "api_version", "update_available", "update_error", "expected_updates"), + [ + pytest.param(True, 0, True, None, 1, id="owned_outdated"), + pytest.param(True, 0, False, None, 0, id="no_update"), + pytest.param(False, 0, True, None, 0, id="external"), + pytest.param(True, 2, True, None, 1, id="newer_protocol"), + pytest.param(True, 0, True, SupervisorError("busy"), 1, id="update_failed"), + ], +) +@pytest.mark.usefixtures("supervisor", "addon_running") +async def test_setup_updates_owned_app( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + aioclient_mock: AiohttpClientMocker, + addon_info: AsyncMock, + create_backup: AsyncMock, + update_addon: AsyncMock, + owned: bool, + api_version: int, + update_available: bool, + update_error: Exception | None, + expected_updates: int, +) -> None: + """Test setup updates an incompatible app only when the integration installed it.""" + addon_info.return_value.update_available = update_available + update_addon.side_effect = update_error + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, + data={**mock_config_entry.data, CONF_INTEGRATION_CREATED_APP: owned}, + ) + aioclient_mock.get(INFO_URL, json={**INFO, "api_version": api_version}) + + assert not await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + assert create_backup.call_count == expected_updates + assert update_addon.call_count == expected_updates + + +SYSTEM_FLOW = call(ANY, DOMAIN, context={"source": SOURCE_SYSTEM}, data={}) + + +@pytest.mark.parametrize( + ("components", "feature", "expected_flows"), + [ + pytest.param(set(), True, [], id="no_supervisor"), + pytest.param({"hassio"}, False, [], id="feature_off"), + pytest.param({"hassio"}, True, [SYSTEM_FLOW], id="wanted"), + ], +) +@pytest.mark.usefixtures("labs") +async def test_loading_provisions( + hass: HomeAssistant, + components: set[str], + feature: bool, + expected_flows: list[Any], +) -> None: + """Test loading asks for the app, on a Supervised system with the feature on.""" + hass.config.components.update(components) + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, feature + ) + + with patch( + "homeassistant.components.voice_support.discovery_flow.async_create_flow" + ) as create_flow: + assert await async_setup_component(hass, DOMAIN, {}) + + assert create_flow.call_args_list == expected_flows + + +@pytest.mark.usefixtures("supervisor", "preview_feature_enabled") +async def test_provision_once( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test an entry, or a flow already underway, means nothing more to do.""" + with patch( + "homeassistant.components.voice_support.discovery_flow.async_create_flow" + ) as create_flow: + await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert await async_setup_component(hass, DOMAIN, {}) + assert create_flow.call_count == 0 + + for flow in hass.config_entries.flow.async_progress_by_handler(DOMAIN): + hass.config_entries.flow.async_abort(flow["flow_id"]) + mock_config_entry.add_to_hass(hass) + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, False + ) + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, True + ) + await hass.async_block_till_done() + assert create_flow.call_count == 0 + + +@pytest.mark.usefixtures("supervisor", "preview_feature_enabled") +async def test_enabling_the_feature_asks_for_the_app(hass: HomeAssistant) -> None: + """Test turning the feature on is one of the moments the app is wanted.""" + with patch( + "homeassistant.components.voice_support.discovery_flow.async_create_flow" + ) as create_flow: + assert await async_setup_component(hass, DOMAIN, {}) + assert create_flow.call_count == 1 + + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, False + ) + await hass.async_block_till_done() + assert create_flow.call_count == 1 + + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, True + ) + await hass.async_block_till_done() + assert create_flow.call_count == 2 + + +@pytest.mark.parametrize( + ("owned", "expected_removals", "expected_refreshes"), + [ + pytest.param(True, 1, 0, id="managed"), + pytest.param(False, 0, 1, id="manual"), + ], +) +@pytest.mark.usefixtures( + "supervisor", "addon_running", "preview_feature_enabled", "app_info" +) +async def test_disabling_removes_managed_entry( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + aioclient_mock: AiohttpClientMocker, + stop_addon: AsyncMock, + create_backup: AsyncMock, + uninstall_addon: AsyncMock, + owned: bool, + expected_removals: int, + expected_refreshes: int, +) -> None: + """Test disabling removes only entries and apps created by the integration.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, + data={**mock_config_entry.data, CONF_INTEGRATION_CREATED_APP: owned}, + ) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, False + ) + await hass.async_block_till_done() + + assert ( + hass.config_entries.async_get_entry(mock_config_entry.entry_id) is None + ) == owned + assert (DATA_CLIENT not in hass.data) == owned + assert stop_addon.call_count == expected_removals + assert create_backup.call_count == expected_removals + assert uninstall_addon.call_count == expected_removals + + aioclient_mock.clear_requests() + aioclient_mock.get(INFO_URL, json=INFO) + async_fire_time_changed(hass, dt_util.utcnow() + INFO_REFRESH_INTERVAL) + await hass.async_block_till_done() + assert aioclient_mock.call_count == expected_refreshes + + with patch( + "homeassistant.components.voice_support.discovery_flow.async_create_flow" + ) as create_flow: + await async_update_preview_feature( + hass, DOMAIN, PREVIEW_FEATURE_NEXT_GENERATION_VOICE, True + ) + await hass.async_block_till_done() + assert create_flow.call_count == expected_removals + + +@pytest.mark.parametrize("component", ["assist_pipeline", "assist_satellite"]) +async def test_voice_component_loads_the_integration( + hass: HomeAssistant, component: str +) -> None: + """Test voice support loads through the pipeline dependency.""" + assert await async_setup_component(hass, "homeassistant", {}) + assert await async_setup_component(hass, component, {}) + + assert DOMAIN in hass.config.components + + +@pytest.mark.parametrize( + ("extra_data", "expected_calls"), + [ + pytest.param({CONF_INTEGRATION_CREATED_APP: True}, 1, id="ours"), + pytest.param({}, 0, id="theirs"), + ], +) +@pytest.mark.usefixtures("supervisor", "addon_running") +async def test_remove_entry( + hass: HomeAssistant, + stop_addon: AsyncMock, + create_backup: AsyncMock, + uninstall_addon: AsyncMock, + extra_data: dict[str, Any], + expected_calls: int, +) -> None: + """Test removing the entry takes the app with it only if we installed it.""" + entry = MockConfigEntry( + domain=DOMAIN, + title="Voice", + data={CONF_HOST: APP_HOST, CONF_PORT: PORT, **extra_data}, + ) + entry.add_to_hass(hass) + + await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + + assert stop_addon.call_count == expected_calls + assert create_backup.call_count == expected_calls + assert uninstall_addon.call_count == expected_calls + + +@pytest.mark.usefixtures("supervisor", "addon_running", "create_backup") +async def test_remove_entry_app_error( + hass: HomeAssistant, + stop_addon: AsyncMock, + uninstall_addon: AsyncMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test the app refusing to stop is logged, and the entry still goes.""" + stop_addon.side_effect = SupervisorError("busy") + entry = MockConfigEntry( + domain=DOMAIN, + title="Voice", + data={CONF_HOST: APP_HOST, CONF_PORT: PORT, CONF_INTEGRATION_CREATED_APP: True}, + ) + entry.add_to_hass(hass) + + await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + + assert uninstall_addon.call_count == 0 + assert "Failed to stop the Voice app: busy" in caplog.text + assert not hass.config_entries.async_entries(DOMAIN) + + +@pytest.mark.parametrize( + ("owned", "update_available", "expected_updates"), + [(True, True, 1), (True, False, 0), (False, True, 0)], +) +@pytest.mark.usefixtures("supervisor", "addon_running", "app_info") +async def test_setup_updates_compatible_app( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + addon_info: AsyncMock, + update_addon: AsyncMock, + owned: bool, + update_available: bool, + expected_updates: int, +) -> None: + """Test compatible managed apps are also updated when an update is available.""" + addon_info.return_value.update_available = update_available + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, + data={**mock_config_entry.data, CONF_INTEGRATION_CREATED_APP: owned}, + ) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert update_addon.call_count == expected_updates + + +@pytest.mark.usefixtures("supervisor", "addon_running", "app_info") +async def test_refresh_does_not_update_managed_app( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + addon_info: AsyncMock, + update_addon: AsyncMock, +) -> None: + """Test periodic info refreshes do not update the app.""" + addon_info.return_value.update_available = False + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, + data={**mock_config_entry.data, CONF_INTEGRATION_CREATED_APP: True}, + ) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + update_addon.assert_not_called() + + addon_info.return_value.update_available = True + async_fire_time_changed(hass, dt_util.utcnow() + INFO_REFRESH_INTERVAL) + await hass.async_block_till_done() + + update_addon.assert_not_called() + + +async def test_setup_waits_for_info_before_update( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the app cannot update while the initial info request is pending.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, + data={**mock_config_entry.data, CONF_INTEGRATION_CREATED_APP: True}, + ) + info_requested = asyncio.Event() + info: asyncio.Future[AppInfo] = asyncio.Future() + + async def async_read_info() -> AppInfo: + info_requested.set() + return await info + + with ( + patch( + "homeassistant.components.voice_support.VoiceSupportClient.async_update_info", + side_effect=async_read_info, + ), + patch("homeassistant.components.voice_support.get_app_manager") as app_manager, + ): + setup_task = hass.async_create_task( + hass.config_entries.async_setup(mock_config_entry.entry_id) + ) + await info_requested.wait() + app_manager.assert_not_called() + + info.set_result(AppInfo.from_json(INFO)) + assert await setup_task + + app_manager.return_value.async_schedule_update_addon.assert_called_once_with( + catch_error=True + ) diff --git a/tests/snapshots/test_bootstrap.ambr b/tests/snapshots/test_bootstrap.ambr index 13e9ea90e99f..42585428fee1 100644 --- a/tests/snapshots/test_bootstrap.ambr +++ b/tests/snapshots/test_bootstrap.ambr @@ -103,6 +103,7 @@ 'vacuum', 'valve', 'vibration', + 'voice_support', 'wake_word', 'water_heater', 'weather', @@ -215,6 +216,7 @@ 'vacuum', 'valve', 'vibration', + 'voice_support', 'wake_word', 'water_heater', 'weather',