From 853ce892eb9984897e079a832422a3a1996eb6ea Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Fri, 29 May 2026 12:30:01 +0200 Subject: [PATCH 1/2] Ignore concatenated template entity fragments --- custom_components/spook/entity_filtering.py | 33 ++++++++++++++----- .../repairs/test_unknown_entity_references.py | 25 ++++++++++++++ 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/custom_components/spook/entity_filtering.py b/custom_components/spook/entity_filtering.py index 6686fbf5de..5c0cb0b4c9 100644 --- a/custom_components/spook/entity_filtering.py +++ b/custom_components/spook/entity_filtering.py @@ -108,6 +108,7 @@ ] # Build regex patterns using Home Assistant's core validation patterns +_STATES_DOMAIN_ENTITY_GROUPS = 2 ENTITY_ID_TEMPLATE_PATTERNS = [ # Template functions with entity ID as first parameter rf"(?:{'|'.join(_ENTITY_FUNCTIONS)})\s*\(\s*['\"]({ENTITY_ID_PATTERN})['\"]", @@ -399,6 +400,24 @@ async def async_extract_entities_from_template_string( return entities +def _is_concatenated_template_match(template_str: str, match: re.Match[str]) -> bool: + """Return if a template regex match is part of a concatenated string.""" + before = template_str[: match.start()].rstrip() + after = template_str[match.end() :].lstrip() + return before.endswith("~") or after.startswith("~") + + +def _entity_id_from_template_match(match: re.Match[str]) -> str: + """Return the entity ID captured by a template regex match.""" + groups = match.groups() + + # Handle the states.domain.entity pattern that captures (domain, object_id) + if len(groups) == _STATES_DOMAIN_ENTITY_GROUPS: + return f"{groups[0]}.{groups[1]}" + + return groups[0] + + def extract_entities_from_template_regex( hass: HomeAssistant, template_str: str ) -> set[str]: @@ -413,17 +432,13 @@ def extract_entities_from_template_regex( return set() entities = set() - # Number of capture groups in states.domain.entity pattern - domain_entity_groups = 2 for pattern in ENTITY_ID_TEMPLATE_PATTERNS: - matches = re.findall(pattern, template_str, re.IGNORECASE) - for match in matches: - # Handle the states.domain.entity pattern that captures (domain, object_id) - if isinstance(match, tuple) and len(match) == domain_entity_groups: - entity_id = f"{match[0]}.{match[1]}" - else: - entity_id = match + for match in re.finditer(pattern, template_str, re.IGNORECASE): + if _is_concatenated_template_match(template_str, match): + continue + + entity_id = _entity_id_from_template_match(match) # For each entity ID (which might be comma-separated), add all valid ones for individual_id in split_comma_separated_entity_ids(entity_id): diff --git a/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py index f3adf66a3c..f4be3697b6 100644 --- a/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py +++ b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py @@ -58,6 +58,22 @@ async def test_value_template_extracts_referenced_entity( assert await extract_entities_from_value(hass, template) == {"light.kitchen"} +async def test_value_template_ignores_concatenated_entity_id_literal( + hass: HomeAssistant, +) -> None: + """Templated entity ID fragments are not complete entity references.""" + template = "{{ 'switch.camera' ~ cam_id ~ '_movies' }}" + assert await extract_entities_from_value(hass, template) == set() + + +async def test_value_template_ignores_concatenated_helper_entity_id( + hass: HomeAssistant, +) -> None: + """Helper calls using templated entity IDs do not expose a static entity.""" + template = "{{ is_state('switch.camera' ~ cam_id ~ '_movies', 'on') }}" + assert await extract_entities_from_value(hass, template) == set() + + async def test_value_non_string_non_collection_returns_empty( hass: HomeAssistant, ) -> None: @@ -162,6 +178,15 @@ async def test_action_target_block(hass: HomeAssistant) -> None: } +async def test_action_target_template_entity_id_fragment(hass: HomeAssistant) -> None: + """A templated ``target.entity_id`` fragment is not treated as an entity.""" + config = { + "action": "switch.turn_on", + "target": {"entity_id": "{{ 'switch.camera' ~ cam_id ~ '_movies' }}"}, + } + assert await extract_entities_from_action_config(hass, config) == set() + + async def test_action_data_dict(hass: HomeAssistant) -> None: """Entities buried inside ``data`` values are captured.""" config = { From 106d0f38cbf5f1be443bd73563640f7d4a4bae1d Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Fri, 29 May 2026 21:10:15 +0200 Subject: [PATCH 2/2] Preserve static concatenated template entities --- custom_components/spook/entity_filtering.py | 19 +++++++++++++++---- .../repairs/test_unknown_entity_references.py | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/custom_components/spook/entity_filtering.py b/custom_components/spook/entity_filtering.py index 5c0cb0b4c9..c8e03ac9e5 100644 --- a/custom_components/spook/entity_filtering.py +++ b/custom_components/spook/entity_filtering.py @@ -401,10 +401,21 @@ async def async_extract_entities_from_template_string( def _is_concatenated_template_match(template_str: str, match: re.Match[str]) -> bool: - """Return if a template regex match is part of a concatenated string.""" - before = template_str[: match.start()].rstrip() - after = template_str[match.end() :].lstrip() - return before.endswith("~") or after.startswith("~") + """Return if a quoted entity ID literal is part of a concatenated string.""" + groups = match.groups() + if len(groups) == _STATES_DOMAIN_ENTITY_GROUPS: + return False + + entity_start, entity_end = match.span(1) + before_entity = template_str[:entity_start].rstrip() + after_entity = template_str[entity_end:].lstrip() + + if not (before_entity.endswith(("'", '"')) and after_entity.startswith(("'", '"'))): + return False + + before_literal = before_entity[:-1].rstrip() + after_literal = after_entity[1:].lstrip() + return before_literal.endswith("~") or after_literal.startswith("~") def _entity_id_from_template_match(match: re.Match[str]) -> str: diff --git a/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py index f4be3697b6..58cfaa9396 100644 --- a/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py +++ b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py @@ -74,6 +74,22 @@ async def test_value_template_ignores_concatenated_helper_entity_id( assert await extract_entities_from_value(hass, template) == set() +async def test_value_template_keeps_concatenated_state_value( + hass: HomeAssistant, +) -> None: + """Concatenated values still expose static entity references.""" + template = "{{ states.light.kitchen.state ~ '_suffix' }}" + assert await extract_entities_from_value(hass, template) == {"light.kitchen"} + + +async def test_value_template_keeps_concatenated_filtered_entity( + hass: HomeAssistant, +) -> None: + """Filtered entity references are kept when their value is concatenated.""" + template = "{{ 'prefix' ~ ('light.kitchen' | states) }}" + assert await extract_entities_from_value(hass, template) == {"light.kitchen"} + + async def test_value_non_string_non_collection_returns_empty( hass: HomeAssistant, ) -> None: