Add repair fix flow LLM tools to repairs integration (#194224)

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
Allen Porter
2026-11-24 20:10:21 -05:00
committed by GitHub
co-authored by Paulus Schoutsen
parent eeac2e7ebf
commit 5bbdead438
4 changed files with 1249 additions and 66 deletions
+11 -3
View File
@@ -205,9 +205,9 @@ async def async_configure_step[
Returns a `ToolResult` directly when input arguments are invalid, when the
flow is not found, when `abort` is true, when input does not match the
current step type, or when `async_configure` raises `InvalidData` or
`UnknownFlow`. Otherwise returns the next `FlowResult` (or the current
`SHOW_PROGRESS` step while its progress task is still running) for the
caller to format with `format_result`.
`UnknownFlow`. Otherwise returns the current `FlowResult` when inspecting
a form/menu or waiting for a progress task, or the next `FlowResult` when
advancing the flow, for the caller to format with `format_result`.
"""
if user_input is not None and next_step_id is not None:
return _error_result("Cannot specify both 'user_input' and 'next_step_id'.")
@@ -256,6 +256,14 @@ async def async_configure_step[
f"Current step has type '{cur_type}' and does not accept input."
)
if (
cur_type
in (data_entry_flow.FlowResultType.FORM, data_entry_flow.FlowResultType.MENU)
and user_input is None
and next_step_id is None
):
return cur_step
if (
cur_type is data_entry_flow.FlowResultType.SHOW_PROGRESS
and (progress_task := flow_handler.async_get_progress_task()) is not None
+256 -9
View File
@@ -1,10 +1,14 @@
"""LLM tools for the repairs integration."""
from typing import TYPE_CHECKING, override
from collections.abc import Mapping
from contextlib import suppress
from typing import TYPE_CHECKING, Any, override
import probatio
from homeassistant.components.llm import LLMTools
from homeassistant import data_entry_flow
from homeassistant.components.llm import LLMTools, flow as llm_flow
from homeassistant.config_entries import UnknownEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import (
config_validation as cv,
@@ -22,12 +26,24 @@ from homeassistant.helpers.llm import (
)
from homeassistant.util.json import JsonObjectType, JsonValueType
from .const import DOMAIN
from .const import DATA_REPAIRS, DOMAIN
from .issue_handler import RepairsFlowManager
from .models import RepairsFlowResult
_NON_EMPTY_STRING = probatio.All(str, probatio.Strip, probatio.NonEmpty())
_SEVERITY_ORDER = {severity.value: idx for idx, severity in enumerate(ir.IssueSeverity)}
def _resolve_language(hass: HomeAssistant, language: str | None) -> str:
"""Resolve a translation language code from an LLMContext language."""
return language if language and language != "*" else hass.config.language
def _error_result(error: str) -> ToolResult:
"""Return an error ToolResult."""
return ToolResult(data={"error": error}, error=True)
def _format_issue(issue: ir.IssueEntry, translations: dict[str, str]) -> JsonObjectType:
"""Format an active IssueEntry for LLM consumption."""
if TYPE_CHECKING:
@@ -149,11 +165,7 @@ class GetIssuesTool(Tool):
if not issues:
return ToolResult(data={"issues": []})
language = (
llm_context.language
if llm_context.language and llm_context.language != "*"
else hass.config.language
)
language = _resolve_language(hass, llm_context.language)
translations = await translation.async_get_translations(
hass,
language,
@@ -169,6 +181,235 @@ class GetIssuesTool(Tool):
)
async def _async_finalize_fix_flow_step(
hass: HomeAssistant,
flow_mgr: RepairsFlowManager,
result: RepairsFlowResult,
domain: str,
issue_id: str,
language: str | None,
*,
issue_translation_key: str | None,
issue_placeholders: Mapping[str, str] | None,
) -> ToolResult:
"""Handle external steps or format a RepairsFlowResult with translations."""
if result["type"] is data_entry_flow.FlowResultType.EXTERNAL_STEP:
with suppress(data_entry_flow.UnknownFlow):
flow_mgr.async_abort(result["flow_id"])
return ToolResult(
data={
"error": (
f"Repair fix flow for '{domain}/{issue_id}' requires browser "
"interaction (external step) and must be completed in the "
"Home Assistant UI at /config/repairs."
),
"frontend_url": "/config/repairs",
},
error=True,
)
translations: dict[str, str] = {}
base_prefix = ""
fallback_title: str | None = None
if issue_translation_key is not None:
trans_domain: str = result.get("translation_domain") or domain
translations = await translation.async_get_translations(
hass,
_resolve_language(hass, language),
"issues",
{domain, trans_domain},
)
base_prefix = (
f"component.{trans_domain}.issues.{issue_translation_key}.fix_flow"
)
fallback_title = translations.get(
f"component.{domain}.issues.{issue_translation_key}.title"
)
formatted = llm_flow.format_result(
result,
translations,
base_prefix,
fallback_title=fallback_title,
extra_placeholders=issue_placeholders,
)
return ToolResult(data={"result": formatted})
class StartFixFlowTool(Tool):
"""LLM Tool to start a repair issue fix flow."""
name = "repairs__start_fix_flow"
title = "Start repair fix flow"
description = (
"Start a repair fix flow for a fixable Home Assistant repair issue and "
"return its initial step. Use repairs__get_issues first to find the "
"issue's 'domain' and 'issue_id' (only issues with 'is_fixable: true' "
"have a fix flow)."
)
annotations = ToolAnnotations(
read_only=False, destructive=True, idempotent=False, open_world=True
)
integration = DOMAIN
parameters = probatio.Schema(
{
probatio.Required(
"domain",
description=(
"The owning integration domain of the repair issue "
"(e.g. 'automation', 'homeassistant')."
),
): _NON_EMPTY_STRING,
probatio.Required(
"issue_id",
description="The issue_id of the fixable repair issue to fix.",
): _NON_EMPTY_STRING,
}
)
@override
async def async_call(
self, hass: HomeAssistant, tool_input: ToolInput, llm_context: LLMContext
) -> ToolResult:
"""Start a fix flow for the specified repair issue."""
args = self.parameters(tool_input.tool_args)
domain: str = args["domain"].lower()
issue_id: str = args["issue_id"]
issue_registry = ir.async_get(hass)
issue = issue_registry.async_get_issue(domain, issue_id)
if issue is None or not issue.active or issue_registry.async_is_hidden(issue):
return _error_result(
f"Repair issue '{issue_id}' for domain '{domain}' not found."
)
if not issue.is_fixable:
return _error_result(
f"Repair issue '{issue_id}' for domain '{domain}' is not fixable."
)
# Capture translation metadata before async_init, as immediate CREATE_ENTRY
# deletes the issue from the registry.
issue_translation_key = issue.translation_key
issue_placeholders = issue.translation_placeholders
flow_mgr = hass.data[DATA_REPAIRS].flow_manager
try:
result = await flow_mgr.async_init(domain, context={"issue_id": issue_id})
except data_entry_flow.UnknownFlow, data_entry_flow.UnknownStep:
return _error_result(
f"Unable to start fix flow for repair issue '{issue_id}' "
f"in domain '{domain}'."
)
except UnknownEntry as err:
return _error_result(f"Config entry '{err}' not found in next_flow.")
return await _async_finalize_fix_flow_step(
hass,
flow_mgr,
result,
domain,
issue_id,
llm_context.language,
issue_translation_key=issue_translation_key,
issue_placeholders=issue_placeholders,
)
class ConfigureFixFlowTool(Tool):
"""LLM Tool to inspect, advance, or abort an in-progress repair fix flow."""
name = "repairs__configure_fix_flow"
title = "Configure repair fix flow step"
description = (
"Inspect, submit input to, or abort an in-progress repair fix flow by flow_id.\n"
"- To inspect the current step without submitting, omit both 'user_input' and 'next_step_id'.\n"
"- For a 'progress' step, omit both 'user_input' and 'next_step_id' to poll until it advances.\n"
"- To submit a 'form' step, pass field values in 'user_input' (pass {} for "
"a confirmation form with no fields).\n"
"- To select an option in a 'menu' step, pass the option key in 'next_step_id'.\n"
"- To cancel/abort the flow, set 'abort' to true."
)
annotations = ToolAnnotations(
read_only=False, destructive=True, idempotent=False, open_world=True
)
integration = DOMAIN
parameters = probatio.Schema(
{
probatio.Required(
"flow_id",
description="The flow_id returned by repairs__start_fix_flow.",
): _NON_EMPTY_STRING,
probatio.Optional(
"user_input",
description=(
"Field values to submit when the current step has type 'form' "
"(pass {} to confirm an empty form). Omit to fetch the current step state."
),
): dict,
probatio.Optional(
"next_step_id",
description=(
"Menu option key to select when the current step has type 'menu'."
),
): _NON_EMPTY_STRING,
probatio.Optional(
"abort",
description="Set to true to cancel and abort the flow (default: false).",
default=False,
): probatio.All(probatio.Boolean(), bool),
}
)
@override
async def async_call(
self, hass: HomeAssistant, tool_input: ToolInput, llm_context: LLMContext
) -> ToolResult:
"""Configure or abort the specified repair fix flow."""
args = self.parameters(tool_input.tool_args)
flow_id: str = args["flow_id"]
user_input: dict[str, Any] | None = args.get("user_input")
next_step_id: str | None = args.get("next_step_id")
abort: bool = args["abort"]
# Capture flow and issue metadata before advancing, as CREATE_ENTRY pops
# the flow and deletes the issue from the registry.
flow_mgr = hass.data[DATA_REPAIRS].flow_manager
domain = ""
issue_id = ""
issue_translation_key: str | None = None
issue_placeholders: Mapping[str, str] | None = None
if (flow_handler := flow_mgr._progress.get(flow_id)) is not None: # noqa: SLF001
domain = flow_handler.handler
issue_id = flow_handler.context["issue_id"]
if issue := ir.async_get(hass).async_get_issue(domain, issue_id):
issue_translation_key = issue.translation_key
issue_placeholders = issue.translation_placeholders
try:
step_result = await llm_flow.async_configure_step(
flow_mgr,
flow_id,
user_input=user_input,
next_step_id=next_step_id,
abort=abort,
)
except UnknownEntry as err:
return _error_result(f"Config entry '{err}' not found in next_flow.")
if isinstance(step_result, ToolResult):
return step_result
return await _async_finalize_fix_flow_step(
hass,
flow_mgr,
step_result,
domain,
issue_id,
llm_context.language,
issue_translation_key=issue_translation_key,
issue_placeholders=issue_placeholders,
)
@callback
def async_get_tools(
hass: HomeAssistant, llm_context: LLMContext, api_id: str
@@ -177,4 +418,10 @@ def async_get_tools(
if api_id != LLM_API_HOME_ASSISTANT:
return None
return LLMTools(tools=[GetIssuesTool()])
return LLMTools(
tools=[
GetIssuesTool(),
StartFixFlowTool(),
ConfigureFixFlowTool(),
]
)
+112 -24
View File
@@ -52,33 +52,121 @@
# ---
# name: test_tool_exposure_and_schema
dict({
'additionalProperties': False,
'properties': dict({
'domain': dict({
'description': "Filter by the issue's owning integration domain (e.g. 'automation', 'hue', 'mqtt', or 'homeassistant' for core reauth and YAML issues).",
'items': dict({
'format': 'strip',
'type': 'string',
'repairs__configure_fix_flow': dict({
'annotations': dict({
'destructive': True,
'idempotent': False,
'open_world': True,
'read_only': False,
}),
'description': '''
Inspect, submit input to, or abort an in-progress repair fix flow by flow_id.
- To inspect the current step without submitting, omit both 'user_input' and 'next_step_id'.
- For a 'progress' step, omit both 'user_input' and 'next_step_id' to poll until it advances.
- To submit a 'form' step, pass field values in 'user_input' (pass {} for a confirmation form with no fields).
- To select an option in a 'menu' step, pass the option key in 'next_step_id'.
- To cancel/abort the flow, set 'abort' to true.
''',
'parameters': dict({
'additionalProperties': False,
'properties': dict({
'abort': dict({
'default': False,
'description': 'Set to true to cancel and abort the flow (default: false).',
'type': 'boolean',
}),
'flow_id': dict({
'description': 'The flow_id returned by repairs__start_fix_flow.',
'format': 'strip',
'type': 'string',
}),
'next_step_id': dict({
'description': "Menu option key to select when the current step has type 'menu'.",
'format': 'strip',
'type': 'string',
}),
'user_input': dict({
'additionalProperties': True,
'description': "Field values to submit when the current step has type 'form' (pass {} to confirm an empty form). Omit to fetch the current step state.",
'type': 'object',
}),
}),
'minItems': 1,
'type': 'array',
}),
'include_ignored': dict({
'default': True,
'description': 'Whether to include ignored (dismissed) issues in the results.',
'type': 'boolean',
}),
'severity': dict({
'description': 'Filter by issue severity.',
'enum': list([
'critical',
'error',
'warning',
'required': list([
'flow_id',
]),
'format': 'lower',
'type': 'string',
'type': 'object',
}),
'title': 'Configure repair fix flow step',
}),
'repairs__get_issues': dict({
'annotations': dict({
'destructive': False,
'idempotent': True,
'open_world': False,
'read_only': True,
}),
'description': "Retrieve active Home Assistant repair issues raised by integrations or core (such as broken automations, deprecated configurations, or device problems), including their severity, fixability, and translated title and description. Ignored issues are included by default and marked with 'ignored: true'; issues for disabled config entries are excluded.",
'parameters': dict({
'additionalProperties': False,
'properties': dict({
'domain': dict({
'description': "Filter by the issue's owning integration domain (e.g. 'automation', 'hue', 'mqtt', or 'homeassistant' for core reauth and YAML issues).",
'items': dict({
'format': 'strip',
'type': 'string',
}),
'minItems': 1,
'type': 'array',
}),
'include_ignored': dict({
'default': True,
'description': 'Whether to include ignored (dismissed) issues in the results.',
'type': 'boolean',
}),
'severity': dict({
'description': 'Filter by issue severity.',
'enum': list([
'critical',
'error',
'warning',
]),
'format': 'lower',
'type': 'string',
}),
}),
'type': 'object',
}),
'title': 'Get repair issues',
}),
'repairs__start_fix_flow': dict({
'annotations': dict({
'destructive': True,
'idempotent': False,
'open_world': True,
'read_only': False,
}),
'description': "Start a repair fix flow for a fixable Home Assistant repair issue and return its initial step. Use repairs__get_issues first to find the issue's 'domain' and 'issue_id' (only issues with 'is_fixable: true' have a fix flow).",
'parameters': dict({
'additionalProperties': False,
'properties': dict({
'domain': dict({
'description': "The owning integration domain of the repair issue (e.g. 'automation', 'homeassistant').",
'format': 'strip',
'type': 'string',
}),
'issue_id': dict({
'description': 'The issue_id of the fixable repair issue to fix.',
'format': 'strip',
'type': 'string',
}),
}),
'required': list([
'domain',
'issue_id',
]),
'type': 'object',
}),
'title': 'Start repair fix flow',
}),
'type': 'object',
})
# ---
+870 -30
View File
@@ -1,21 +1,32 @@
"""Tests for the repairs LLM tools."""
import asyncio
import dataclasses
from unittest.mock import patch
from typing import Any
from unittest.mock import Mock, patch
import probatio
import pytest
from pytest_homeassistant.common import MockConfigEntry, MockUser
from pytest_homeassistant.common import MockConfigEntry, MockUser, mock_platform
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.repairs import DOMAIN
from homeassistant.config_entries import ConfigEntryDisabler
from homeassistant import data_entry_flow
from homeassistant.components.repairs import (
DOMAIN,
RepairsFlow,
RepairsFlowResult,
repairs_flow_manager,
)
from homeassistant.config_entries import ConfigEntryDisabler, UnknownEntry
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import issue_registry as ir, llm
from homeassistant.setup import async_setup_component
from homeassistant.util.json import JsonObjectType
TOOL_NAME = "repairs__get_issues"
START_FIX_FLOW_TOOL = "repairs__start_fix_flow"
CONFIGURE_FIX_FLOW_TOOL = "repairs__configure_fix_flow"
ALL_TOOL_NAMES = [TOOL_NAME, START_FIX_FLOW_TOOL, CONFIGURE_FIX_FLOW_TOOL]
MOCK_DOMAINS = ["domain_a", "domain_b"]
@@ -96,27 +107,26 @@ async def test_tool_exposure_and_schema(
llm_api: llm.APIInstance,
snapshot: SnapshotAssertion,
) -> None:
"""Test repairs__get_issues is exposed only on the Home Assistant API."""
"""Test repairs tools are exposed only on the Home Assistant API."""
assist_api = await llm.async_get_api(hass, llm.LLM_API_ASSIST, llm_context)
assert all(tool.name != TOOL_NAME for tool in assist_api.tools)
assert all(tool.name not in ALL_TOOL_NAMES for tool in assist_api.tools)
repairs_tools = [tool for tool in llm_api.tools if tool.integration == DOMAIN]
assert [tool.name for tool in repairs_tools] == [TOOL_NAME]
tool = repairs_tools[0]
assert tool.title == "Get repair issues"
assert tool.description
assert tool.annotations == llm.ToolAnnotations(
read_only=True, destructive=False, idempotent=True, open_world=False
)
assert [tool.name for tool in repairs_tools] == ALL_TOOL_NAMES
assert llm_api.api_prompt == ""
assert (
probatio.to_openapi(
tool.parameters,
custom_serializer=llm_api.custom_serializer,
openapi_version="3.1.0",
)
== snapshot
)
assert {
tool.name: {
"title": tool.title,
"description": tool.description,
"annotations": tool.annotations,
"parameters": probatio.to_openapi(
tool.parameters,
custom_serializer=llm_api.custom_serializer,
openapi_version="3.1.0",
),
}
for tool in repairs_tools
} == snapshot
@pytest.mark.freeze_time("2026-11-16 02:00:00+00:00")
@@ -321,19 +331,849 @@ async def test_get_issues_missing_translations_and_placeholders(
@pytest.mark.parametrize(
"invalid_args",
("tool_name", "invalid_args"),
[
pytest.param({"domain": " "}, id="whitespace_domain"),
pytest.param({"domain": []}, id="empty_domain_list"),
pytest.param({"severity": "info"}, id="invalid_severity"),
pytest.param({"include_ignored": "invalid"}, id="invalid_include_ignored"),
pytest.param({"unknown": True}, id="unknown_arg"),
pytest.param(TOOL_NAME, {"domain": " "}, id="get_issues_whitespace_domain"),
pytest.param(TOOL_NAME, {"domain": []}, id="get_issues_empty_domain_list"),
pytest.param(TOOL_NAME, {"severity": "info"}, id="get_issues_invalid_severity"),
pytest.param(
TOOL_NAME,
{"include_ignored": "invalid"},
id="get_issues_invalid_include_ignored",
),
pytest.param(TOOL_NAME, {"unknown": True}, id="get_issues_unknown_arg"),
pytest.param(
START_FIX_FLOW_TOOL, {"domain": "automation"}, id="start_missing_issue_id"
),
pytest.param(
START_FIX_FLOW_TOOL, {"issue_id": "issue_1"}, id="start_missing_domain"
),
pytest.param(
START_FIX_FLOW_TOOL,
{"domain": " ", "issue_id": "issue_1"},
id="start_whitespace_domain",
),
pytest.param(
START_FIX_FLOW_TOOL,
{"domain": "automation", "issue_id": " "},
id="start_whitespace_issue_id",
),
pytest.param(CONFIGURE_FIX_FLOW_TOOL, {}, id="configure_missing_flow_id"),
pytest.param(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": " "},
id="configure_whitespace_flow_id",
),
pytest.param(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": "flow_1", "user_input": "not_a_dict"},
id="configure_invalid_user_input",
),
pytest.param(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": "flow_1", "next_step_id": " "},
id="configure_whitespace_next_step_id",
),
pytest.param(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": "flow_1", "abort": "not_a_bool"},
id="configure_invalid_abort",
),
],
)
async def test_get_issues_invalid_args(
async def test_invalid_args(
llm_api: llm.APIInstance,
tool_name: str,
invalid_args: JsonObjectType,
) -> None:
"""Test invalid arguments are rejected by the schema."""
"""Test invalid arguments are rejected by the tool schemas."""
with pytest.raises(probatio.Invalid):
await llm_api.async_call_tool(llm.ToolInput(TOOL_NAME, invalid_args))
await llm_api.async_call_tool(llm.ToolInput(tool_name, invalid_args))
async def test_confirm_fix_flow_end_to_end(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
llm_api: llm.APIInstance,
) -> None:
"""Test starting, inspecting, and confirming a default ConfirmRepairFlow."""
ir.async_create_issue(
hass,
"automation",
"service_not_found_morning",
is_fixable=True,
severity=ir.IssueSeverity.ERROR,
translation_key="service_not_found",
translation_placeholders={
"service": "light.turn_on",
"entity_id": "automation.morning",
"name": "Morning",
"edit": "/config/automation/edit/1",
},
)
start_res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": " AUTOMATION ", "issue_id": "service_not_found_morning"},
)
)
assert start_res.error is False
step = start_res.data["result"]
flow_id = step["flow_id"]
assert step["type"] == "form"
assert step["step_id"] == "confirm"
assert step["title"] == "Morning uses an unknown action"
assert "light.turn_on" in step["description"]
assert step["fields"] == []
inspect_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id})
)
assert inspect_res == start_res
confirm_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id, "user_input": {}})
)
assert confirm_res == llm.ToolResult(
data={"result": {"flow_id": flow_id, "type": "create_entry"}}
)
assert (
issue_registry.async_get_issue("automation", "service_not_found_morning")
is None
)
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
@pytest.mark.usefixtures("setup_issues")
@pytest.mark.parametrize(
("domain", "issue_id", "expected_error"),
[
pytest.param(
"domain_a",
"does_not_exist",
"Repair issue 'does_not_exist' for domain 'domain_a' not found.",
id="missing_issue",
),
pytest.param(
"domain_a",
"inactive",
"Repair issue 'inactive' for domain 'domain_a' not found.",
id="inactive_issue",
),
pytest.param(
"domain_a",
"hidden",
"Repair issue 'hidden' for domain 'domain_a' not found.",
id="hidden_issue",
),
pytest.param(
"domain_a",
"warn_1",
"Repair issue 'warn_1' for domain 'domain_a' is not fixable.",
id="not_fixable",
),
],
)
async def test_start_fix_flow_validation_errors(
llm_api: llm.APIInstance,
domain: str,
issue_id: str,
expected_error: str,
) -> None:
"""Test start_fix_flow rejects missing, inactive, hidden, and unfixable issues."""
result = await llm_api.async_call_tool(
llm.ToolInput(START_FIX_FLOW_TOOL, {"domain": domain, "issue_id": issue_id})
)
assert result == llm.ToolResult(data={"error": expected_error}, error=True)
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
@pytest.mark.parametrize(
("exc", "expected_error"),
[
pytest.param(
data_entry_flow.UnknownStep("step missing"),
"Unable to start fix flow for repair issue 'broken_flow' in domain 'domain_a'.",
id="unknown_step",
),
pytest.param(
data_entry_flow.UnknownFlow("flow missing"),
"Unable to start fix flow for repair issue 'broken_flow' in domain 'domain_a'.",
id="unknown_flow",
),
pytest.param(
UnknownEntry("missing_entry_123"),
"Config entry 'missing_entry_123' not found in next_flow.",
id="unknown_entry",
),
],
)
async def test_start_fix_flow_init_errors(
hass: HomeAssistant,
llm_api: llm.APIInstance,
exc: Exception,
expected_error: str,
) -> None:
"""Test start_fix_flow handles exceptions raised by flow_mgr.async_init."""
ir.async_create_issue(
hass,
"domain_a",
"broken_flow",
is_fixable=True,
severity=ir.IssueSeverity.ERROR,
translation_key="broken_flow",
)
with patch.object(
repairs_flow_manager(hass),
"async_init",
side_effect=exc,
):
result = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": "domain_a", "issue_id": "broken_flow"},
)
)
assert result == llm.ToolResult(data={"error": expected_error}, error=True)
class _MenuAndFormFixFlow(RepairsFlow):
"""Test fix flow with a menu step followed by a validated form step."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Show initial menu step."""
return self.async_show_menu(
step_id="init",
menu_options=["configure", "cancel"],
)
async def async_step_configure(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Show form step with validation."""
errors: dict[str, str] = {}
if user_input is not None:
if user_input["target"] == "bad":
errors["target"] = "invalid_target"
else:
return self.async_create_entry(data=user_input)
return self.async_show_form(
step_id="configure",
data_schema=probatio.Schema({probatio.Required("target"): str}),
errors=errors,
)
async def async_step_cancel(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Abort the fix flow."""
return self.async_abort(
reason="cancelled_by_user",
translation_domain="domain_b",
)
def _register_repairs_flow(
hass: HomeAssistant, domain: str, flow_cls: type[RepairsFlow]
) -> None:
"""Register a mock repairs platform returning instances of flow_cls."""
hass.config.components.add(domain)
async def async_create_fix_flow(
hass: HomeAssistant,
issue_id: str,
data: dict[str, str | int | float | None] | None,
) -> RepairsFlow:
return flow_cls()
mock_platform(
hass,
f"{domain}.repairs",
Mock(async_create_fix_flow=async_create_fix_flow),
)
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
@pytest.mark.parametrize(
("step_type", "submit_args"),
[
(data_entry_flow.FlowResultType.FORM, {"user_input": {}}),
(data_entry_flow.FlowResultType.MENU, {"next_step_id": "finish"}),
],
)
async def test_inspect_fix_flow_preserves_pending_step(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
llm_api: llm.APIInstance,
step_type: data_entry_flow.FlowResultType,
submit_args: JsonObjectType,
) -> None:
"""Inspect a stateful repair without advancing it or clearing its issue."""
class StatefulFixFlow(RepairsFlow):
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
if self.cur_step is not None:
return self.async_create_entry(data={})
if step_type is data_entry_flow.FlowResultType.FORM:
return self.async_show_form(
step_id="init", data_schema=probatio.Schema({})
)
return self.async_show_menu(step_id="init", menu_options=["finish"])
async def async_step_finish(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
return self.async_create_entry(data={})
_register_repairs_flow(hass, "domain_a", StatefulFixFlow)
ir.async_create_issue(
hass,
"domain_a",
"stateful_issue",
is_fixable=True,
severity=ir.IssueSeverity.WARNING,
translation_key="stateful_key",
)
start_res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL, {"domain": "domain_a", "issue_id": "stateful_issue"}
)
)
flow_id = start_res.data["result"]["flow_id"]
inspect_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id})
)
assert inspect_res == start_res
assert issue_registry.async_get_issue("domain_a", "stateful_issue") is not None
done_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id, **submit_args})
)
assert done_res.data["result"]["type"] == "create_entry"
assert issue_registry.async_get_issue("domain_a", "stateful_issue") is None
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
async def test_custom_fix_flow_menu_form_and_create_entry(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
llm_context: llm.LLMContext,
llm_api: llm.APIInstance,
) -> None:
"""Test a multi-step custom fix flow with menu, validation errors, and translations."""
llm_context.language = "de"
_register_repairs_flow(hass, "domain_a", _MenuAndFormFixFlow)
ir.async_create_issue(
hass,
"domain_a",
"custom_issue",
is_fixable=True,
severity=ir.IssueSeverity.WARNING,
translation_key="custom_key",
translation_placeholders={"name": "Kitchen"},
)
mock_translations = {
"component.domain_a.issues.custom_key.title": "Fix {name}",
"component.domain_a.issues.custom_key.fix_flow.step.init.menu_options.configure": "Configure {name}",
"component.domain_a.issues.custom_key.fix_flow.step.init.menu_options.cancel": "Cancel",
"component.domain_a.issues.custom_key.fix_flow.step.configure.data.target": "Target device",
"component.domain_a.issues.custom_key.fix_flow.error.invalid_target": "Invalid target for {name}",
"component.domain_a.issues.custom_key.fix_flow.create_entry.default": "Updated {name}",
}
with patch(
"homeassistant.components.repairs.llm.translation.async_get_translations",
return_value=mock_translations,
) as mock_get_translations:
start_res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": "domain_a", "issue_id": "custom_issue"},
)
)
assert start_res.error is False
flow_id = start_res.data["result"]["flow_id"]
assert start_res.data["result"] == {
"flow_id": flow_id,
"type": "menu",
"step_id": "init",
"title": "Fix Kitchen",
"menu_options": {"configure": "Configure Kitchen", "cancel": "Cancel"},
}
mock_get_translations.assert_awaited_with(hass, "de", "issues", {"domain_a"})
both_inputs_res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL,
{
"flow_id": flow_id,
"user_input": {},
"next_step_id": "configure",
},
)
)
assert both_inputs_res.error is True
menu_res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": flow_id, "next_step_id": "configure"},
)
)
assert menu_res.error is False
assert menu_res.data["result"]["type"] == "form"
assert menu_res.data["result"]["step_id"] == "configure"
assert menu_res.data["result"]["title"] == "Fix Kitchen"
assert menu_res.data["result"]["fields"] == [
{
"name": "target",
"required": True,
"type": "string",
"label": "Target device",
}
]
invalid_schema_res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": flow_id, "user_input": {}},
)
)
assert invalid_schema_res.error is True
assert "Invalid input" in invalid_schema_res.data["error"]
err_res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": flow_id, "user_input": {"target": "bad"}},
)
)
assert err_res.error is False
assert err_res.data["result"]["errors"] == {
"target": "Invalid target for Kitchen"
}
done_res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": flow_id, "user_input": {"target": "good"}},
)
)
assert done_res == llm.ToolResult(
data={
"result": {
"flow_id": flow_id,
"type": "create_entry",
"description": "Updated Kitchen",
}
}
)
assert issue_registry.async_get_issue("domain_a", "custom_issue") is None
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
async def test_custom_fix_flow_abort_and_cancel(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
llm_api: llm.APIInstance,
) -> None:
"""Test flow-initiated abort (with translation_domain), user abort, and ignored issues."""
_register_repairs_flow(hass, "domain_a", _MenuAndFormFixFlow)
ir.async_create_issue(
hass,
"domain_a",
"abort_issue",
is_fixable=True,
severity=ir.IssueSeverity.WARNING,
translation_key="abort_key",
)
ir.async_ignore_issue(hass, "domain_a", "abort_issue", True)
mock_translations = {
"component.domain_b.issues.abort_key.fix_flow.abort.cancelled_by_user": "Cancelled",
}
with patch(
"homeassistant.components.repairs.llm.translation.async_get_translations",
return_value=mock_translations,
) as mock_get_translations:
start_res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": "domain_a", "issue_id": "abort_issue"},
)
)
flow_id = start_res.data["result"]["flow_id"]
abort_res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": flow_id, "next_step_id": "cancel"},
)
)
assert abort_res == llm.ToolResult(
data={
"result": {
"flow_id": flow_id,
"type": "abort",
"reason": "cancelled_by_user",
"description": "Cancelled",
}
}
)
mock_get_translations.assert_awaited_with(
hass, "en", "issues", {"domain_a", "domain_b"}
)
assert issue_registry.async_get_issue("domain_a", "abort_issue") is not None
start_res2 = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": "domain_a", "issue_id": "abort_issue"},
)
)
flow_id2 = start_res2.data["result"]["flow_id"]
user_abort_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id2, "abort": True})
)
assert user_abort_res == llm.ToolResult(
data={
"result": {
"flow_id": flow_id2,
"type": "abort",
"reason": "aborted",
}
}
)
assert issue_registry.async_get_issue("domain_a", "abort_issue") is not None
class _ImmediateCompleteFixFlow(RepairsFlow):
"""Test fix flow that completes immediately on init."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Complete immediately."""
return self.async_create_entry(data={})
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
async def test_fix_flow_immediate_create_entry(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
llm_api: llm.APIInstance,
) -> None:
"""Test metadata is captured before async_init when flow completes immediately."""
_register_repairs_flow(hass, "domain_a", _ImmediateCompleteFixFlow)
ir.async_create_issue(
hass,
"domain_a",
"instant_issue",
is_fixable=True,
severity=ir.IssueSeverity.WARNING,
translation_key="instant_key",
translation_placeholders={"item": "Sensor"},
)
mock_translations = {
"component.domain_a.issues.instant_key.fix_flow.create_entry.default": "Fixed {item}",
}
with patch(
"homeassistant.components.repairs.llm.translation.async_get_translations",
return_value=mock_translations,
):
res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": "domain_a", "issue_id": "instant_issue"},
)
)
assert res.error is False
assert res.data["result"]["type"] == "create_entry"
assert res.data["result"]["description"] == "Fixed Sensor"
assert issue_registry.async_get_issue("domain_a", "instant_issue") is None
class _ExternalStepFixFlow(RepairsFlow):
"""Test fix flow that returns an external step on init."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Return an external step."""
return self.async_external_step(
step_id="init", url="https://example.com/repair"
)
class _DelayedExternalStepFixFlow(RepairsFlow):
"""Test fix flow that returns an external step after a form step."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Forward to the confirmation step."""
return await self.async_step_confirm()
async def async_step_confirm(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Show a form step before transitioning to an external step."""
if user_input is not None:
return await self.async_step_auth()
return self.async_show_form(step_id="confirm", data_schema=probatio.Schema({}))
async def async_step_auth(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
"""Return an external step."""
return self.async_external_step(
step_id="auth", url="https://example.com/repair"
)
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
async def test_fix_flow_external_step_rejected_on_start(
hass: HomeAssistant,
llm_api: llm.APIInstance,
) -> None:
"""Test external steps returned by start_fix_flow are aborted with a UI redirect."""
_register_repairs_flow(hass, "domain_a", _ExternalStepFixFlow)
ir.async_create_issue(
hass,
"domain_a",
"ext_issue",
is_fixable=True,
severity=ir.IssueSeverity.ERROR,
translation_key="ext_key",
)
res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL, {"domain": "domain_a", "issue_id": "ext_issue"}
)
)
assert res == llm.ToolResult(
data={
"error": (
"Repair fix flow for 'domain_a/ext_issue' requires browser "
"interaction (external step) and must be completed in the "
"Home Assistant UI at /config/repairs."
),
"frontend_url": "/config/repairs",
},
error=True,
)
assert repairs_flow_manager(hass).async_progress() == []
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
async def test_fix_flow_external_step_rejected_on_configure(
hass: HomeAssistant,
llm_api: llm.APIInstance,
) -> None:
"""Test external steps returned by configure_fix_flow are aborted with a UI redirect."""
_register_repairs_flow(hass, "domain_a", _DelayedExternalStepFixFlow)
ir.async_create_issue(
hass,
"domain_a",
"ext_issue",
is_fixable=True,
severity=ir.IssueSeverity.ERROR,
translation_key="ext_key",
)
start_res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL, {"domain": "domain_a", "issue_id": "ext_issue"}
)
)
assert start_res.error is False
res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL,
{"flow_id": start_res.data["result"]["flow_id"], "user_input": {}},
)
)
assert res == llm.ToolResult(
data={
"error": (
"Repair fix flow for 'domain_a/ext_issue' requires browser "
"interaction (external step) and must be completed in the "
"Home Assistant UI at /config/repairs."
),
"frontend_url": "/config/repairs",
},
error=True,
)
assert repairs_flow_manager(hass).async_progress() == []
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
async def test_fix_flow_progress_step(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
llm_api: llm.APIInstance,
) -> None:
"""Test polling a SHOW_PROGRESS repair fix flow until it completes."""
gate = asyncio.Event()
class _ProgressFixFlow(RepairsFlow):
progress_task: asyncio.Task[None] | None = None
async def _do_work(self) -> None:
await gate.wait()
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
if not self.progress_task:
self.progress_task = self.hass.async_create_task(self._do_work())
if not self.progress_task.done():
return self.async_show_progress(
step_id="init",
progress_action="repairing",
progress_task=self.progress_task,
)
return self.async_show_progress_done(next_step_id="finish")
async def async_step_finish(
self, user_input: dict[str, Any] | None = None
) -> RepairsFlowResult:
return self.async_create_entry(data={})
_register_repairs_flow(hass, "domain_a", _ProgressFixFlow)
ir.async_create_issue(
hass,
"domain_a",
"progress_issue",
is_fixable=True,
severity=ir.IssueSeverity.WARNING,
translation_key="progress_key",
)
mock_translations = {
"component.domain_a.issues.progress_key.fix_flow.progress.repairing": "Repairing...",
"component.domain_a.issues.progress_key.fix_flow.create_entry.default": "Repair complete",
}
with patch(
"homeassistant.components.repairs.llm.translation.async_get_translations",
return_value=mock_translations,
):
start_res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": "domain_a", "issue_id": "progress_issue"},
)
)
flow_id = start_res.data["result"]["flow_id"]
assert start_res.data["result"] == {
"flow_id": flow_id,
"type": "progress",
"step_id": "init",
"progress_action": "repairing",
"description": "Repairing...",
}
poll_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id})
)
assert poll_res == start_res
gate.set()
await hass.async_block_till_done()
done_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id})
)
assert done_res == llm.ToolResult(
data={
"result": {
"flow_id": flow_id,
"type": "create_entry",
"description": "Repair complete",
}
}
)
assert issue_registry.async_get_issue("domain_a", "progress_issue") is None
@pytest.mark.parametrize("ignore_translations_for_mock_domains", [MOCK_DOMAINS])
async def test_configure_fix_flow_errors_and_deleted_issue(
hass: HomeAssistant,
llm_api: llm.APIInstance,
) -> None:
"""Test configure_fix_flow error handling and externally deleted issues."""
missing_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": "unknown-flow"})
)
assert missing_res == llm.ToolResult(
data={"error": "Flow 'unknown-flow' not found."}, error=True
)
ir.async_create_issue(
hass,
"domain_a",
"vanishing_issue",
is_fixable=True,
severity=ir.IssueSeverity.WARNING,
translation_key="vanishing_key",
)
start_res = await llm_api.async_call_tool(
llm.ToolInput(
START_FIX_FLOW_TOOL,
{"domain": "domain_a", "issue_id": "vanishing_issue"},
)
)
flow_id = start_res.data["result"]["flow_id"]
with patch.object(
repairs_flow_manager(hass),
"async_configure",
side_effect=UnknownEntry("missing_entry_456"),
):
unknown_entry_res = await llm_api.async_call_tool(
llm.ToolInput(
CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id, "user_input": {}}
)
)
assert unknown_entry_res == llm.ToolResult(
data={"error": "Config entry 'missing_entry_456' not found in next_flow."},
error=True,
)
ir.async_delete_issue(hass, "domain_a", "vanishing_issue")
inspect_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id})
)
assert inspect_res == llm.ToolResult(
data={
"result": {
"flow_id": flow_id,
"type": "form",
"step_id": "confirm",
"fields": [],
}
}
)
done_res = await llm_api.async_call_tool(
llm.ToolInput(CONFIGURE_FIX_FLOW_TOOL, {"flow_id": flow_id, "user_input": {}})
)
assert done_res == llm.ToolResult(
data={"result": {"flow_id": flow_id, "type": "create_entry"}}
)