Home Information - Your home, your data, organized.
Python
Issue #281: Auto-reconnect disconnected entities; structured detached/reconnected sync results (#289)
Tony Cd890f7100fad
diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_entity_toggle.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_entity_toggle.htmlindex 1fe0dd5b..9c6987c6 100644--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_entity_toggle.html+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_entity_toggle.html@@ -1,4 +1,4 @@-{% load integration_tags %}+{% load integration_tags static %}<div id="hi-entity-toggle-collection-{{ entity.id }}"class="{{ DIVID.ENTITY_PICKER_FILTERABLE_ITEM_CLASS }} entity-item-row{% if is_unused %} unused{% elif exists_in_collection %} in-view{% endif %}"data-entity-id="{{ entity.id }}"@@ -16,7 +16,11 @@{% if exists_in_collection %}checked{% endif %}onchange-async="true" ><label for="entity-toggle-collection-checkbox-{{ entity.id }}" class="entity-item-label">- {{ entity.name }} <span class="entity-item-id">[{% integration_display_name entity %}]</span>+ {{ entity.name }}+ {% if entity.integration_id %}+ {% integration_logo_path entity as logo_path %}+ {% if logo_path %}<img src="{% static logo_path %}" class="hi-integration-logo--inline ml-1" alt="{% integration_display_name entity %}" title="{% integration_display_name entity %}">{% endif %}+ {% endif %}</label></form></div>diff --git a/src/hi/apps/control/migrations/0005_add_previous_integration_identity.py b/src/hi/apps/control/migrations/0005_add_previous_integration_identity.pynew file mode 100644index 00000000..56675df1--- /dev/null+++ b/src/hi/apps/control/migrations/0005_add_previous_integration_identity.py@@ -0,0 +1,34 @@+# Generated by Django 4.2.24 on 2026-05-05 02:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("control", "0004_alter_controller_integration_payload"),+ ]++ operations = [+ migrations.AddField(+ model_name="controller",+ name="previous_integration_id",+ field=models.CharField(+ blank=True,+ db_index=True,+ max_length=32,+ null=True,+ verbose_name="Previous Integration Id",+ ),+ ),+ migrations.AddField(+ model_name="controller",+ name="previous_integration_name",+ field=models.CharField(+ blank=True,+ max_length=128,+ null=True,+ verbose_name="Previous Integration Name",+ ),+ ),+ ]diff --git a/src/hi/apps/entity/admin.py b/src/hi/apps/entity/admin.pyindex a6c99572..d3f08487 100644--- a/src/hi/apps/entity/admin.py+++ b/src/hi/apps/entity/admin.py@@ -75,11 +75,14 @@ class EntityAdmin(admin.ModelAdmin):'entity_type_str','integration_id','integration_name',+ 'previous_integration_id',+ 'previous_integration_name','is_disabled','created_datetime',)- search_fields = ['name']+ list_filter = ( 'integration_id', 'previous_integration_id', 'is_disabled', )+ search_fields = ['name', 'integration_name', 'previous_integration_name']inlines = [EntityAttributeInLine,diff --git a/src/hi/apps/entity/migrations/0015_add_previous_integration_identity.py b/src/hi/apps/entity/migrations/0015_add_previous_integration_identity.pynew file mode 100644index 00000000..695bf9fc--- /dev/null+++ b/src/hi/apps/entity/migrations/0015_add_previous_integration_identity.py@@ -0,0 +1,34 @@+# Generated by Django 4.2.24 on 2026-05-05 02:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0014_add_entity_is_disabled"),+ ]++ operations = [+ migrations.AddField(+ model_name="entity",+ name="previous_integration_id",+ field=models.CharField(+ blank=True,+ db_index=True,+ max_length=32,+ null=True,+ verbose_name="Previous Integration Id",+ ),+ ),+ migrations.AddField(+ model_name="entity",+ name="previous_integration_name",+ field=models.CharField(+ blank=True,+ max_length=128,+ null=True,+ verbose_name="Previous Integration Name",+ ),+ ),+ ]diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.htmlindex d1974f73..630e5e9e 100644--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html@@ -14,10 +14,18 @@<div class="my-2"><div class="text-muted">{% integration_logo_path entity as logo_path %}- {% if logo_path %}<img src="{% static logo_path %}" alt="" style="max-height: 18px; width: auto; margin-right: 4px;">{% endif %}+ {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}From: <strong>{% integration_display_name entity %}</strong></div></div>+{% elif entity.previous_integration_id %}+<div class="my-2">+ <div class="text-muted font-italic">+ {% previous_integration_logo_path entity as prev_logo_path %}+ {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}+ Detached from: <strong>{% previous_integration_display_name entity %}</strong>+ </div>+</div>{% endif %}<div id="{{ DIVID.ENTITY_PROPERTIES_PANE }}">diff --git a/src/hi/apps/entity/templates/entity/modals/entity_edit.html b/src/hi/apps/entity/templates/entity/modals/entity_edit.htmlindex c1596c4d..0dbfcc53 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_edit.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_edit.html@@ -10,10 +10,18 @@<div class="text-muted text-center"><small>{% integration_logo_path entity as logo_path %}- {% if logo_path %}<img src="{% static logo_path %}" alt="" style="max-height: 18px; width: auto; margin-right: 4px;">{% endif %}+ {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}From: {% integration_display_name entity %}</small></div>+{% elif entity.previous_integration_id %}+<div class="text-muted text-center font-italic">+ <small>+ {% previous_integration_logo_path entity as prev_logo_path %}+ {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}+ Detached from: {% previous_integration_display_name entity %}+ </small>+</div>{% endif %}<!-- Root container for this attribute editing context --><div id="{{ attr_page_context.container_html_id }}"diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status.html b/src/hi/apps/entity/templates/entity/modals/entity_status.htmlindex 60289f9e..d4da42ed 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html@@ -22,10 +22,18 @@ Status<div class="text-muted"><small>{% integration_logo_path entity as logo_path %}- {% if logo_path %}<img src="{% static logo_path %}" alt="" style="max-height: 18px; width: auto; margin-right: 4px;">{% endif %}+ {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}From: {% integration_display_name entity %}</small></div>+ {% elif entity.previous_integration_id %}+ <div class="text-muted font-italic">+ <small>+ {% previous_integration_logo_path entity as prev_logo_path %}+ {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}+ Detached from: {% previous_integration_display_name entity %}+ </small>+ </div>{% endif %}</div><div>diff --git a/src/hi/apps/event/migrations/0006_add_previous_integration_identity.py b/src/hi/apps/event/migrations/0006_add_previous_integration_identity.pynew file mode 100644index 00000000..748fe7d8--- /dev/null+++ b/src/hi/apps/event/migrations/0006_add_previous_integration_identity.py@@ -0,0 +1,34 @@+# Generated by Django 4.2.24 on 2026-05-05 02:19++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("event", "0005_alter_eventclause_options_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="eventdefinition",+ name="previous_integration_id",+ field=models.CharField(+ blank=True,+ db_index=True,+ max_length=32,+ null=True,+ verbose_name="Previous Integration Id",+ ),+ ),+ migrations.AddField(+ model_name="eventdefinition",+ name="previous_integration_name",+ field=models.CharField(+ blank=True,+ max_length=128,+ null=True,+ verbose_name="Previous Integration Name",+ ),+ ),+ ]diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_entity_toggle.html b/src/hi/apps/location/templates/location/edit/panes/location_view_entity_toggle.htmlindex 8006d015..19020a41 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_view_entity_toggle.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_entity_toggle.html@@ -1,4 +1,4 @@-{% load integration_tags %}+{% load integration_tags static %}<div id="hi-entity-toggle-location-{{ entity.id }}"class="{{ DIVID.ENTITY_PICKER_FILTERABLE_ITEM_CLASS }} entity-item-row{% if is_unused %} unused{% elif exists_in_view %} in-view{% endif %}"data-entity-id="{{ entity.id }}"@@ -16,7 +16,11 @@{% if exists_in_view %}checked{% endif %}onchange-async="true" ><label for="entity-toggle-location-checkbox-{{ entity.id }}" class="entity-item-label">- {{ entity.name }} <span class="entity-item-id">[{% integration_display_name entity %}]</span>+ {{ entity.name }}+ {% if entity.integration_id %}+ {% integration_logo_path entity as logo_path %}+ {% if logo_path %}<img src="{% static logo_path %}" class="hi-integration-logo--inline ml-1" alt="{% integration_display_name entity %}" title="{% integration_display_name entity %}">{% endif %}+ {% endif %}</label></form></div>diff --git a/src/hi/apps/sense/migrations/0011_add_previous_integration_identity.py b/src/hi/apps/sense/migrations/0011_add_previous_integration_identity.pynew file mode 100644index 00000000..fc51bbf8--- /dev/null+++ b/src/hi/apps/sense/migrations/0011_add_previous_integration_identity.py@@ -0,0 +1,34 @@+# Generated by Django 4.2.24 on 2026-05-05 02:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("sense", "0010_replace_duration_with_correlation_fields"),+ ]++ operations = [+ migrations.AddField(+ model_name="sensor",+ name="previous_integration_id",+ field=models.CharField(+ blank=True,+ db_index=True,+ max_length=32,+ null=True,+ verbose_name="Previous Integration Id",+ ),+ ),+ migrations.AddField(+ model_name="sensor",+ name="previous_integration_name",+ field=models.CharField(+ blank=True,+ max_length=128,+ null=True,+ verbose_name="Previous Integration Name",+ ),+ ),+ ]diff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/entity_operations.pyindex 9fb4daec..3e4cbc9c 100644--- a/src/hi/integrations/entity_operations.py+++ b/src/hi/integrations/entity_operations.py@@ -7,7 +7,7 @@ are distinct from the read-only analytical methods on EntityUserDataDetector."""import logging-from typing import Dict, Iterable, Optional, Set+from typing import Dict, Iterable, List, Optional, Setfrom django.db import transaction@@ -17,7 +17,7 @@ from hi.apps.sense.models import Sensorfrom hi.apps.control.models import Controllerfrom .sync_result import IntegrationSyncResult-from .transient_models import IntegrationRemovalSummary+from .transient_models import IntegrationKey, IntegrationRemovalSummaryfrom .user_data_detector import EntityUserDataDetectorlogger = logging.getLogger(__name__)@@ -121,16 +121,19 @@ class EntityIntegrationOperations:* ``preserve_user_data=True`` (the SAFE pattern, used byDELETE SAFE on disable and by sync-time refreshremovals): entities carrying operator-added attributes- are preserved via ``[Disconnected]`` rename; others are- hard-deleted.+ are detached from the integration (active integration+ identity cleared, previous identity recorded for the+ auto-reconnect path); others are hard-deleted.* ``preserve_user_data=False`` (the DELETE ALL pattern):every entity in the closure is hard-deleted, includingthose with user-added data.``result`` is optional. When provided, each closure entity's- name is appended to ``result.removed_list``; the preserve- path also adds its diagnostic note to ``result.info_list``.+ name is appended to either ``result.removed_list`` (the+ hard-delete branch) or ``result.detached_list`` (the+ preserve branch) — never both. The preserve branch also+ adds its diagnostic note to ``result.info_list``.Each entity in the closure is classified by its *own* userdata, independent of the seed's classification. This@@ -142,15 +145,17 @@ class EntityIntegrationOperations:"""closure_ids = cls.collect_removal_closure( seed_entity_ids )for entity in Entity.objects.filter( id__in = closure_ids ):- if result is not None:- result.removed_list.append( entity.name )if preserve_user_data and EntityUserDataDetector.has_user_created_attributes( entity ):+ # preserve_with_user_data appends to result.detached_list+ # itself; nothing to record here on this branch.cls.preserve_with_user_data(entity = entity,integration_name = integration_name,result = result,)else:+ if result is not None:+ result.removed_list.append( entity.name )entity.delete()return@@ -176,15 +181,103 @@ class EntityIntegrationOperations:user_data_count = user_data_count,)+ @classmethod+ def find_reconnect_candidates(+ cls,+ integration_id : str,+ upstream_keys : Iterable[ IntegrationKey ],+ result : Optional[ IntegrationSyncResult ] = None,+ ) -> Dict[ IntegrationKey, Entity ]:+ """+ Auto-reconnect candidate lookup (Issue #281). Pure read.++ Given a set of upstream IntegrationKeys that the+ synchronizer's primary-match step did NOT match, return a+ map of ``upstream_key → matching disconnected entity`` for+ every key that uniquely aligns with a disconnected entity's+ ``previous_integration_id`` / ``previous_integration_name``.++ Ambiguous matches (multiple disconnected entities sharing+ the same previous identity) are dropped from the result map.+ The issue's contract is to leave the duplicate for the user+ to resolve via merge (#263), since the system has no basis+ to pick one side over the other. A WARNING is logged and a+ breadcrumb is appended to ``result.info_list`` (when+ provided) for each ambiguous case so the operator can find+ them.++ The per-entity reconnect mutations and converter dispatch+ are deliberately NOT performed here. Callers (the+ per-integration synchronizers) own that step because each+ integration's converter has a different signature and+ callers also want to enrich ``result`` with their own+ operator-facing messages. ``strip_disconnected_prefix`` is+ provided as a shared helper for the name-cleanup step.++ The lookup is a single batched DB query keyed on+ ``(previous_integration_id, previous_integration_name__in=...)``+ — O(1) DB round trips regardless of how many upstream keys+ the caller passes.+ """+ upstream_keys = list( upstream_keys )+ if not upstream_keys:+ return {}++ upstream_keys_by_name : Dict[ str, IntegrationKey ] = {+ key.integration_name: key for key in upstream_keys+ }++ candidate_entities = Entity.objects.filter(+ previous_integration_id = integration_id,+ previous_integration_name__in = list( upstream_keys_by_name.keys() ),+ )++ candidates_by_name : Dict[ str, List[ Entity ] ] = {}+ for entity in candidate_entities:+ candidates_by_name.setdefault(+ entity.previous_integration_name, [],+ ).append( entity )++ reconnect_map : Dict[ IntegrationKey, Entity ] = {}+ for previous_name, entities in candidates_by_name.items():+ upstream_key = upstream_keys_by_name.get( previous_name )+ # Defensive: the IN-filter guarantees previous_name is in+ # the dict, but a corrupted row could slip through.+ if upstream_key is None:+ continue++ if len( entities ) > 1:+ ambiguity_message = (+ f'Auto-reconnect skipped for {integration_id} item '+ f'"{previous_name}": {len(entities)} disconnected '+ f'entities share that previous identity. Resolve via '+ f'merge.'+ )+ logger.warning( ambiguity_message )+ if result is not None:+ result.info_list.append( ambiguity_message )+ continue++ reconnect_map[ upstream_key ] = entities[0]++ return reconnect_map+@staticmethoddef preserve_with_user_data( entity : Entity,integration_name : str,result : Optional[IntegrationSyncResult] = None ):"""- Preserve an entity with user-created data by disconnecting it from- its integration and removing only integration-related components- (sensors, controllers, orphaned states, integration-owned- attributes). Applies the '[Disconnected]' name prefix.+ Preserve an entity with user-created data by disconnecting it+ from its integration and removing only integration-related+ components (sensors, controllers, orphaned states,+ integration-owned attributes). The entity's previous+ integration identity is recorded on the entity so the+ auto-reconnect path can recognize it if the same upstream+ key reappears later. The detached state is signaled+ structurally — ``integration_id`` becomes NULL and+ ``previous_integration_id`` carries the prior identity — and+ surfaced to the operator via a "Detached from <integration>"+ badge in the entity-detail UI.Args:entity: The Entity to preserve.@@ -238,13 +331,18 @@ class EntityIntegrationOperations:if removed_attr_count:logger.debug(f'Removed {removed_attr_count} integration attributes for {entity}')- # Disconnect entity from integration- entity.integration_id = None- entity.integration_name = None+ # Disconnect entity from integration. The current integration+ # identity is copied to the previous_integration_* fields+ # so the auto-reconnect path can recognize this entity if+ # the same upstream key reappears later. The presence of+ # previous_integration_id is also what drives the+ # "Detached from <integration>" UI badge.+ entity.previous_integration_key = entity.integration_key+ entity.integration_key = None# Restore user-management flags. These are commonly set to False# by integration converters to prevent the user from deleting or- # extending an integration-managed entity. After disconnect the+ # extending an integration-managed entity. After detach the# entity is no longer integration-managed, so user-management# rights are restored.entity.can_user_delete = True@@ -254,19 +352,20 @@ class EntityIntegrationOperations:# video-stream capability is genuinely lost (the backing sensor# was deleted above). The is_disabled flag is the general# capability gate — listing/enumeration sites use it to keep- # a disconnected entity out of capability-driven UX (e.g., the+ # a detached entity out of capability-driven UX (e.g., the# sidebar Cameras list).entity.has_video_stream = Falseentity.is_disabled = True- # Update name to indicate disconnected status- if not entity.name.startswith('[Disconnected]'):- entity.name = f'[Disconnected] {entity.name}'-entity.save()if result is not None:+ # detached_list drives the operator-visible "Detached"+ # tile + per-category list in the sync result modal;+ # info_list keeps the diagnostic note for the collapsed+ # Details section.+ result.detached_list.append( entity.name )result.info_list.append(- f'Preserved {integration_name} item "{original_name}" with user data, '- f'disconnected from integration and renamed to "{entity.name}"'+ f'Preserved {integration_name} item "{original_name}" with user data; '+ f'detached from integration.')diff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.pyindex 4314f3ad..9e93750a 100644--- a/src/hi/integrations/enums.py+++ b/src/hi/integrations/enums.py@@ -10,9 +10,11 @@ class IntegrationDisableMode( LabeledEnum ):integration's attached entities are handled.SAFE — delete entities without user-created data; preserve entities with- user-created data by disconnecting them (strips integration association,- removes integration-only components, applies '[Disconnected]' name- prefix). This mirrors the sync-time preservation behavior.+ user-created data by detaching them from the integration (strips+ integration association, removes integration-only components, records+ the previous integration identity to drive the "Detached from ..."+ UI badge and the auto-reconnect path). This mirrors the sync-time+ preservation behavior.ALL — hard-delete all entities attached to the integration regardless ofuser-created data.diff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.pyindex 65ffbf53..1fc085fc 100644--- a/src/hi/integrations/integration_manager.py+++ b/src/hi/integrations/integration_manager.py@@ -413,7 +413,9 @@ class IntegrationManager( Singleton ):SAFE (default): delete entities without user-created data; preserveentities with user-created data by detaching them from theintegration (via EntityIntegrationOperations.preserve_with_user_data).- Preserved entities get the '[Disconnected]' name prefix.+ Preserved entities surface as "Detached from <integration>" in+ the entity-detail UI and become candidates for the auto-reconnect+ path on a subsequent re-Configure + sync.ALL: hard-delete all entities attached to this integrationregardless of user data.diff --git a/src/hi/integrations/integration_synchronizer.py b/src/hi/integrations/integration_synchronizer.pyindex b5e9f4a0..d3a2191c 100644--- a/src/hi/integrations/integration_synchronizer.py+++ b/src/hi/integrations/integration_synchronizer.py@@ -13,7 +13,9 @@ Sync is opt-in: a gateway whose integration does not support syncreturns None."""import logging-from typing import List, Optional+from typing import Any, Dict, List, Optional++from django.db import transactionfrom hi.apps.common.database_lock import ExclusionLockContextfrom hi.apps.entity.entity_placement import (@@ -24,6 +26,7 @@ from hi.apps.entity.models import Entityfrom .entity_operations import EntityIntegrationOperationsfrom .sync_result import IntegrationSyncResult+from .transient_models import IntegrationKey, IntegrationMetaDatalogger = logging.getLogger(__name__)@@ -109,6 +112,20 @@ class IntegrationSynchronizer:"""raise NotImplementedError('Subclasses must override this method')+ def get_integration_metadata(self) -> IntegrationMetaData:+ """+ Subclasses return their integration's ``IntegrationMetaData``+ constant (the same object the gateway exposes via+ ``get_metadata()``). The framework reads ``.integration_id``+ and ``.label`` from it for shared operations like the+ auto-reconnect pre-pass and the entity-removal helper, so+ each subclass declares the source of truth in one place+ instead of repeating the values at every call site.+ """+ raise NotImplementedError(+ f'{self.__class__.__name__} must override get_integration_metadata()'+ )+def group_entities_for_placement(self, entities : List[Entity],) -> EntityPlacementInput:@@ -153,10 +170,139 @@ class IntegrationSynchronizer:return f'{integration_key.integration_id}:{integration_key.integration_name}'return f'entity:{entity.id}'+ def reconnect_disconnected_items(+ self,+ integration_key_to_upstream : Dict[ IntegrationKey, Any ],+ integration_key_to_entity : Dict[ IntegrationKey, Entity ],+ result : IntegrationSyncResult ):+ """+ Framework-level auto-reconnect (Issue #281). Symmetric to+ the framework-level disconnect path+ (``EntityIntegrationOperations.preserve_with_user_data``):+ both directions of the cycle live in shared code, with each+ integration contributing only the minimal piece that's+ genuinely integration-specific — the converter dispatch via+ ``_rebuild_integration_components()``.++ For each unmatched upstream key with a unique secondary+ match, this method:++ * clears the previous-identity columns (which removes the+ "Detached from <integration>" badge in the UI),+ * dispatches to ``_rebuild_integration_components()`` so the+ integration's converter repopulates the integration-owned+ components on the existing entity,+ * appends the entity name to ``result.reconnected_list``+ (which drives the "Reconnected" tile + per-category list+ in the sync result modal) and to ``result.info_list``+ (the diagnostic Details section),+ * inserts the reconnected entity into+ ``integration_key_to_entity`` so the synchronizer's main+ loop sees it as primary-matched and gives it the standard+ update / attribute-sync treatment without any+ reconnect-specific branching.++ The entity's ``name`` is deliberately not touched: the user+ may have edited it before or after the intervening detach,+ and the detached/connected distinction is signaled+ structurally via the integration_id / previous_integration_id+ columns rather than by a name-string convention.++ Ambiguous secondary matches are handled inside+ ``find_reconnect_candidates``: dropped silently, with a+ WARNING log + ``info_list`` breadcrumb so the operator can+ find them and resolve via merge (#263).+ """+ unmatched_upstream_keys = [+ integration_key for integration_key in integration_key_to_upstream+ if integration_key not in integration_key_to_entity+ ]+ if not unmatched_upstream_keys:+ return++ metadata = self.get_integration_metadata()+ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id = metadata.integration_id,+ upstream_keys = unmatched_upstream_keys,+ result = result,+ )+ if not candidates:+ return++ for upstream_key, entity in candidates.items():+ # Wrap each reconnect in its own atomic boundary so a+ # mid-batch converter failure rolls back that single+ # entity's changes (including the cleared previous+ # identity) without aborting reconnects already+ # committed for prior entities. The result-list appends+ # are inside the boundary so they stay consistent with+ # the persisted state.+ with transaction.atomic():+ entity.previous_integration_key = None+ self._rebuild_integration_components(+ entity = entity,+ upstream = integration_key_to_upstream[ upstream_key ],+ result = result,+ )+ # The disconnect path set is_disabled=True (the+ # capability gate that hides detached entities from+ # listings like the Cameras sidebar). Reconnect is+ # the symmetric clear: the entity is integration-+ # attached again and should participate in those+ # listings. Capability flags like has_video_stream+ # are converter-owned and should already have been+ # re-established by _rebuild_integration_components.+ entity.is_disabled = False+ # Defensive save: subclasses' converters typically+ # save the entity themselves, but the framework+ # explicitly persists the cleared previous-identity+ # and is_disabled fields so a future converter that+ # only writes related rows cannot leave the entity+ # in a half-reconnected state.+ entity.save(+ update_fields = [+ 'previous_integration_id',+ 'previous_integration_name',+ 'is_disabled',+ ],+ )+ # reconnected_list drives the operator-visible+ # "Reconnected" tile + per-category list in the+ # sync result modal; info_list keeps the same name+ # in the diagnostic Details section so the operator+ # sees a consistent record across both surfaces.+ result.reconnected_list.append( entity.name )+ result.info_list.append(+ f'Auto-reconnected {metadata.label} item "{entity.name}"'+ )+ integration_key_to_entity[ upstream_key ] = entity+ return++ def _rebuild_integration_components( self,+ entity : Entity,+ upstream : Any,+ result : IntegrationSyncResult ):+ """+ Subclass hook for the auto-reconnect (Issue #281) path. Given+ an existing Entity (the previously-disconnected one) and the+ upstream payload for it, repopulate the entity's+ integration-owned components by dispatching to the+ integration's converter with the existing-entity parameter set.++ The base class raises NotImplementedError; subclasses must+ override to participate in auto-reconnect. (Reconnect is+ framework-driven; the only piece each integration owns is+ this thin converter-dispatch override.)+ """+ raise NotImplementedError(+ f'{self.__class__.__name__} must override '+ f'_rebuild_integration_components() to participate in '+ f'auto-reconnect.'+ )+def _remove_entity_intelligently(self,entity: Entity,- result: IntegrationSyncResult,- integration_name: str):+ result: IntegrationSyncResult):"""Remove an entity that no longer exists in the integration.@@ -165,13 +311,12 @@ class IntegrationSynchronizer:closure walk picks up delegate entities (e.g., the Areaauto-created when a camera was placed in a view) when theironly remaining principal is being removed. Operator-added- attributes on any closure entity trigger the- ``[Disconnected]`` preserve path; otherwise the entity is- hard-deleted.+ attributes on any closure entity trigger the detach-and-preserve+ path; otherwise the entity is hard-deleted."""EntityIntegrationOperations.remove_entities_with_closure(seed_entity_ids = { entity.id },- integration_name = integration_name,+ integration_name = self.get_integration_metadata().label,preserve_user_data = True,result = result,)diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.pyindex 8e756ceb..3f36ce37 100644--- a/src/hi/integrations/models.py+++ b/src/hi/integrations/models.py@@ -108,9 +108,34 @@ class IntegrationDetailsModel( models.Model ):blank = True,help_text = 'Integration-specific data (e.g., HA domain, device capabilities)',)+ # The previous_integration_* fields record the integration identity+ # an instance had at the moment it was disconnected (e.g., via+ # sync-time preservation or Disable-SAFE). They drive the+ # auto-reconnect path in IntegrationSynchronizer: when an upstream+ # entity reappears whose key matches a disconnected entity's+ # previous identity, the entity is reconnected rather than a+ # duplicate being created. The previous_integration_id is indexed+ # because the secondary-match query during sync filters on it.+ previous_integration_id = models.CharField(+ 'Previous Integration Id',+ max_length = 32,+ null = True, blank = True,+ db_index = True,+ )+ previous_integration_name = models.CharField(+ 'Previous Integration Name',+ max_length = 128,+ null = True, blank = True,+ )@propertydef integration_key(self) -> IntegrationKey:+ # Symmetric with the setter: returns None when the underlying+ # fields are unset, so reading the property on a never-attached+ # or already-disconnected instance is safe (and round-trips+ # cleanly through the setter as a no-op clear).+ if self.integration_id is None or self.integration_name is None:+ return Nonereturn IntegrationKey(integration_id = self.integration_id,integration_name = self.integration_name,@@ -121,10 +146,39 @@ class IntegrationDetailsModel( models.Model ):if not integration_key:self.integration_id = Noneself.integration_name = None- return+ returnself.integration_id = integration_key.integration_idself.integration_name = integration_key.integration_name- return+ # Re-attaching to an active integration invalidates any+ # prior detached-state record. Clearing here is defensive+ # against future call sites that set integration_key+ # without going through reconnect_disconnected_items: a+ # stale previous_integration_* pair on an active entity+ # would mis-trigger the "Detached from" UI badge and+ # confuse any future query that filters disconnected+ # entities by previous_integration_id alone.+ self.previous_integration_id = None+ self.previous_integration_name = None+ return++ @property+ def previous_integration_key(self) -> IntegrationKey:+ if self.previous_integration_id is None or self.previous_integration_name is None:+ return None+ return IntegrationKey(+ integration_id = self.previous_integration_id,+ integration_name = self.previous_integration_name,+ )++ @previous_integration_key.setter+ def previous_integration_key( self, integration_key : IntegrationKey ):+ if not integration_key:+ self.previous_integration_id = None+ self.previous_integration_name = None+ return+ self.previous_integration_id = integration_key.integration_id+ self.previous_integration_name = integration_key.integration_name+ returndef get_integration_details(self) -> IntegrationDetails:return IntegrationDetails(diff --git a/src/hi/integrations/sync_result.py b/src/hi/integrations/sync_result.pyindex 18b9d578..43c3e8ba 100644--- a/src/hi/integrations/sync_result.py+++ b/src/hi/integrations/sync_result.py@@ -41,23 +41,43 @@ class IntegrationSyncResult:not emptiness checks against groups/ungrouped_items — to decidewhether to show the placement.- ``created_list`` / ``updated_list`` / ``removed_list`` hold the- *names* of entities affected by this sync run, populated by the- per-integration synchronizer as it walks upstream items. The- result modal uses list length for the count badges and the- list contents for per-category "Show items" disclosures so the- operator can see which entities were touched. Names only —- per-attribute change detail is intentionally not surfaced.+ ``created_list`` / ``updated_list`` / ``reconnected_list`` /+ ``detached_list`` / ``removed_list`` hold the *names* of entities+ affected by this sync run, populated by the per-integration+ synchronizer as it walks upstream items. The result modal uses+ list length for the count badges and the list contents for+ per-category "Show items" disclosures so the operator can see+ which entities were touched. Names only — per-attribute change+ detail is intentionally not surfaced.++ The five categories are mutually exclusive for any given entity+ in a single sync run:+ * ``created_list`` — brand new entities this sync.+ * ``updated_list`` — existing primary-matched entities+ whose payload changed.+ * ``reconnected_list`` — previously-detached entities that+ were re-attached this sync (Issue+ #281 auto-reconnect).+ * ``detached_list`` — entities preserved with user data on+ this sync (sync-time preservation+ or Disable-SAFE). They retain their+ custom attributes / layout / etc.+ and surface in the UI as "Detached+ from <integration>".+ * ``removed_list`` — entities hard-deleted this sync.``info_list`` carries diagnostic notes — "Found N upstream- items", "Filtered N by allowlist" — that the per-item lists- can't express. Rendered as a collapsible Details section in- the result modal. ``error_list`` is the parallel for failures.+ items", "Filtered N by allowlist", ambiguous-reconnect+ breadcrumbs — that the per-item lists can't express. Rendered+ as a collapsible Details section in the result modal.+ ``error_list`` is the parallel for failures."""title: strplacement_input: Optional[EntityPlacementInput] = Nonecreated_list: List[str] = field(default_factory=list)updated_list: List[str] = field(default_factory=list)+ reconnected_list: List[str] = field(default_factory=list)+ detached_list: List[str] = field(default_factory=list)removed_list: List[str] = field(default_factory=list)info_list: List[str] = field(default_factory=list)error_list: List[str] = field(default_factory=list)@@ -70,5 +90,7 @@ class IntegrationSyncResult:return bool(self.created_listor self.updated_list+ or self.reconnected_list+ or self.detached_listor self.removed_list)diff --git a/src/hi/integrations/templates/integrations/modals/integration_disable.html b/src/hi/integrations/templates/integrations/modals/integration_disable.htmlindex 8684250d..34ef00a4 100644--- a/src/hi/integrations/templates/integrations/modals/integration_disable.html+++ b/src/hi/integrations/templates/integrations/modals/integration_disable.html@@ -32,8 +32,9 @@<strong>DELETE SAFE</strong> — delete the {{ removal_summary.deletable_count }}{% if removal_summary.deletable_count == 1 %}item{% else %}items{% endif %}without custom data, and preserve the {{ removal_summary.user_data_count }} with custom- data (disconnected from this integration, prefixed with- <code>[Disconnected]</code>, custom attributes and layout retained).+ data (detached from this integration; the items will show as+ <em>Detached from {{ integration_data.label }}</em> in the entity-detail UI,+ with custom attributes and layout retained).</li><li><strong>DELETE ALL</strong> — delete all {{ removal_summary.total_count }}diff --git a/src/hi/integrations/templates/integrations/modals/sync_result.html b/src/hi/integrations/templates/integrations/modals/sync_result.htmlindex 14f2336f..f2e25a39 100644--- a/src/hi/integrations/templates/integrations/modals/sync_result.html+++ b/src/hi/integrations/templates/integrations/modals/sync_result.html@@ -104,7 +104,7 @@item lists. Only non-zero categories render — symmetry is lessimportant than not implying a third stat that doesn't exist.{% endcomment %}- <div class="d-flex justify-content-around text-center mb-4 pb-3 border-bottom">+ <div class="d-flex justify-content-around flex-wrap text-center mb-4 pb-3 border-bottom">{% if sync_result.created_list %}<div class="px-3"><div class="text-success font-weight-bold hi-sync-result-stat-number">@@ -121,9 +121,25 @@<div class="text-muted small text-uppercase hi-uppercase-label">Updated</div></div>{% endif %}- {% if sync_result.removed_list %}+ {% if sync_result.reconnected_list %}+ <div class="px-3">+ <div class="text-info font-weight-bold hi-sync-result-stat-number">+ {{ sync_result.reconnected_list|length }}+ </div>+ <div class="text-muted small text-uppercase hi-uppercase-label">Reconnected</div>+ </div>+ {% endif %}+ {% if sync_result.detached_list %}<div class="px-3"><div class="text-secondary font-weight-bold hi-sync-result-stat-number">+ {{ sync_result.detached_list|length }}+ </div>+ <div class="text-muted small text-uppercase hi-uppercase-label">Detached</div>+ </div>+ {% endif %}+ {% if sync_result.removed_list %}+ <div class="px-3">+ <div class="text-danger font-weight-bold hi-sync-result-stat-number">{{ sync_result.removed_list|length }}</div><div class="text-muted small text-uppercase hi-uppercase-label">Removed</div>@@ -138,8 +154,8 @@the affordance to the entity names themselves.{% endcomment %}{% if sync_result.removed_list %}- <div class="mb-3 pl-3 hi-category-section hi-category-section--secondary">- <div class="small text-secondary text-uppercase mb-1 hi-uppercase-label">+ <div class="mb-3 pl-3 hi-category-section hi-category-section--danger">+ <div class="small text-danger text-uppercase mb-1 hi-uppercase-label">Removed ({{ sync_result.removed_list|length }})</div><ul class="list-unstyled small mb-0 hi-sync-result-item-list">@@ -150,6 +166,19 @@</div>{% endif %}+ {% if sync_result.detached_list %}+ <div class="mb-3 pl-3 hi-category-section hi-category-section--secondary">+ <div class="small text-secondary text-uppercase mb-1 hi-uppercase-label">+ Detached ({{ sync_result.detached_list|length }})+ </div>+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">+ {% for name in sync_result.detached_list %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+ </div>+ {% endif %}+{% if sync_result.updated_list %}<div class="mb-3 pl-3 hi-category-section hi-category-section--info"><div class="small text-info text-uppercase mb-1 hi-uppercase-label">@@ -163,6 +192,19 @@</div>{% endif %}+ {% if sync_result.reconnected_list %}+ <div class="mb-3 pl-3 hi-category-section hi-category-section--info">+ <div class="small text-info text-uppercase mb-1 hi-uppercase-label">+ Reconnected ({{ sync_result.reconnected_list|length }})+ </div>+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">+ {% for name in sync_result.reconnected_list %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+ </div>+ {% endif %}+{% if sync_result.created_list %}<div class="mb-3 pl-3 hi-category-section hi-category-section--success"><div class="small text-success text-uppercase mb-1 hi-uppercase-label">diff --git a/src/hi/integrations/templatetags/integration_tags.py b/src/hi/integrations/templatetags/integration_tags.pyindex 07a667ae..bbb438aa 100644--- a/src/hi/integrations/templatetags/integration_tags.py+++ b/src/hi/integrations/templatetags/integration_tags.py@@ -9,18 +9,30 @@ logger = logging.getLogger(__name__)register = template.Library()-def _get_integration_metadata( model : IntegrationDetailsModel ):- if not model:+def _resolve_metadata_for_id( integration_id : str ):+ if not integration_id:return Noneintegration_manager = IntegrationManager()try:- gateway = integration_manager.get_integration_gateway( model.integration_id )+ gateway = integration_manager.get_integration_gateway( integration_id )return gateway.get_metadata()except Exception:passreturn None+def _get_integration_metadata( model : IntegrationDetailsModel ):+ if not model:+ return None+ return _resolve_metadata_for_id( model.integration_id )+++def _get_previous_integration_metadata( model : IntegrationDetailsModel ):+ if not model:+ return None+ return _resolve_metadata_for_id( model.previous_integration_id )++@register.simple_tagdef integration_display_name( model : IntegrationDetailsModel ) -> str:metadata = _get_integration_metadata( model )@@ -32,3 +44,22 @@ def integration_logo_path( model : IntegrationDetailsModel ) -> str:metadata = _get_integration_metadata( model )return metadata.logo_static_path if metadata else ''++def previous_integration_display_name( model : IntegrationDetailsModel ) -> str:+ """The label of the integration this entity was previously+ attached to (i.e., the source of the "Detached from ..." badge).+ Returns None when the entity is not detached, or when the prior+ integration has since been removed from the system."""+ metadata = _get_previous_integration_metadata( model )+ return metadata.label if metadata else None+++def previous_integration_logo_path( model : IntegrationDetailsModel ) -> str:+ """Logo for the integration the entity was previously attached+ to. Used in the entity-detail UI to show the "Detached from ..."+ badge alongside the same logo the integration uses when active."""+ metadata = _get_previous_integration_metadata( model )+ return metadata.logo_static_path if metadata else ''+diff --git a/src/hi/integrations/tests/test_entity_operations.py b/src/hi/integrations/tests/test_entity_operations.pyindex d9cce6b0..8b6770ef 100644--- a/src/hi/integrations/tests/test_entity_operations.py+++ b/src/hi/integrations/tests/test_entity_operations.py@@ -292,3 +292,244 @@ class PreserveWithUserDataFlagTests(TestCase):entity.refresh_from_db()self.assertFalse(entity.has_video_stream)self.assertTrue(entity.is_disabled)++ def test_preserve_records_previous_integration_identity(self):+ """+ On disconnect via preservation, the entity's pre-disconnect+ integration identity is captured into previous_integration_id /+ previous_integration_name. This is the signal the+ auto-reconnect path (Issue #281) reads to recognize+ previously-disconnected entities when the same upstream key+ reappears later.+ """+ entity = Entity.objects.create(+ name='Reconnectable',+ entity_type_str='LIGHT',+ integration_id='hass',+ integration_name='light.kitchen',+ )+ EntityAttribute.objects.create(+ entity=entity,+ name='User Note',+ value='keep me',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM),+ )++ EntityIntegrationOperations.preserve_with_user_data(+ entity=entity,+ integration_name='hass',+ )++ entity.refresh_from_db()+ # Active identity is cleared (existing contract).+ self.assertIsNone(entity.integration_id)+ self.assertIsNone(entity.integration_name)+ # Previous identity captures what was cleared (new contract).+ self.assertEqual(entity.previous_integration_id, 'hass')+ self.assertEqual(entity.previous_integration_name, 'light.kitchen')+++class FindReconnectCandidatesTests(TestCase):+ """+ find_reconnect_candidates (Issue #281): given the upstream+ IntegrationKeys the synchronizer's primary-match step did not+ match, return a map of upstream_key → matching disconnected+ entity for every key with a unique previous-identity match.+ Ambiguous matches are dropped and noted via result.info_list.+ """++ INTEGRATION_ID = 'hass'++ def _disconnected_entity(self, name, previous_integration_name):+ """Create an entity in the disconnected state — active+ integration_id NULL, previous_integration_id populated."""+ return Entity.objects.create(+ name = name,+ entity_type_str = 'LIGHT',+ previous_integration_id = self.INTEGRATION_ID,+ previous_integration_name = previous_integration_name,+ )++ def _make_upstream_key(self, integration_name, integration_id=None):+ from hi.integrations.transient_models import IntegrationKey+ return IntegrationKey(+ integration_id = integration_id or self.INTEGRATION_ID,+ integration_name = integration_name,+ )++ def test_returns_match_for_unique_secondary(self):+ entity = self._disconnected_entity(+ name = '[Disconnected] Kitchen Light',+ previous_integration_name = 'light.kitchen',+ )+ upstream_key = self._make_upstream_key('light.kitchen')++ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id = self.INTEGRATION_ID,+ upstream_keys = [ upstream_key ],+ )++ self.assertEqual(candidates, {upstream_key: entity})++ def test_ambiguous_match_is_dropped_and_noted(self):+ """Two disconnected entities sharing the same previous+ identity → upstream_key absent from result map; operator+ breadcrumb in result.info_list."""+ self._disconnected_entity(+ name = '[Disconnected] Kitchen Light A',+ previous_integration_name = 'light.kitchen',+ )+ self._disconnected_entity(+ name = '[Disconnected] Kitchen Light B',+ previous_integration_name = 'light.kitchen',+ )+ upstream_key = self._make_upstream_key('light.kitchen')++ from hi.integrations.sync_result import IntegrationSyncResult+ result = IntegrationSyncResult(title='Test')++ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id = self.INTEGRATION_ID,+ upstream_keys = [ upstream_key ],+ result = result,+ )++ self.assertEqual(candidates, {})+ self.assertTrue(any('share that previous identity' in note+ for note in result.info_list))++ def test_mixed_unique_ambiguous_and_unmatched_in_one_call(self):+ """Each upstream-key match decision is independent: a unique+ match is returned, an ambiguous one is dropped (with an+ info_list breadcrumb), and a no-match is silently absent.+ Pins that the per-name branches in find_reconnect_candidates+ don't cross-contaminate within a single call."""+ self._disconnected_entity(+ name='[Disconnected] Unique Light',+ previous_integration_name='light.unique',+ )+ self._disconnected_entity(+ name='[Disconnected] Ambiguous A',+ previous_integration_name='light.ambiguous',+ )+ self._disconnected_entity(+ name='[Disconnected] Ambiguous B',+ previous_integration_name='light.ambiguous',+ )++ unique_key = self._make_upstream_key('light.unique')+ ambiguous_key = self._make_upstream_key('light.ambiguous')+ unmatched_key = self._make_upstream_key('light.never_existed')++ from hi.integrations.sync_result import IntegrationSyncResult+ result = IntegrationSyncResult(title='Mixed')++ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id=self.INTEGRATION_ID,+ upstream_keys=[unique_key, ambiguous_key, unmatched_key],+ result=result,+ )++ # Unique key is in the result; ambiguous and unmatched are not.+ self.assertEqual(set(candidates.keys()), {unique_key})+ self.assertEqual(candidates[unique_key].name, '[Disconnected] Unique Light')+ # Ambiguity breadcrumb references the ambiguous name specifically.+ ambiguous_notes = [+ note for note in result.info_list+ if 'share that previous identity' in note+ ]+ self.assertEqual(len(ambiguous_notes), 1)+ self.assertIn('light.ambiguous', ambiguous_notes[0])+ # No spurious breadcrumb for the unmatched or unique keys.+ self.assertNotIn('light.unique', ambiguous_notes[0])+ self.assertNotIn('light.never_existed', ambiguous_notes[0])++ def test_does_not_match_across_integrations(self):+ """An entity disconnected from HASS must not match an upstream+ key from ZM, even if the integration_name coincides."""+ self._disconnected_entity(+ name = '[Disconnected] foo',+ previous_integration_name = 'foo',+ )+ zm_upstream_key = self._make_upstream_key('foo', integration_id='zoneminder')++ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id = 'zoneminder',+ upstream_keys = [ zm_upstream_key ],+ )++ self.assertEqual(candidates, {})++ def test_no_match_returns_empty_dict(self):+ upstream_key = self._make_upstream_key('light.unknown')++ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id = self.INTEGRATION_ID,+ upstream_keys = [ upstream_key ],+ )++ self.assertEqual(candidates, {})++ def test_empty_upstream_set_short_circuits_without_db_query(self):+ with self.assertNumQueries(0):+ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id = self.INTEGRATION_ID,+ upstream_keys = [],+ )++ self.assertEqual(candidates, {})++ def test_secondary_lookup_is_a_single_batched_query(self):+ """Many upstream keys → one DB query for the candidate scan,+ regardless of how many keys are passed."""+ for i in range(5):+ self._disconnected_entity(+ name = f'[Disconnected] light_{i}',+ previous_integration_name = f'light.{i}',+ )+ upstream_keys = [ self._make_upstream_key(f'light.{i}') for i in range(5) ]++ with self.assertNumQueries(1):+ candidates = EntityIntegrationOperations.find_reconnect_candidates(+ integration_id = self.INTEGRATION_ID,+ upstream_keys = upstream_keys,+ )++ self.assertEqual(len(candidates), 5)+++class PreserveWithUserDataNamePreservationTests(TestCase):+ """+ Disconnect (preserve_with_user_data) signals the detached state+ structurally — via the previous_integration_* columns — and does+ NOT mutate the entity name. This pins the contract: any name the+ operator sees post-detach is the name the entity had before+ detach.+ """++ def test_disconnect_does_not_mutate_entity_name(self):+ entity = Entity.objects.create(+ name='User Edited Name',+ entity_type_str='LIGHT',+ integration_id='hass',+ integration_name='light.kitchen',+ )+ EntityAttribute.objects.create(+ entity=entity,+ name='Custom Note',+ value='retain me',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM),+ )++ EntityIntegrationOperations.preserve_with_user_data(+ entity=entity,+ integration_name='hass',+ )++ entity.refresh_from_db()+ self.assertEqual(entity.name, 'User Edited Name')+ # Detached state is signaled by the previous_integration_* columns.+ self.assertEqual(entity.previous_integration_id, 'hass')+ self.assertIsNone(entity.integration_id)diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.pyindex f68cb8f1..2a4e9dea 100644--- a/src/hi/integrations/tests/test_integration_manager.py+++ b/src/hi/integrations/tests/test_integration_manager.py@@ -682,10 +682,12 @@ class IntegrationManagerTestCase(TestCase):# Integration-only entity is gone.self.assertFalse(Entity.objects.filter(id=no_user_id).exists())- # User-data entity survives and is disconnected (integration_id cleared).+ # User-data entity survives in detached state: active integration+ # identity cleared, previous identity recorded for the+ # auto-reconnect path.preserved = Entity.objects.get(id=user_data_id)self.assertIsNone(preserved.integration_id)- self.assertTrue(preserved.name.startswith('[Disconnected]'))+ self.assertIsNotNone(preserved.previous_integration_id)# Configuration attributes retained for re-Configure.self.assertEqual(integration.attributes.count(), 1)diff --git a/src/hi/integrations/tests/test_integration_synchronizer.py b/src/hi/integrations/tests/test_integration_synchronizer.pyindex e2fc0efd..a513ae23 100644--- a/src/hi/integrations/tests/test_integration_synchronizer.py+++ b/src/hi/integrations/tests/test_integration_synchronizer.py@@ -1,5 +1,21 @@"""-Unit tests for IntegrationSynchronizer's intelligent entity-removal helper.+Unit tests for IntegrationSynchronizer framework helpers.++Covers the framework-owned policies that all per-integration+synchronizers share:++ * ``_remove_entity_intelligently`` — sync-time entity removal /+ preservation (delegates to+ ``EntityIntegrationOperations.remove_entities_with_closure``).+ * ``reconnect_disconnected_items`` — Issue #281 auto-reconnect+ pre-pass.+ * ``_rebuild_integration_components`` — abstract subclass hook+ used by reconnect.++End-to-end cycle coverage (sync → detach → reconnect across multiple+sync passes) lives in ``IntegrationSynchronizerReconnectCycleTests``+at the bottom of this module; the per-integration converter+contracts live in each ``services/<integration>/tests/`` directory."""import logging@@ -16,10 +32,22 @@ from hi.integrations.sync_result import IntegrationSyncResultlogging.disable(logging.CRITICAL)+def _stub_integration_metadata(integration_id='test_integration', label='TestIntegration'):+ """Lightweight metadata stub for tests that exercise the+ framework's integration-id-aware code paths without standing up a+ full IntegrationGateway."""+ from types import SimpleNamespace+ return SimpleNamespace(integration_id=integration_id, label=label)++class TestSynchronizer(IntegrationSynchronizer):"""Concrete IntegrationSynchronizer used to exercise the- intelligent-removal helper. Stubs the abstract hooks so the class- can be instantiated; sync() itself is not exercised here."""+ intelligent-removal and reconnect framework helpers. Stubs the+ abstract hooks so the class can be instantiated; sync() itself+ is not exercised here."""++ def get_integration_metadata(self):+ return _stub_integration_metadata()def get_result_title(self, is_initial_import=False):return 'Test Sync Result'@@ -77,7 +105,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Entity should be completely deleted@@ -140,7 +168,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Entity should still exist but be disconnected@@ -149,10 +177,14 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Reload entityself.entity.refresh_from_db()- # Check entity is disconnected+ # Check entity is detached: active integration identity is+ # cleared, previous identity is recorded, and the entity name+ # is preserved verbatim (the detached state is signaled+ # structurally, not by mutating the name).self.assertIsNone(self.entity.integration_id)self.assertIsNone(self.entity.integration_name)- self.assertEqual(self.entity.name, f'[Disconnected] {original_name}')+ self.assertEqual(self.entity.previous_integration_id, 'test_integration')+ self.assertEqual(self.entity.name, original_name)# User attribute should still existself.assertTrue(EntityAttribute.objects.filter(id=user_attr.id).exists())@@ -169,17 +201,17 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Entity state should be deleted (orphaned)self.assertFalse(EntityState.objects.filter(id=state_id).exists())- # Preservation records the original name in removed_list- # (captured before the rename) and surfaces a diagnostic- # info note — the operator wants to know an entity was- # disconnected and renamed, not just see a name in a list.- self.assertEqual(self.result.removed_list, [original_name])+ # Preservation records the entity name in detached_list (the+ # operator-visible "Detached" tile) and surfaces a diagnostic+ # info note in info_list. The hard-delete branch was not+ # taken for this entity, so removed_list stays empty.+ self.assertEqual(self.result.detached_list, [original_name])+ self.assertEqual(self.result.removed_list, [])self.assertEqual(len(self.result.info_list), 1)message = self.result.info_list[0]self.assertIn('Preserved TestIntegration item', message)- self.assertIn('disconnected from integration', message)+ self.assertIn('detached from integration', message)self.assertIn(original_name, message)- self.assertIn('[Disconnected]', message)# Verify integration payload is clearedself.entity.refresh_from_db()@@ -229,7 +261,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Entity state should still exist (has user sensor)@@ -241,33 +273,6 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Integration sensor should be deletedself.assertFalse(Sensor.objects.filter(id=integration_sensor.id).exists())- def test_disconnected_name_not_duplicated(self):- """Test that [Disconnected] prefix is not added if already present."""- # Set entity name to already have disconnected prefix- self.entity.name = '[Disconnected] Already Disconnected'- self.entity.save()-- # Create user data- EntityAttribute.objects.create(- entity=self.entity,- name='User Note',- value='User note',- value_type_str='TEXT',- attribute_type_str=str(AttributeType.CUSTOM)- )-- # Call the method- self.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'- )-- # Reload entity- self.entity.refresh_from_db()-- # Name should not have duplicate prefix- self.assertEqual(self.entity.name, '[Disconnected] Already Disconnected')- self.assertNotIn('[Disconnected] [Disconnected]', self.entity.name)-def test_multiple_entity_states_mixed_preservation(self):"""Test handling of multiple entity states with different preservation needs."""# Create user data to trigger preservation@@ -315,7 +320,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# First state should be deleted (orphaned)@@ -350,7 +355,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Entity should be completely deleted; name recorded.@@ -379,7 +384,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Verify entity is preserved and integration fields are cleared@@ -415,7 +420,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# All integration attributes should be deleted@@ -496,7 +501,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call the methodself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Verify entity is preserved@@ -585,7 +590,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):# Call deletion (no user data, should delete completely)self.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Verify complete cascade deletion@@ -616,7 +621,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):)self.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# 3 entries: 2 pre-existing + 1 preservation note.@@ -624,8 +629,9 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):self.assertIn('Preserved TestIntegration item', self.result.info_list[2])self.assertEqual(self.result.info_list[0], 'Initial message')self.assertEqual(self.result.info_list[1], 'Another message')- # And removed_list captured the name exactly once.- self.assertEqual(self.result.removed_list, ['Test Entity'])+ # detached_list (not removed_list) captures preserved entities.+ self.assertEqual(self.result.detached_list, ['Test Entity'])+ self.assertEqual(self.result.removed_list, [])class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):@@ -712,12 +718,12 @@ class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):# Execute preservation operationself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Verify entity preservation and disconnectionself.entity.refresh_from_db()- self.assertTrue(self.entity.name.startswith('[Disconnected]'))+ self.assertIsNotNone(self.entity.previous_integration_id)self.assertIsNone(self.entity.integration_id)self.assertIsNone(self.entity.integration_name)@@ -748,13 +754,15 @@ class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):self.assertEqual(remaining_attributes.count(), 1)self.assertEqual(remaining_attributes.first().name, 'User Note')- # Preservation diagnostic surfaces in info_list; the- # original (pre-rename) name is captured in removed_list.+ # Preservation diagnostic surfaces in info_list; the entity+ # name is captured in detached_list (preserved entities go+ # there, not in removed_list).self.assertEqual(len(self.result.info_list), 1)message = self.result.info_list[0]self.assertIn('Preserved TestIntegration item', message)- self.assertIn('disconnected from integration', message)- self.assertEqual(self.result.removed_list, ['Test Entity'])+ self.assertIn('detached from integration', message)+ self.assertEqual(self.result.detached_list, ['Test Entity'])+ self.assertEqual(self.result.removed_list, [])def test_preservation_with_database_constraint_validation(self):"""Test that preservation operations respect database constraints and maintain referential integrity."""@@ -806,12 +814,12 @@ class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):# Execute preservationself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Verify our entity was preserved and disconnectedself.entity.refresh_from_db()- self.assertTrue(self.entity.name.startswith('[Disconnected]'))+ self.assertIsNotNone(self.entity.previous_integration_id)self.assertIsNone(self.entity.integration_id)self.assertIsNone(self.entity.integration_name)@@ -865,7 +873,7 @@ class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):entity_id = integration_only_entity.idself.synchronizer._remove_entity_intelligently(- integration_only_entity, self.result, 'TestIntegration'+ integration_only_entity, self.result)# Should be completely deleted@@ -900,12 +908,12 @@ class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):)self.synchronizer._remove_entity_intelligently(- mixed_entity, self.result, 'TestIntegration'+ mixed_entity, self.result)# Should be preserved and disconnectedmixed_entity.refresh_from_db()- self.assertTrue(mixed_entity.name.startswith('[Disconnected]'))+ self.assertIsNotNone(mixed_entity.previous_integration_id)self.assertIsNone(mixed_entity.integration_id)self.assertIsNone(mixed_entity.integration_name)@@ -972,12 +980,12 @@ class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):# Execute preservationself.synchronizer._remove_entity_intelligently(- self.entity, self.result, 'TestIntegration'+ self.entity, self.result)# Our entity should be preserved and disconnectedself.entity.refresh_from_db()- self.assertTrue(self.entity.name.startswith('[Disconnected]'))+ self.assertIsNotNone(self.entity.previous_integration_id)self.assertIsNone(self.entity.integration_id)# Integration components should be deleted@@ -1004,70 +1012,6 @@ class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):self.assertEqual(remaining_state.controllers.count(), 0)self.assertEqual(remaining_state.sensors.first().name, 'User Sensor')- def test_complex_disconnection_name_handling(self):- """Test various edge cases in disconnection name handling."""- test_cases = [- {- 'name': 'Simple Entity Name',- 'expected': '[Disconnected] Simple Entity Name'- },- {- 'name': '[Already Disconnected] Entity',- 'expected': '[Disconnected] [Already Disconnected] Entity' # Should not duplicate if different format- },- {- 'name': '[Disconnected] Already Prefixed',- 'expected': '[Disconnected] Already Prefixed' # Should not duplicate exact match- },- {- 'name': ' Whitespace Padded ',- 'expected': '[Disconnected] Whitespace Padded ' # Should preserve exact spacing- },- {- 'name': '',- 'expected': '[Disconnected] ' # Should handle empty name- }- ]-- for i, test_case in enumerate(test_cases):- with self.subTest(test_case=test_case):- # Create entity for this test- entity = Entity.objects.create(- name=test_case['name'],- entity_type_str='LIGHT',- integration_id='test_integration',- integration_name=f'device_{i}'- )-- # Add user data to trigger preservation- EntityAttribute.objects.create(- entity=entity,- name='User Data',- value='User value',- value_type_str='TEXT',- attribute_type_str=str(AttributeType.CUSTOM)- )-- # Create fresh result for each test- test_result = IntegrationSyncResult(title='Test Result')-- # Execute preservation- self.synchronizer._remove_entity_intelligently(- entity, test_result, 'TestIntegration'- )-- # Verify name transformation- entity.refresh_from_db()- self.assertEqual(entity.name, test_case['expected'])-- # Verify disconnection- self.assertIsNone(entity.integration_id)- self.assertIsNone(entity.integration_name)-- # Preservation note surfaces in info_list.- self.assertEqual(len(test_result.info_list), 1)- self.assertIn('Preserved TestIntegration item', test_result.info_list[0])-class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):@@ -1113,7 +1057,7 @@ class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):area_id = self.area.idself.synchronizer._remove_entity_intelligently(- self.camera, self.result, 'TestIntegration',+ self.camera, self.result,)self.assertFalse(Entity.objects.filter(id=camera_id).exists())@@ -1145,7 +1089,7 @@ class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):area_id = self.area.idself.synchronizer._remove_entity_intelligently(- self.camera, self.result, 'TestIntegration',+ self.camera, self.result,)self.assertFalse(Entity.objects.filter(id=camera_id).exists())@@ -1170,20 +1114,27 @@ class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):area_id = self.area.idself.synchronizer._remove_entity_intelligently(- self.camera, self.result, 'TestIntegration',+ self.camera, self.result,)self.assertFalse(Entity.objects.filter(id=camera_id).exists())- # Area persists with operator-added data.+ # Area persists with operator-added data and is now in+ # the user-managed state (preserve_with_user_data flips+ # is_disabled=True and can_user_delete=True). The Area+ # never had an active integration identity of its own — it+ # was an auto-created delegate of the camera — so the+ # previous_integration_* columns remain NULL on it; the+ # is_disabled gate is the durable detached signal here.self.assertTrue(Entity.objects.filter(id=area_id).exists())self.area.refresh_from_db()- self.assertTrue(self.area.name.startswith('[Disconnected]'))+ self.assertTrue(self.area.is_disabled)+ self.assertTrue(self.area.can_user_delete)def test_orphan_delegate_deleted_when_only_principal_has_user_data(self):- """Camera carries user data so it is preserved (kept as- [Disconnected]); Area carries none. Even though the- principal survives in name, the Area is correctly hard-- deleted — see the rationale documented on+ """Camera carries user data so it is detached and preserved;+ Area carries none. Even though the principal survives, the+ Area is correctly hard-deleted — see the rationale+ documented on``EntityIntegrationOperations.remove_entities_with_closure``.Pinning this case prevents a well-intentioned futurerefactor from flipping it back to preservation."""@@ -1199,13 +1150,497 @@ class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):area_id = self.area.idself.synchronizer._remove_entity_intelligently(- self.camera, self.result, 'TestIntegration',+ self.camera, self.result,)- # Camera kept with [Disconnected] rename (user data).+ # Camera detached and preserved (user data).self.assertTrue(Entity.objects.filter(id=camera_id).exists())self.camera.refresh_from_db()- self.assertTrue(self.camera.name.startswith('[Disconnected]'))+ self.assertIsNotNone(self.camera.previous_integration_id)# Area is gone — its display purpose is negated once the# principal's integration-derived state is removed.self.assertFalse(Entity.objects.filter(id=area_id).exists())+++class ReconnectDisconnectedItemsFrameworkTests(TestCase):+ """+ Issue #281: framework-level reconnect lives on the+ IntegrationSynchronizer base class, symmetric to disconnect+ (preserve_with_user_data) which lives on EntityIntegrationOperations.+ Each integration only contributes a thin+ ``_rebuild_integration_components`` override; all the boilerplate+ (find candidates, strip prefix, clear previous identity, append+ info_list note, update entity-map) lives here in the base.++ These tests exercise the base method directly with a recording+ subclass, so the per-integration sync tests don't need to+ re-verify the boilerplate.+ """++ INTEGRATION_ID = 'hass'+ INTEGRATION_LABEL = 'Home Assistant'++ def _make_synchronizer(self):+ """Concrete synchronizer that records each+ _rebuild_integration_components dispatch + simulates the+ per-integration converter's effect (sets integration_key)."""+ from hi.integrations.transient_models import IntegrationKey++ captured = []+ integration_id = self.INTEGRATION_ID++ integration_label = self.INTEGRATION_LABEL++ class RecordingSynchronizer(IntegrationSynchronizer):+ def get_integration_metadata(self):+ return _stub_integration_metadata(+ integration_id=integration_id,+ label=integration_label,+ )++ def _rebuild_integration_components(self, entity, upstream, result):+ captured.append((entity.id, upstream))+ entity.integration_key = IntegrationKey(+ integration_id=integration_id,+ integration_name=upstream['name'],+ )+ entity.save()++ return RecordingSynchronizer(), captured++ def _disconnected_entity(self, name, previous_integration_name):+ return Entity.objects.create(+ name=name,+ entity_type_str='LIGHT',+ previous_integration_id=self.INTEGRATION_ID,+ previous_integration_name=previous_integration_name,+ )++ def _make_upstream_key(self, integration_name):+ from hi.integrations.transient_models import IntegrationKey+ return IntegrationKey(+ integration_id=self.INTEGRATION_ID,+ integration_name=integration_name,+ )++ def test_reconnect_clears_previous_identity_and_inserts_to_entity_map(self):+ """Single secondary match → entity is reconnected end-to-end:+ previous identity cleared (which removes the "Detached from"+ UI badge), converter dispatched, info_list note added, entity+ inserted into the entity-map so the caller's main loop sees+ it as matched. The entity name is preserved verbatim — the+ user's name is not the place we encode connection state."""+ user_edited_name = 'Kitchen Light (user-edited)'+ entity = self._disconnected_entity(+ name=user_edited_name,+ previous_integration_name='light.kitchen',+ )+ upstream_key = self._make_upstream_key('light.kitchen')+ upstream_payload = {'name': 'light.kitchen', 'flavor': 'demo'}++ synchronizer, captured = self._make_synchronizer()+ result = IntegrationSyncResult(title='Test')+ integration_key_to_entity = {}++ synchronizer.reconnect_disconnected_items(+ integration_key_to_upstream={upstream_key: upstream_payload},+ integration_key_to_entity=integration_key_to_entity,+ result=result,+ )++ self.assertEqual(captured, [(entity.id, upstream_payload)])+ entity.refresh_from_db()+ # Name is preserved verbatim — reconnect does not touch it.+ self.assertEqual(entity.name, user_edited_name)+ self.assertIsNone(entity.previous_integration_id)+ self.assertEqual(entity.integration_id, self.INTEGRATION_ID)+ self.assertEqual(integration_key_to_entity, {upstream_key: entity})+ self.assertTrue(any(+ f'Auto-reconnected {self.INTEGRATION_LABEL} item' in note+ for note in result.info_list+ ))++ def test_no_unmatched_short_circuits_without_dispatch(self):+ """All upstream keys already primary-matched →+ _rebuild_integration_components is never invoked."""+ existing_key = self._make_upstream_key('light.existing')+ existing_entity = Entity.objects.create(+ name='Already Connected',+ entity_type_str='LIGHT',+ integration_id=self.INTEGRATION_ID,+ integration_name='light.existing',+ )++ synchronizer, captured = self._make_synchronizer()+ result = IntegrationSyncResult(title='Test')+ integration_key_to_entity = {existing_key: existing_entity}++ synchronizer.reconnect_disconnected_items(+ integration_key_to_upstream={existing_key: {'name': 'light.existing'}},+ integration_key_to_entity=integration_key_to_entity,+ result=result,+ )++ self.assertEqual(captured, [])++ def test_subclass_without_override_raises_clear_error_when_match_found(self):+ """A subclass that doesn't override+ _rebuild_integration_components but whose sync flow has a+ reconnect candidate hits NotImplementedError with a+ diagnostic message — fail loud, not silent."""+ self._disconnected_entity(+ name='[Disconnected] foo',+ previous_integration_name='foo',+ )+ upstream_key = self._make_upstream_key('foo')++ class IncompleteSynchronizer(IntegrationSynchronizer):+ # Metadata is provided so the framework reaches the+ # _rebuild_integration_components hook (the missing+ # override under test) rather than tripping on the+ # earlier metadata abstract-hook check.+ def get_integration_metadata(_self):+ return _stub_integration_metadata(+ integration_id=self.INTEGRATION_ID,+ label=self.INTEGRATION_LABEL,+ )++ synchronizer = IncompleteSynchronizer()+ result = IntegrationSyncResult(title='Test')++ with self.assertRaises(NotImplementedError) as cm:+ synchronizer.reconnect_disconnected_items(+ integration_key_to_upstream={upstream_key: {'name': 'foo'}},+ integration_key_to_entity={},+ result=result,+ )+ self.assertIn('_rebuild_integration_components', str(cm.exception))+++class IntegrationSynchronizerReconnectCycleTests(TestCase):+ """+ Issue #281 end-to-end cycle tests. Exercise the full+ sync → disconnect → re-add upstream → sync → reconnect cycle+ against a self-contained test synchronizer that mimics the real+ per-integration sync pattern (primary-match lookup, framework+ reconnect pre-pass, create-new for the remainder, disconnect+ for upstream-orphans). The shared synchronizer fixture means+ these tests are integration-agnostic — they exercise the+ framework path that all integrations now share.++ Phase 6 of #281's plan; the per-converter unit-level coverage+ lives in services/<integration>/tests/test_*.+ """++ INTEGRATION_ID = 'test_e2e'+ INTEGRATION_LABEL = 'Test E2E'++ def _make_upstream_key(self, integration_name):+ from hi.integrations.transient_models import IntegrationKey+ return IntegrationKey(+ integration_id=self.INTEGRATION_ID,+ integration_name=integration_name,+ )++ def _build_synchronizer(self):+ """Test-only synchronizer that drives a complete sync cycle+ against an in-memory upstream-key list. The+ ``_rebuild_integration_components`` override mirrors what a+ real integration converter does: set integration_key on the+ existing entity and save."""+ from hi.integrations.entity_operations import EntityIntegrationOperations+ from hi.integrations.transient_models import IntegrationKey++ integration_id = self.INTEGRATION_ID+ integration_label = self.INTEGRATION_LABEL++ class TestE2ESynchronizer(IntegrationSynchronizer):+ def get_integration_metadata(self):+ return _stub_integration_metadata(+ integration_id=integration_id,+ label=integration_label,+ )++ def _rebuild_integration_components(self, entity, upstream, result):+ entity.integration_key = IntegrationKey(+ integration_id=integration_id,+ integration_name=upstream['name'],+ )+ entity.save()++ def run_sync_cycle(self, upstream_keys, result):+ """Run one full sync pass: primary-match → framework+ reconnect pre-pass → create-new for the remainder →+ disconnect upstream-orphans. Mirrors the real+ per-integration sync structure."""+ upstream_map = {+ IntegrationKey(integration_id=integration_id,+ integration_name=name): {'name': name}+ for name in upstream_keys+ }+ existing_qs = Entity.objects.filter(integration_id=integration_id)+ integration_key_to_entity = {+ e.integration_key: e for e in existing_qs+ if e.integration_key is not None+ }++ self.reconnect_disconnected_items(+ integration_key_to_upstream=upstream_map,+ integration_key_to_entity=integration_key_to_entity,+ result=result,+ )++ for upstream_key, payload in upstream_map.items():+ if upstream_key in integration_key_to_entity:+ continue+ Entity.objects.create(+ name=payload['name'],+ entity_type_str='LIGHT',+ integration_id=integration_id,+ integration_name=upstream_key.integration_name,+ )++ for upstream_key, entity in list(integration_key_to_entity.items()):+ if upstream_key not in upstream_map:+ EntityIntegrationOperations.preserve_with_user_data(+ entity=entity,+ integration_name=integration_id,+ result=result,+ )++ return TestE2ESynchronizer()++ def _user_attribute(self, entity, name='Custom Note', value='retain me'):+ """Anchor an entity for sync-time preservation by attaching+ user-created custom data."""+ EntityAttribute.objects.create(+ entity=entity,+ name=name,+ value=value,+ value_type_str='TEXT',+ attribute_type_str=str(AttributeType.CUSTOM),+ )++ def test_sync_disconnect_then_reconnect_does_not_create_duplicate(self):+ """The headline cycle: an entity is imported, drops from+ upstream (disconnect via sync-time preservation), reappears+ (reconnect via the secondary-match path). Total entity+ count returns to 1 — no duplicate is created. The+ operator-visible result modal shows the right tile each+ pass: Created on import, Detached on drop, Reconnected on+ re-add."""+ synchronizer = self._build_synchronizer()+ result_pass1 = IntegrationSyncResult(title='Cycle 1')++ # Pass 1: upstream introduces the entity.+ synchronizer.run_sync_cycle(['light.kitchen'], result_pass1)+ self.assertEqual(Entity.objects.count(), 1)+ original = Entity.objects.get(integration_name='light.kitchen')+ self._user_attribute(original)+ original_id = original.id++ # Pass 2: upstream drops the entity → detached.+ result_pass2 = IntegrationSyncResult(title='Cycle 2')+ synchronizer.run_sync_cycle([], result_pass2)+ original.refresh_from_db()+ self.assertIsNone(original.integration_id)+ self.assertEqual(original.previous_integration_id, self.INTEGRATION_ID)+ self.assertEqual(original.previous_integration_name, 'light.kitchen')+ # The entity is on the Detached tile, NOT the Removed tile.+ self.assertEqual(result_pass2.detached_list, [original.name])+ self.assertEqual(result_pass2.removed_list, [])++ # Pass 3: upstream re-adds → reconnected (NOT duplicated).+ result_pass3 = IntegrationSyncResult(title='Cycle 3')+ synchronizer.run_sync_cycle(['light.kitchen'], result_pass3)+ self.assertEqual(Entity.objects.count(), 1)+ reconnected = Entity.objects.get(id=original_id)+ self.assertEqual(reconnected.integration_id, self.INTEGRATION_ID)+ self.assertIsNone(reconnected.previous_integration_id)+ # The entity is on the Reconnected tile.+ self.assertEqual(result_pass3.reconnected_list, [reconnected.name])+ self.assertEqual(result_pass3.created_list, [])+ # And the diagnostic info note is also captured.+ self.assertTrue(any('Auto-reconnected' in note+ for note in result_pass3.info_list))++ def test_disable_safe_then_resync_reconnects_preserved_entity(self):+ """Operator-initiated disable (SAFE mode) preserves entities+ with user data via the same code path as sync-time+ preservation, so reconnect must work for those too. Pinned+ in the corrected #281 issue's edge-cases section."""+ from hi.integrations.entity_operations import EntityIntegrationOperations++ synchronizer = self._build_synchronizer()+ result = IntegrationSyncResult(title='Disable Cycle')++ synchronizer.run_sync_cycle(['light.lounge'], result)+ entity = Entity.objects.get(integration_name='light.lounge')+ self._user_attribute(entity)+ entity_id = entity.id++ # Disable-SAFE: this is the exact call the integration_manager+ # makes for SAFE-mode disable on entities with user data.+ EntityIntegrationOperations.preserve_with_user_data(+ entity=entity,+ integration_name=self.INTEGRATION_ID,+ result=result,+ )+ entity.refresh_from_db()+ self.assertIsNone(entity.integration_id)+ self.assertEqual(entity.previous_integration_id, self.INTEGRATION_ID)++ # Re-Configure + sync re-imports the upstream item → reconnect.+ result_resync = IntegrationSyncResult(title='Resync')+ synchronizer.run_sync_cycle(['light.lounge'], result_resync)+ self.assertEqual(Entity.objects.count(), 1)+ reconnected = Entity.objects.get(id=entity_id)+ self.assertEqual(reconnected.integration_id, self.INTEGRATION_ID)+ self.assertIsNone(reconnected.previous_integration_id)+ # The entity surfaces on the Reconnected tile.+ self.assertEqual(result_resync.reconnected_list, [reconnected.name])++ def test_primary_match_shadows_secondary_so_no_false_reconnect(self):+ """A live entity matches the primary scan; an unrelated+ disconnected entity happens to share the previous_integration_name+ of an unrelated upstream key. The primary-match wins and the+ secondary scan only operates on the unmatched residual —+ the disconnected entity is NOT silently re-attached to the+ wrong upstream item."""+ synchronizer = self._build_synchronizer()+ result = IntegrationSyncResult(title='Shadow')++ # A primary-matched entity for 'light.bath'.+ Entity.objects.create(+ name='light.bath',+ entity_type_str='LIGHT',+ integration_id=self.INTEGRATION_ID,+ integration_name='light.bath',+ )+ # An unrelated disconnected entity whose previous identity+ # is for 'light.attic' — different upstream key entirely.+ Entity.objects.create(+ name='[Disconnected] light.attic',+ entity_type_str='LIGHT',+ previous_integration_id=self.INTEGRATION_ID,+ previous_integration_name='light.attic',+ )++ # Sync sees only 'light.bath' upstream — light.attic is NOT+ # in upstream, so no reconnect attempt for it.+ synchronizer.run_sync_cycle(['light.bath'], result)++ # The disconnected entity is unchanged: still disconnected,+ # not reconnected to light.bath.+ attic = Entity.objects.get(name__contains='attic')+ self.assertIsNone(attic.integration_id)+ self.assertEqual(attic.previous_integration_name, 'light.attic')++ def test_ambiguous_secondary_creates_fresh_entity_with_info_list_note(self):+ """Two disconnected entities share the same+ previous_integration_id + previous_integration_name. When+ upstream re-adds that key, the system has no basis to pick+ one — so it skips reconnect, creates a fresh entity, and+ leaves the duplicates for the user to resolve via merge."""+ synchronizer = self._build_synchronizer()++ Entity.objects.create(+ name='[Detached A] light.foo',+ entity_type_str='LIGHT',+ previous_integration_id=self.INTEGRATION_ID,+ previous_integration_name='light.foo',+ )+ Entity.objects.create(+ name='[Detached B] light.foo',+ entity_type_str='LIGHT',+ previous_integration_id=self.INTEGRATION_ID,+ previous_integration_name='light.foo',+ )++ result = IntegrationSyncResult(title='Ambiguous')+ synchronizer.run_sync_cycle(['light.foo'], result)++ # Three rows now: the two disconnected stragglers + a fresh entity.+ self.assertEqual(Entity.objects.count(), 3)+ # Fresh entity has the active integration_id; previous-identity NULL.+ fresh = Entity.objects.get(integration_id=self.INTEGRATION_ID)+ self.assertEqual(fresh.integration_name, 'light.foo')+ self.assertIsNone(fresh.previous_integration_id)+ # The two disconnected entities are unchanged.+ disconnected = Entity.objects.filter(+ previous_integration_id=self.INTEGRATION_ID,+ )+ self.assertEqual(disconnected.count(), 2)+ # Operator-visible breadcrumb in result.info_list.+ self.assertTrue(any('share that previous identity' in note+ for note in result.info_list))++ def test_single_sync_can_simultaneously_reconnect_and_detach(self):+ """A single sync pass can produce both reconnects and detaches+ in the same run when upstream simultaneously re-adds one+ previously-detached item and drops a different active one.+ Pins the mutual-exclusivity claim in IntegrationSyncResult's+ docstring: the two lists are mutually exclusive *per entity*,+ not per sync run — both fields can be populated in one+ result object."""+ synchronizer = self._build_synchronizer()+ result_pass1 = IntegrationSyncResult(title='Initial')++ # Pass 1: import two entities, both gain user data.+ synchronizer.run_sync_cycle(['light.kitchen', 'light.lounge'], result_pass1)+ for ent in Entity.objects.filter(integration_id=self.INTEGRATION_ID):+ self._user_attribute(ent)++ # Pass 2: drop kitchen → detached.+ result_pass2 = IntegrationSyncResult(title='Drop kitchen')+ synchronizer.run_sync_cycle(['light.lounge'], result_pass2)+ # Confirm precondition: kitchen is detached, lounge is active.+ kitchen = Entity.objects.get(previous_integration_name='light.kitchen')+ self.assertIsNone(kitchen.integration_id)++ # Pass 3: re-add kitchen AND drop lounge — both transitions+ # in the same sync pass.+ result_mixed = IntegrationSyncResult(title='Mixed')+ synchronizer.run_sync_cycle(['light.kitchen'], result_mixed)++ kitchen.refresh_from_db()+ lounge = Entity.objects.get(previous_integration_name='light.lounge')++ # Kitchen reconnected, lounge detached, both in the same result.+ self.assertEqual(kitchen.integration_id, self.INTEGRATION_ID)+ self.assertIsNone(lounge.integration_id)+ self.assertEqual(lounge.previous_integration_id, self.INTEGRATION_ID)+ self.assertEqual(result_mixed.reconnected_list, [kitchen.name])+ self.assertEqual(result_mixed.detached_list, [lounge.name])+ self.assertEqual(result_mixed.removed_list, [])+ self.assertEqual(result_mixed.created_list, [])++ def test_legacy_disconnected_entity_does_not_reconnect(self):+ """An entity disconnected before this feature landed has NO+ previous_integration_id (the column was NULL by default). It+ cannot be auto-reconnected — the system has no signal to use.+ Fresh entity is created instead; user resolves via merge.+ Pinned in the issue's 'Legacy disconnected entities' edge case."""+ synchronizer = self._build_synchronizer()+ result = IntegrationSyncResult(title='Legacy')++ Entity.objects.create(+ name='[Disconnected] light.cellar',+ entity_type_str='LIGHT',+ integration_id=None,+ integration_name=None,+ previous_integration_id=None,+ previous_integration_name=None,+ )++ synchronizer.run_sync_cycle(['light.cellar'], result)++ # Two rows: the legacy one (untouched) + a fresh import.+ self.assertEqual(Entity.objects.count(), 2)+ fresh = Entity.objects.get(integration_id=self.INTEGRATION_ID)+ self.assertEqual(fresh.integration_name, 'light.cellar')+ # Legacy entity is unchanged.+ legacy = Entity.objects.exclude(id=fresh.id).get()+ self.assertEqual(legacy.name, '[Disconnected] light.cellar')+ self.assertIsNone(legacy.integration_id)+ self.assertIsNone(legacy.previous_integration_id)diff --git a/src/hi/integrations/tests/test_models.py b/src/hi/integrations/tests/test_models.pyindex 2d976fef..474a4183 100644--- a/src/hi/integrations/tests/test_models.py+++ b/src/hi/integrations/tests/test_models.py@@ -401,10 +401,75 @@ class IntegrationDetailsModelTestCase(TestCase):# Test setting with falsy valuemock_obj.integration_key = ''-+self.assertIsNone(mock_obj.integration_id)self.assertIsNone(mock_obj.integration_name)+ def test_previous_integration_key_property_round_trip_on_real_model(self):+ """previous_integration_key get/set round-trip on a real+ concrete subclass (Entity). Asserts the property is wired+ correctly to the previous_integration_id /+ previous_integration_name fields independently of the active+ integration_id / integration_name pair.++ Uses Entity directly rather than a re-implemented mock so a+ future refactor of the property cannot silently diverge from+ production behavior."""+ from hi.apps.entity.models import Entity++ entity = Entity.objects.create(+ name='reconnect_test',+ entity_type_str='LIGHT',+ )++ # Default: both previous-identity fields NULL.+ self.assertIsNone(entity.previous_integration_id)+ self.assertIsNone(entity.previous_integration_name)++ # Set via the property.+ prev_key = IntegrationKey('hass', 'light.kitchen')+ entity.previous_integration_key = prev_key++ self.assertEqual(entity.previous_integration_id, 'hass')+ self.assertEqual(entity.previous_integration_name, 'light.kitchen')++ # Get returns an equivalent IntegrationKey.+ round_tripped = entity.previous_integration_key+ self.assertEqual(round_tripped, prev_key)++ # Clearing via None.+ entity.previous_integration_key = None+ self.assertIsNone(entity.previous_integration_id)+ self.assertIsNone(entity.previous_integration_name)++ def test_previous_integration_key_is_independent_of_active_integration_key(self):+ """Setting previous_integration_key must not touch+ integration_id / integration_name, and vice versa. The two+ pairs are semantically independent: an entity can be+ actively connected (active populated, previous NULL),+ disconnected (active NULL, previous populated), or fresh+ (both NULL). Reconnect transitions disconnected → active+ and the symmetry of the two setters is what makes that+ transition safe."""+ from hi.apps.entity.models import Entity++ entity = Entity.objects.create(+ name='independence_test',+ entity_type_str='LIGHT',+ integration_id='hass',+ integration_name='light.living_room',+ )++ # Setting previous_integration_key leaves the active pair alone.+ entity.previous_integration_key = IntegrationKey('zoneminder', 'monitor.4')+ self.assertEqual(entity.integration_id, 'hass')+ self.assertEqual(entity.integration_name, 'light.living_room')++ # Clearing the active pair leaves the previous pair alone.+ entity.integration_key = None+ self.assertEqual(entity.previous_integration_id, 'zoneminder')+ self.assertEqual(entity.previous_integration_name, 'monitor.4')+def test_get_integration_details_method(self):"""Test get_integration_details method returns correct IntegrationDetails."""class MockIntegrationDetails:diff --git a/src/hi/requirements/base.txt b/src/hi/requirements/base.txtindex ff669445..67bc1fb3 100644--- a/src/hi/requirements/base.txt+++ b/src/hi/requirements/base.txt@@ -18,7 +18,7 @@ pillow==12.2.0Pint==0.25psutil==6.0.0python-dateutil==2.9.0.post0-python-dotenv==1.1.2+python-dotenv==1.2.2python-utils==3.9.1pytz==2025.2redis==5.2.0diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex 366e5673..6dbcc959 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -483,20 +483,32 @@ class HassConverter:@classmethoddef create_models_for_hass_device( cls,hass_device : HassDevice,- add_alarm_events : bool ) -> Entity:-+ add_alarm_events : bool,+ entity : Optional[Entity] = None ) -> Entity:+ """+ Create or repopulate the integration-owned components for a+ HassDevice. When ``entity`` is None (the standard import path),+ a fresh Entity is created from the upstream device. When+ ``entity`` is provided (the auto-reconnect path from Issue+ #281), the integration-owned fields on that entity are+ repopulated; the entity's ``name`` is deliberately preserved+ because the user may have edited it before/after the+ intervening disconnect.+ """with transaction.atomic():entity_integration_key = cls.hass_device_to_integration_key( hass_device = hass_device )- entity_name = cls.hass_device_to_entity_name( hass_device )- entity_type = cls.hass_device_to_entity_type( hass_device )-- entity = Entity(- name = entity_name,- entity_type_str = str(entity_type),- can_user_delete = HassMetaData.allow_entity_deletion,- )++ if entity is None:+ entity = Entity(+ name = cls.hass_device_to_entity_name( hass_device ),+ entity_type_str = str( cls.hass_device_to_entity_type( hass_device ) ),+ )++ # Integration-owned: re-applied on both fresh-create and+ # reconnect so the entity reflects current upstream state.entity.integration_key = entity_integration_key+ entity.can_user_delete = HassMetaData.allow_entity_deletionentity.save()insteon_address = cls.hass_device_to_insteon_address( hass_device )diff --git a/src/hi/services/hass/hass_sync.py b/src/hi/services/hass/hass_sync.pyindex 0687ba6e..74b9fcb1 100644--- a/src/hi/services/hass/hass_sync.py+++ b/src/hi/services/hass/hass_sync.py@@ -25,6 +25,9 @@ logger = logging.getLogger(__name__)class HassSynchronizer( IntegrationSynchronizer, HassMixin ):+ def get_integration_metadata(self):+ return HassMetaData+def get_description(self, is_initial_import: bool) -> Optional[str]:if is_initial_import:return 'Only items matching your Allowed Item Types setting will be imported.'@@ -77,10 +80,24 @@ class HassSynchronizer( IntegrationSynchronizer, HassMixin ):for hass_device in hass_device_id_to_device.values()}+ # Issue #281 reconnect pre-pass (framework-level). Any+ # disconnected entity whose previous identity matches an+ # unmatched upstream device is reconnected in place and+ # added to integration_key_to_entity, so the main loop below+ # treats it as primary-matched without any reconnect-aware+ # branching.+ self.reconnect_disconnected_items(+ integration_key_to_upstream = integration_key_to_hass_device,+ integration_key_to_entity = integration_key_to_entity,+ result = result,+ )+# Track newly-created entities only — existing-entity updates# don't need re-placement and shouldn't surface in the- # dispatcher modal (refresh-with-no-new-items must produce- # an empty sync result).+ # placement modal (refresh-with-no-new-items must produce+ # an empty sync result). Reconnected entities are also+ # excluded: their layout/collection memberships are preserved+ # by reconnect (Part 3 contract) so they don't need placement.created_entities: List[Entity] = []with transaction.atomic():@@ -108,6 +125,21 @@ class HassSynchronizer( IntegrationSynchronizer, HassMixin ):)return result+ def _rebuild_integration_components( self,+ entity : Entity,+ upstream : HassDevice,+ result : IntegrationSyncResult ):+ """Issue #281: dispatch to the HASS converter with the+ existing-entity parameter set, so the converter repopulates+ integration-owned components on the previously-disconnected+ entity rather than creating a fresh one."""+ HassConverter.create_models_for_hass_device(+ hass_device = upstream,+ add_alarm_events = self.hass_manager().should_add_alarm_events,+ entity = entity,+ )+ return+def _get_existing_hass_entities( self, result : IntegrationSyncResult ) -> Dict[ IntegrationKey, Entity ]:logger.debug( 'Getting existing HAss entities.' )integration_key_to_entity = dict()@@ -160,7 +192,7 @@ class HassSynchronizer( IntegrationSynchronizer, HassMixin ):Uses intelligent deletion that preserves user-created data."""- self._remove_entity_intelligently(entity, result, 'HASS')+ self._remove_entity_intelligently(entity, result)returndef group_entities_for_placement( self, entities ) -> EntityPlacementInput:diff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.pynew file mode 100644index 00000000..a927f99b--- /dev/null+++ b/src/hi/services/hass/tests/test_hass_converter_create.py@@ -0,0 +1,158 @@+"""+Pre-refactor safety net for HassConverter.create_models_for_hass_device.++The Phase 3 refactor of Issue #281 will change this entrypoint's+signature to accept an optional existing Entity (for the auto-reconnect+path). These tests pin the current "create a new Entity from upstream+payload" contract so the refactor can't silently regress it.++Coverage is deliberately narrow: one happy-path assertion that the+entrypoint produces an Entity with the right integration_key + at least+one ancillary component. State-mapping branches are already covered by+test_hass_converter_mapping.py.+"""+import logging++from django.test import TestCase++from hi.apps.entity.models import Entity, EntityState+from hi.services.hass.hass_converter import HassConverter+from hi.services.hass.hass_metadata import HassMetaData+from hi.services.hass.hass_models import HassDevice++logging.disable(logging.CRITICAL)+++class CreateModelsForHassDeviceCreateNewContractTests(TestCase):+ """Pin the create-new-entity contract before the optional-entity refactor."""++ def _build_simple_light_device(self, device_id='kitchen_light'):+ """Hand-built HassDevice with a single light HassState — enough+ to drive the converter through entity + state + sensor/controller+ creation without coupling to specific fixture JSON."""+ api_dict = {+ 'entity_id': f'light.{device_id}',+ 'state': 'on',+ 'attributes': {+ 'friendly_name': device_id.replace('_', ' ').title(),+ 'supported_color_modes': ['onoff'],+ 'color_mode': 'onoff',+ },+ 'last_changed': '2026-01-01T00:00:00+00:00',+ 'last_reported': '2026-01-01T00:00:00+00:00',+ 'last_updated': '2026-01-01T00:00:00+00:00',+ 'context': {'id': 'ctx', 'parent_id': None, 'user_id': None},+ }+ hass_state = HassConverter.create_hass_state(api_dict)+ device = HassDevice(device_id=device_id)+ device.add_state(hass_state)+ return device++ def test_creates_entity_with_correct_integration_key(self):+ device = self._build_simple_light_device()++ entity = HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ )++ self.assertIsInstance(entity, Entity)+ self.assertEqual(entity.integration_id, HassMetaData.integration_id)+ # integration_name is set from the device — converter normalizes it.+ self.assertIsNotNone(entity.integration_name)+ self.assertTrue(entity.integration_name)++ def test_creates_at_least_one_entity_state_for_the_device(self):+ device = self._build_simple_light_device()++ entity = HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ )++ # Light produces at least one EntityState (the on/off state).+ self.assertGreaterEqual(EntityState.objects.filter(entity=entity).count(), 1)+++class CreateModelsForHassDeviceReconnectContractTests(TestCase):+ """+ Pin the reconnect contract added in Issue #281 Phase 3:+ when ``entity`` is provided, the converter populates that entity's+ integration-owned components without creating a new Entity row and+ without overwriting the entity's name. The user may have edited+ the name before/after the intervening disconnect; reconnect must+ not clobber that.+ """++ def _build_simple_light_device(self, device_id='kitchen_light'):+ api_dict = {+ 'entity_id': f'light.{device_id}',+ 'state': 'on',+ 'attributes': {+ 'friendly_name': device_id.replace('_', ' ').title(),+ 'supported_color_modes': ['onoff'],+ 'color_mode': 'onoff',+ },+ 'last_changed': '2026-01-01T00:00:00+00:00',+ 'last_reported': '2026-01-01T00:00:00+00:00',+ 'last_updated': '2026-01-01T00:00:00+00:00',+ 'context': {'id': 'ctx', 'parent_id': None, 'user_id': None},+ }+ hass_state = HassConverter.create_hass_state(api_dict)+ device = HassDevice(device_id=device_id)+ device.add_state(hass_state)+ return device++ def test_with_existing_entity_does_not_create_new_entity(self):+ from hi.apps.entity.models import Entity as EntityModel++ # Pre-existing user-renamed entity (simulating one that was+ # disconnected and is now being reconnected).+ existing = EntityModel.objects.create(+ name='User Renamed Light',+ entity_type_str='LIGHT',+ )+ device = self._build_simple_light_device()+ baseline_count = EntityModel.objects.count()++ result = HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ entity=existing,+ )++ self.assertEqual(EntityModel.objects.count(), baseline_count)+ self.assertEqual(result.id, existing.id)++ def test_with_existing_entity_preserves_entity_name(self):+ existing = Entity.objects.create(+ name='User Renamed Light',+ entity_type_str='LIGHT',+ )+ device = self._build_simple_light_device()++ HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ entity=existing,+ )++ existing.refresh_from_db()+ self.assertEqual(existing.name, 'User Renamed Light')++ def test_with_existing_entity_sets_integration_key(self):+ existing = Entity.objects.create(+ name='User Renamed Light',+ entity_type_str='LIGHT',+ )+ device = self._build_simple_light_device()++ HassConverter.create_models_for_hass_device(+ hass_device=device,+ add_alarm_events=False,+ entity=existing,+ )++ existing.refresh_from_db()+ self.assertEqual(existing.integration_id, HassMetaData.integration_id)+ self.assertIsNotNone(existing.integration_name)diff --git a/src/hi/services/homebox/hb_converter.py b/src/hi/services/homebox/hb_converter.pyindex f43e4dc4..2900e1c6 100644--- a/src/hi/services/homebox/hb_converter.py+++ b/src/hi/services/homebox/hb_converter.py@@ -27,24 +27,41 @@ class HbConverter:]@classmethod- def create_models_for_hb_item( cls, hb_item: HbItem ) -> Entity:-+ def create_models_for_hb_item( cls,+ hb_item : HbItem,+ entity : Optional[Entity] = None ) -> Entity:+ """+ Create or repopulate the integration-owned components for an+ HbItem. When ``entity`` is None (the standard import path), a+ fresh Entity is created from the upstream payload. When+ ``entity`` is provided (the auto-reconnect path from Issue+ #281), the integration-owned fields on that entity are+ repopulated; the entity's ``name`` is deliberately preserved+ because the user may have edited it before/after the+ intervening disconnect.+ """with transaction.atomic():entity_integration_key = cls.hb_item_to_integration_key( hb_item = hb_item )- entity_name = cls.hb_item_to_entity_name( hb_item = hb_item )- entity_type = cls.hb_item_to_entity_type( hb_item = hb_item )-- entity = Entity(- name = entity_name,- entity_type_str = str(entity_type),- can_user_delete = HbMetaData.allow_entity_deletion,- can_add_custom_attributes = HbMetaData.can_add_custom_attributes,- integration_payload = cls.hb_item_to_entity_payload( hb_item = hb_item ),- )+ entity_payload = cls.hb_item_to_entity_payload( hb_item = hb_item )+ if entity is None:+ entity = Entity(+ name = cls.hb_item_to_entity_name( hb_item = hb_item ),+ entity_type_str = str( cls.hb_item_to_entity_type( hb_item = hb_item ) ),+ )++ # The fields below apply equally to fresh-create and+ # reconnect: integration_key, integration_payload, and the+ # integration-managed access flags are all integration-owned+ # and must reflect the current upstream state. The entity+ # name and entity_type are intentionally left alone on the+ # reconnect path (set above only for fresh-create).entity.integration_key = entity_integration_key+ entity.integration_payload = entity_payload+ entity.can_user_delete = HbMetaData.allow_entity_deletion+ entity.can_add_custom_attributes = HbMetaData.can_add_custom_attributesentity.save()-+return entity@classmethoddiff --git a/src/hi/services/homebox/hb_sync.py b/src/hi/services/homebox/hb_sync.pyindex 16752648..1b1f0262 100644--- a/src/hi/services/homebox/hb_sync.py+++ b/src/hi/services/homebox/hb_sync.py@@ -19,6 +19,9 @@ logger = logging.getLogger(__name__)class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):+ def get_integration_metadata(self):+ return HbMetaData+def get_description(self, is_initial_import: bool) -> Optional[str]:return ('HomeBox Labels and Locations are kept as metadata on '@@ -85,6 +88,17 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):integration_key_to_entity = self._get_existing_hb_entities( result = result )result.info_list.append( f'Found {len(integration_key_to_entity)} existing HomeBox items.' )+ # Issue #281 reconnect pre-pass (framework-level). Any+ # disconnected entity whose previous identity matches an+ # unmatched upstream item is reconnected in place and added+ # to integration_key_to_entity, so the main loop below treats+ # it as primary-matched without any reconnect-aware branching.+ self.reconnect_disconnected_items(+ integration_key_to_upstream = integration_key_to_item,+ integration_key_to_entity = integration_key_to_entity,+ result = result,+ )+created_entities: List[Entity] = []with transaction.atomic():for integration_key, hb_item in integration_key_to_item.items():@@ -112,6 +126,20 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):continuereturn created_entities+ def _rebuild_integration_components( self,+ entity : Entity,+ upstream : HbItem,+ result : IntegrationSyncResult ):+ """Issue #281: dispatch to the HomeBox converter with the+ existing-entity parameter set, so the converter repopulates+ integration-owned components on the previously-disconnected+ entity rather than creating a fresh one."""+ HbConverter.create_models_for_hb_item(+ hb_item = upstream,+ entity = entity,+ )+ return+def _get_existing_hb_entities( self, result : IntegrationSyncResult ) -> Dict[ IntegrationKey, Entity ]:logger.debug( 'Getting existing HomeBox entities.' )integration_key_to_entity = dict()@@ -156,7 +184,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):def _remove_entity( self,entity : Entity,result : IntegrationSyncResult ):- self._remove_entity_intelligently( entity, result, 'HomeBox' )+ self._remove_entity_intelligently( entity, result )returndef _sync_helper_entity_attributes( self,diff --git a/src/hi/services/homebox/tests/test_hb_converter.py b/src/hi/services/homebox/tests/test_hb_converter.pyindex d40518cc..2d1ab576 100644--- a/src/hi/services/homebox/tests/test_hb_converter.py+++ b/src/hi/services/homebox/tests/test_hb_converter.py@@ -48,6 +48,36 @@ class TestHbConverter(TestCase):self.assertEqual(entity.integration_payload.get('location', {}).get('name'), 'Garage')self.assertEqual(entity.integration_payload.get('labels')[0].get('name'), 'Tools')+ def test_create_models_with_existing_entity_does_not_create_new_and_preserves_name(self):+ """Issue #281 reconnect contract: when an existing Entity is+ passed in, repopulate its integration-owned fields without+ creating a new row and without overwriting the (possibly+ user-edited) name."""+ existing = Entity.objects.create(+ name='User Renamed Item',+ entity_type_str=str(EntityType.SERVICE),+ )+ baseline_count = Entity.objects.count()+ item = self._mock_item(item_id='item-reconnect', name='Upstream Drill Name')++ returned = HbConverter.create_models_for_hb_item(+ hb_item=item,+ entity=existing,+ )++ self.assertEqual(Entity.objects.count(), baseline_count)+ self.assertEqual(returned.id, existing.id)+ existing.refresh_from_db()+ # Name preserved (NOT 'Upstream Drill Name').+ self.assertEqual(existing.name, 'User Renamed Item')+ # Integration-owned fields repopulated from upstream.+ self.assertEqual(existing.integration_id, HbMetaData.integration_id)+ self.assertEqual(existing.integration_name, 'item-reconnect')+ self.assertEqual(+ existing.integration_payload.get('location', {}).get('name'),+ 'Garage',+ )+def test_update_models_for_hb_item_updates_name_type_and_payload(self):entity = Entity.objects.create(name='Old Name',diff --git a/src/hi/services/homebox/tests/test_hb_sync.py b/src/hi/services/homebox/tests/test_hb_sync.pyindex 4d792278..23a22a74 100644--- a/src/hi/services/homebox/tests/test_hb_sync.py+++ b/src/hi/services/homebox/tests/test_hb_sync.py@@ -100,6 +100,15 @@ class TestHomeBoxSynchronizer(SimpleTestCase):sync_attrs_mock = stack.enter_context(patch.object(synchronizer, '_sync_helper_entity_attributes'))+ # Reconnect pre-pass (Issue #281) is framework-level on+ # IntegrationSynchronizer.reconnect_disconnected_items and+ # does its own DB query; this SimpleTestCase doesn't allow+ # DB access, so stub it out. The reconnect logic itself+ # is covered by FindReconnectCandidatesTests in+ # test_entity_operations.py.+ stack.enter_context(+ patch.object(synchronizer, 'reconnect_disconnected_items')+ )synchronizer._sync_helper_entities(item_list=[item_new, item_existing, item_invalid],@@ -353,3 +362,37 @@ class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):# No newly-created entities → placement_input is None.self.assertIsNone(result.placement_input)+++class TestHomeBoxSynchronizerRebuildIntegrationComponents(SimpleTestCase):+ """+ Issue #281: the per-integration ``_rebuild_integration_components``+ override is the only piece each synchronizer contributes to the+ framework-level reconnect path. This test verifies that+ HomeBoxSynchronizer's override dispatches to ``HbConverter`` with+ the existing-entity argument set. Framework-level behavior+ (find candidates, strip prefix, clear previous identity, update+ entity map, info_list note) is covered by tests of+ IntegrationSynchronizer.reconnect_disconnected_items. End-to-end+ DB cycle is exercised in Phase 6.+ """++ def test_dispatches_to_converter_with_existing_entity(self):+ synchronizer = HomeBoxSynchronizer()+ result = IntegrationSyncResult(title='HomeBox Test')+ existing_entity = Mock(name='existing_entity')+ upstream = Mock(name='hb_item')++ with patch(+ 'hi.services.homebox.hb_sync.HbConverter.create_models_for_hb_item'+ ) as mock_converter:+ synchronizer._rebuild_integration_components(+ entity=existing_entity,+ upstream=upstream,+ result=result,+ )++ mock_converter.assert_called_once_with(+ hb_item=upstream,+ entity=existing_entity,+ )diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.pyindex 78c658fa..29cd4bc6 100644--- a/src/hi/services/zoneminder/tests/test_zm_sync.py+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py@@ -7,6 +7,7 @@ from django.test import TestCasefrom hi.apps.entity.models import Entityfrom hi.apps.sense.models import Sensor+from hi.integrations.integration_manager import IntegrationManagerfrom hi.integrations.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKey@@ -137,8 +138,8 @@ class TestZoneMinderSynchronizerStateSync(TestCase):)self.synchronizer._zm_manager = self.mock_manager- @patch.object(Entity.objects, 'filter_by_integration_key')- @patch.object(Sensor.objects, 'filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')@patch.object(ZoneMinderSynchronizer, '_create_zm_entity')def test_sync_states_creates_zm_entity_when_missing(self, mock_create_entity, mock_sensor_filter, mock_entity_filter):"""Test _sync_states creates ZM entity when it doesn't exist and verifies entity creation parameters"""@@ -185,8 +186,8 @@ class TestZoneMinderSynchronizerStateSync(TestCase):# Test behavior: should not have errors when successfulself.assertEqual(len(result.error_list), 0)- @patch.object(Entity.objects, 'filter_by_integration_key')- @patch.object(Sensor.objects, 'filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')def test_sync_states_missing_sensor_error(self, mock_sensor_filter, mock_entity_filter):"""Test _sync_states handles missing run state sensor and stops processing gracefully"""# Mock states@@ -213,8 +214,8 @@ class TestZoneMinderSynchronizerStateSync(TestCase):# Should not have created any entities since sensor missingself.assertEqual(len(result.info_list), 0)- @patch.object(Entity.objects, 'filter_by_integration_key')- @patch.object(Sensor.objects, 'filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')def test_sync_states_updates_value_range_when_changed(self, mock_sensor_filter, mock_entity_filter):"""Test _sync_states updates value range when states change and persists changes"""# Mock new states@@ -260,8 +261,8 @@ class TestZoneMinderSynchronizerStateSync(TestCase):self.assertIn('start', message)self.assertIn('pause', message)- @patch.object(Entity.objects, 'filter_by_integration_key')- @patch.object(Sensor.objects, 'filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')def test_sync_states_no_update_when_unchanged(self, mock_sensor_filter, mock_entity_filter):"""Test _sync_states doesn't update when state values unchanged and preserves existing state"""# Mock states - identical to existing@@ -484,7 +485,7 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'self.synchronizer._zm_manager = self.mock_manager- @patch.object(Entity.objects, 'filter')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')def test_get_existing_zm_monitor_entities_filters_by_integration_id(self, mock_filter):"""Test _get_existing_zm_monitor_entities filters by correct integration ID"""mock_filter.return_value = []@@ -494,7 +495,7 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):mock_filter.assert_called_once_with(integration_id=ZmMetaData.integration_id)- @patch.object(Entity.objects, 'filter')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')def test_get_existing_zm_monitor_entities_handles_missing_integration_key(self, mock_filter):"""Test entity retrieval handles entities without integration keys"""# Mock entity without integration key@@ -512,7 +513,7 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):# Should NOT include entity in result (mock key doesn't start with 'monitor' prefix)self.assertEqual(len(result_dict), 0)- @patch.object(Entity.objects, 'filter')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')def test_get_existing_zm_monitor_entities_filters_monitor_entities(self, mock_filter):"""Test entity retrieval only includes monitor entities"""# Mock entities - one monitor, one non-monitor@@ -535,119 +536,6 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):self.assertNotIn(other_key, result_dict)-class TestZoneMinderSynchronizerEntityCreation(TestCase):- """Test entity creation with database transactions"""-- def setUp(self):- self.synchronizer = ZoneMinderSynchronizer()-- # Mock the zm_manager- self.mock_manager = Mock()- self.mock_manager.ZM_ENTITY_NAME = 'ZoneMinder'- self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'- self.mock_manager.VIDEO_STREAM_SENSOR_PREFIX = 'monitor.video_stream'- self.mock_manager.MOVEMENT_SENSOR_PREFIX = 'monitor.motion'- self.mock_manager.MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'- self.mock_manager.MOVEMENT_EVENT_PREFIX = 'monitor.motion'- self.mock_manager.should_add_alarm_events = True- self.synchronizer._zm_manager = self.mock_manager-- @patch('hi.services.zoneminder.zm_sync.transaction.atomic')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')- @patch.object(Entity, 'save')- def test_create_zm_entity_uses_transaction(self, mock_save, mock_create_controller, mock_atomic):- """Test _create_zm_entity uses database transaction"""- run_state_dict = {'start': 'start', 'stop': 'stop'}-- mock_integration_key = IntegrationKey(integration_id='zm', integration_name='system')- self.mock_manager._zm_integration_key.return_value = mock_integration_key- self.mock_manager._zm_run_state_integration_key.return_value = IntegrationKey(- integration_id='zm', integration_name='run.state'- )-- result = IntegrationSyncResult(title='Test')- self.synchronizer._create_zm_entity(run_state_dict, result)-- mock_atomic.assert_called_once()- mock_save.assert_called_once()- mock_create_controller.assert_called_once()-- @patch('hi.services.zoneminder.zm_sync.transaction.atomic')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')- @patch.object(Entity, 'save')- def test_create_monitor_entity_creates_all_components(self, mock_save, mock_create_event,- mock_create_controller, mock_create_movement,- mock_atomic):- """Test _create_monitor_entity creates all required sensors and controllers"""- # Mock monitor- mock_monitor = Mock()- mock_monitor.id.return_value = 123- mock_monitor.name.return_value = 'Front Door'-- # Mock integration key generation- entity_key = IntegrationKey(integration_id='zm', integration_name='monitor.123')- movement_key = IntegrationKey(integration_id='zm', integration_name='monitor.motion.123')- function_key = IntegrationKey(integration_id='zm', integration_name='monitor.function.123')- event_key = IntegrationKey(integration_id='zm', integration_name='monitor.motion.123')-- self.mock_manager._to_integration_key.side_effect = [- entity_key, movement_key, function_key, event_key- ]-- # Mock movement sensor for event creation- mock_movement_sensor = Mock()- mock_movement_sensor.name = 'Front Door Motion'- mock_movement_sensor.entity_state = Mock()- mock_create_movement.return_value = mock_movement_sensor-- result = IntegrationSyncResult(title='Test')- self.synchronizer._create_monitor_entity(mock_monitor, result)-- # Should create all components- mock_create_movement.assert_called_once()- mock_create_controller.assert_called_once()- mock_create_event.assert_called_once()-- # Should use transaction- mock_atomic.assert_called_once()- mock_save.assert_called_once()-- @patch('hi.services.zoneminder.zm_sync.transaction.atomic')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')- @patch.object(Entity, 'save')- def test_create_monitor_entity_skips_events_when_disabled(self, mock_save, mock_create_event,- mock_create_controller, mock_create_movement,- mock_atomic):- """Test _create_monitor_entity skips event creation when alarm events disabled"""- self.mock_manager.should_add_alarm_events = False-- mock_monitor = Mock()- mock_monitor.id.return_value = 123- mock_monitor.name.return_value = 'Front Door'-- # Mock integration key generation- self.mock_manager._to_integration_key.side_effect = [- Mock(), Mock(), Mock(), Mock() # entity, video, movement, function keys- ]-- mock_movement_sensor = Mock()- mock_create_movement.return_value = mock_movement_sensor-- result = IntegrationSyncResult(title='Test')- self.synchronizer._create_monitor_entity(mock_monitor, result)-- # Should not create event- mock_create_event.assert_not_called()-- # Should still create other components- mock_create_movement.assert_called_once()- mock_create_controller.assert_called_once()--class TestZoneMinderSynchronizerEntityUpdate(TestCase):"""Test entity update logic"""@@ -725,7 +613,7 @@ class TestZoneMinderSynchronizerEntityRemoval(TestCase):self.synchronizer._remove_entity(mock_entity, result)- mock_intelligent_removal.assert_called_once_with(mock_entity, result, 'ZoneMinder')+ mock_intelligent_removal.assert_called_once_with(mock_entity, result)class TestZoneMinderSynchronizerFunctionConstants(TestCase):@@ -793,8 +681,8 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):mock_monitors.append(mock_monitor)return mock_monitors- @patch.object(Entity.objects, 'filter_by_integration_key')- @patch.object(Sensor.objects, 'filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')+ @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')def test_sync_states_with_real_zm_state_names(self, mock_sensor_filter, mock_entity_filter):"""Test state sync handles real ZM state names: default, Away, HomeDay, Disabled"""# Use real state data@@ -905,7 +793,7 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):mock_entity.save.assert_called_once()self.assertEqual(result.updated_list, ['Camera_001 → HighCamera'])- @patch.object(Entity.objects, 'filter')+ @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')def test_get_existing_entities_with_real_monitor_id_patterns(self, mock_filter):"""Test existing entity retrieval with realistic monitor ID patterns"""# Create mock entities with integration keys matching real monitor IDs@@ -1068,3 +956,158 @@ class TestZoneMinderSynchronizerSyncResultGrouping(TestCase):# No newly-created entities → no placement input → placement# modal is not shown.self.assertIsNone(result.placement_input)+++class CreateMonitorEntityCreateNewContractTests(TestCase):+ """+ Pre-refactor safety net for ``ZoneMinderSynchronizer._create_monitor_entity``.++ Phase 3 of Issue #281 will refactor this method to accept an+ optional existing Entity (for the auto-reconnect path). These+ tests pin the current "create a new Entity from upstream+ monitor" contract — real DB persistence, not mocks — so the+ refactor cannot silently regress entity / sensor / controller+ creation.+ """++ def setUp(self):+ # IntegrationManager is a process-wide singleton; reset its+ # in-memory state so prior tests in the suite cannot pollute+ # ours (and ours cannot pollute theirs).+ IntegrationManager().reset_for_testing()++ self.synchronizer = ZoneMinderSynchronizer()++ self.mock_manager = Mock()+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'+ self.mock_manager.MOVEMENT_SENSOR_PREFIX = 'monitor.motion'+ self.mock_manager.MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'+ self.mock_manager.MOVEMENT_EVENT_PREFIX = 'monitor.motion'+ # Skip alarm event creation to keep this safety net narrow —+ # event-definition creation is exercised elsewhere.+ self.mock_manager.should_add_alarm_events = False++ def make_key(prefix, zm_monitor_id):+ return IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=f'{prefix}.{zm_monitor_id}',+ )+ self.mock_manager._to_integration_key.side_effect = make_key++ self.synchronizer._zm_manager = self.mock_manager++ def _mock_monitor(self, monitor_id=42, name='Driveway'):+ monitor = Mock()+ monitor.id.return_value = monitor_id+ monitor.name.return_value = name+ return monitor++ def test_creates_entity_with_camera_type_and_correct_integration_key(self):+ result = IntegrationSyncResult(title='Test')+ monitor = self._mock_monitor(monitor_id=42, name='Driveway')++ entity = self.synchronizer._create_monitor_entity(+ zm_monitor=monitor,+ result=result,+ )++ from hi.apps.entity.enums import EntityType+ self.assertIsInstance(entity, Entity)+ self.assertEqual(entity.name, 'Driveway')+ self.assertEqual(entity.entity_type, EntityType.CAMERA)+ self.assertEqual(entity.integration_id, ZmMetaData.integration_id)+ self.assertEqual(entity.integration_name, 'monitor.42')+ self.assertTrue(entity.has_video_stream)++ def test_creates_movement_sensor_and_function_controller_for_monitor(self):+ result = IntegrationSyncResult(title='Test')+ monitor = self._mock_monitor(monitor_id=43, name='Front Door')++ entity = self.synchronizer._create_monitor_entity(+ zm_monitor=monitor,+ result=result,+ )++ # The monitor's movement sensor should exist on a per-entity basis.+ self.assertGreaterEqual(Sensor.objects.filter(entity_state__entity=entity).count(), 1)+++class CreateMonitorEntityReconnectContractTests(TestCase):+ """+ Pin the reconnect contract added in Issue #281 Phase 3:+ when ``entity`` is provided, ``_create_monitor_entity`` populates+ that entity's integration-owned components without creating a new+ Entity row and without overwriting the entity's name.+ """++ def setUp(self):+ IntegrationManager().reset_for_testing()+ self.synchronizer = ZoneMinderSynchronizer()+ self.mock_manager = Mock()+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'+ self.mock_manager.MOVEMENT_SENSOR_PREFIX = 'monitor.motion'+ self.mock_manager.MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'+ self.mock_manager.MOVEMENT_EVENT_PREFIX = 'monitor.motion'+ self.mock_manager.should_add_alarm_events = False+ self.mock_manager._to_integration_key.side_effect = lambda prefix, zm_monitor_id: IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=f'{prefix}.{zm_monitor_id}',+ )+ self.synchronizer._zm_manager = self.mock_manager++ def _mock_monitor(self, monitor_id=99, name='Driveway'):+ monitor = Mock()+ monitor.id.return_value = monitor_id+ monitor.name.return_value = name+ return monitor++ def test_with_existing_entity_does_not_create_new_entity(self):+ existing = Entity.objects.create(+ name='User Renamed Camera',+ entity_type_str='CAMERA',+ )+ baseline_count = Entity.objects.count()+ result = IntegrationSyncResult(title='Test')++ returned = self.synchronizer._create_monitor_entity(+ zm_monitor=self._mock_monitor(monitor_id=99, name='Upstream Driveway'),+ result=result,+ entity=existing,+ )++ self.assertEqual(Entity.objects.count(), baseline_count)+ self.assertEqual(returned.id, existing.id)++ def test_with_existing_entity_preserves_entity_name(self):+ existing = Entity.objects.create(+ name='User Renamed Camera',+ entity_type_str='CAMERA',+ )+ result = IntegrationSyncResult(title='Test')++ self.synchronizer._create_monitor_entity(+ zm_monitor=self._mock_monitor(monitor_id=100, name='Upstream Camera'),+ result=result,+ entity=existing,+ )++ existing.refresh_from_db()+ self.assertEqual(existing.name, 'User Renamed Camera')++ def test_with_existing_entity_sets_integration_key_and_video_flag(self):+ existing = Entity.objects.create(+ name='User Renamed Camera',+ entity_type_str='CAMERA',+ )+ result = IntegrationSyncResult(title='Test')++ self.synchronizer._create_monitor_entity(+ zm_monitor=self._mock_monitor(monitor_id=101, name='Upstream Camera'),+ result=result,+ entity=existing,+ )++ existing.refresh_from_db()+ self.assertEqual(existing.integration_id, ZmMetaData.integration_id)+ self.assertEqual(existing.integration_name, 'monitor.101')+ self.assertTrue(existing.has_video_stream)diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.pyindex 5662519f..a9472091 100644--- a/src/hi/services/zoneminder/zm_sync.py+++ b/src/hi/services/zoneminder/zm_sync.py@@ -28,6 +28,9 @@ logger = logging.getLogger(__name__)class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):+ def get_integration_metadata(self):+ return ZmMetaData+MONITOR_FUNCTION_NAME_LABEL_DICT = {'None': 'None','Monitor': 'Monitor',@@ -137,6 +140,18 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):integration_key_to_entity = self._get_existing_zm_monitor_entities( result = result )result.info_list.append( f'Found {len(integration_key_to_entity)} existing ZM items.' )+ # Issue #281 reconnect pre-pass (framework-level). Any+ # disconnected entity whose previous identity matches an+ # unmatched upstream monitor is reconnected in place and+ # added to integration_key_to_entity, so the main loop+ # below treats it as primary-matched without any+ # reconnect-aware branching.+ self.reconnect_disconnected_items(+ integration_key_to_upstream = integration_key_to_monitor,+ integration_key_to_entity = integration_key_to_entity,+ result = result,+ )+created_entities = []for integration_key, zm_monitor in integration_key_to_monitor.items():entity = integration_key_to_entity.get( integration_key )@@ -158,6 +173,22 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):return created_entities+ def _rebuild_integration_components( self,+ entity : Entity,+ upstream : ZmMonitor,+ result : IntegrationSyncResult ):+ """Issue #281: dispatch to the ZoneMinder monitor-entity+ converter with the existing-entity parameter set, so the+ converter repopulates integration-owned components on the+ previously-disconnected entity rather than creating a fresh+ one."""+ self._create_monitor_entity(+ zm_monitor = upstream,+ result = result,+ entity = entity,+ )+ return+def _fetch_zm_monitors( self, result : IntegrationSyncResult ) -> Dict[ IntegrationKey, ZmMonitor ]:zm_manager = self.zm_manager()@@ -224,7 +255,17 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):def _create_monitor_entity( self,zm_monitor : ZmMonitor,- result : IntegrationSyncResult ) -> Entity:+ result : IntegrationSyncResult,+ entity : Optional[Entity] = None ) -> Entity:+ """+ Create or repopulate the integration-owned components for a+ ZoneMinder monitor. When ``entity`` is None (the standard+ import path), a fresh Entity is created. When ``entity`` is+ provided (the auto-reconnect path from Issue #281), the+ integration-owned fields on that entity are repopulated; the+ entity's ``name`` is deliberately preserved because the user+ may have edited it before/after the intervening disconnect.+ """zm_manager = self.zm_manager()with transaction.atomic():@@ -232,13 +273,18 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):prefix = zm_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX,zm_monitor_id = zm_monitor.id(),)- entity = Entity(- name = zm_monitor.name(),- entity_type_str = str(EntityType.CAMERA),- can_user_delete = ZmMetaData.allow_entity_deletion,- has_video_stream = True,- )++ if entity is None:+ entity = Entity(+ name = zm_monitor.name(),+ entity_type_str = str(EntityType.CAMERA),+ )++ # Integration-owned: re-applied on both fresh-create and+ # reconnect so the entity reflects current upstream state.entity.integration_key = entity_integration_key+ entity.can_user_delete = ZmMetaData.allow_entity_deletion+ entity.has_video_stream = Trueentity.save()movement_sensor = HiModelHelper.create_movement_sensor(@@ -294,5 +340,5 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):TODO: Should we remove the EventDefinitions that were auto-created (with integration key)?"""- self._remove_entity_intelligently(entity, result, 'ZoneMinder')+ self._remove_entity_intelligently(entity, result)returndiff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex 9f6a1844..4fb00c13 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -11,12 +11,13 @@ Five profiles, each designed to exercise a specific scenario:device types, a handful of HomeBox items, afew ZM monitors. Used as the *before* statefor delta tests.- * baseline-changed — same shape as baseline, with one removal,- one rename, and one addition per integration.- Importing baseline then switching the- simulator to this profile and clicking- Refresh exercises every change kind in a- single click.+ * baseline-changed — same shape as baseline, with deltas in every+ integration. The pair (baseline ↔+ baseline-changed) is designed to exercise all+ five sync-result categories — created,+ updated, reconnected, detached, removed — in+ a single flip back-and-forth. See "Operator+ workflow for full-category coverage" below.* hass-zoo — one HASS entity of every supported type.Visual / grouping coverage for the HASSconverter; HomeBox/ZM stay empty.@@ -27,6 +28,40 @@ Five profiles, each designed to exercise a specific scenario:Re-running the command is a no-op when the named profile exists.Pass ``--reset`` to delete the matching profile (and its entities)before recreating.++Operator workflow for full-category coverage (sync result modal+manual validation):++ 1. Switch simulator to ``baseline``. Sync HI. Three entities+ whose names start with ``★ Custom Attr Needed ★`` will be+ imported alongside the others (one per integration). Open+ each in entity-edit and add ANY custom attribute (e.g., a+ "Note" attribute with any value). The custom attribute is+ what flips them onto the preserve-with-user-data path when+ they later disappear upstream.+ 2. Switch simulator to ``baseline-changed``. Refresh sync.+ The result modal shows:+ - Created: three new items present only in baseline-changed+ - Updated: three items renamed / metadata-changed+ - Removed: three items absent here, no user attribute+ - Detached: three ★-prefixed items absent here, with the+ user attribute the operator added in step 1 retained+ - (Reconnected is empty on this direction)+ 3. Switch simulator back to ``baseline``. Refresh sync.+ The result modal shows:+ - Reconnected: the three ★-prefixed items rejoin via the+ secondary-match path; their custom attributes are intact+ - Created: the three previously-Removed items return as+ fresh entities (no previous_integration_id, so no+ reconnect — they come back as duplicates would, but+ since the originals were hard-deleted there's no+ duplication, just re-creation)+ - Updated: the renames / changes swap back+ - Removed: the three baseline-changed-only items are+ dropped (no user attributes anchored, so hard-deleted)+ - (Detached is empty on this direction unless extra+ attributes were anchored on items unique to+ baseline-changed)"""from django.core.management.base import BaseCommandfrom django.db import transaction@@ -132,17 +167,26 @@ class Command(BaseCommand):return 0def _build_baseline(self, profile: SimProfile) -> int:- # HASS: one of each common device kind (5 entities).+ # HASS: one of each common device kind, plus a ★-prefixed+ # item that the operator anchors with a custom attribute+ # before flipping to baseline-changed (drives the+ # detach/reconnect cycle on the HASS side).self._add_hass_light_switch( profile, 'Garage Light' , '01.AA.01' )self._add_hass_dimmer( profile, 'Den Lamp' , '01.AA.02' )self._add_hass_motion( profile, 'Hallway Motion' , '01.AA.03' )self._add_hass_open_close( profile, 'Front Door' , '01.AA.04' )self._add_hass_outlet( profile, 'Kitchen Outlet' , '01.AA.05' )+ self._add_hass_light_switch(+ profile, '★ Custom Attr Needed ★ Office Light', '01.AA.10',+ )- # HomeBox: 4 items with mixed metadata richness. ``item_id``- # is the per-item stable id used by the integration's- # change-detection — kept identical across baseline /- # baseline-changed for items that should be 'the same item'.+ # HomeBox: 4 items with mixed metadata richness, plus a+ # ★-prefixed item that the operator anchors with a custom+ # attribute (HomeBox-side detach/reconnect anchor).+ # ``item_id`` is the per-item stable id used by the+ # integration's change-detection — kept identical across+ # baseline / baseline-changed for items that should be 'the+ # same item'.self._add_homebox_item(profile, 'Cordless Drill',item_id = 'cordless-drill',@@ -169,25 +213,45 @@ class Command(BaseCommand):item_id = 'spare-light-bulbs',quantity = 12,)+ self._add_homebox_item(+ profile, '★ Custom Attr Needed ★ Multimeter',+ item_id = 'multimeter',+ manufacturer = 'Fluke',+ model_number = '117',+ quantity = 1,+ )- # ZoneMinder: 1 server (singleton) + 2 monitors.+ # ZoneMinder: 1 server (singleton) + 2 monitors + a+ # ★-prefixed monitor anchor for the ZM detach/reconnect+ # cycle.self._add_zm_server( profile )self._add_zm_monitor( profile, 'Front Door Camera' , monitor_id = 1 )self._add_zm_monitor( profile, 'Driveway Camera' , monitor_id = 2 )+ self._add_zm_monitor(+ profile, '★ Custom Attr Needed ★ Backyard Camera',+ monitor_id = 5,+ )return profile.db_sim_entities.count()def _build_baseline_changed(self, profile: SimProfile) -> int:- # Designed so that importing `baseline` first, then switching- # the simulator to this profile and hitting Refresh, exercises- # remove + update + create in a single sync.+ # Designed as the partner of baseline so that flipping the+ # simulator between the two profiles and Refreshing+ # exercises every one of the five sync-result categories+ # (created / updated / reconnected / detached / removed)+ # in a single click. See the module docstring for the+ # operator workflow that drives the detach/reconnect path+ # via user-attribute anchoring.# HASS deltas vs baseline:# Garage Light — kept (no change)# Den Lamp — RENAMED to "Den Reading Lamp" (update)# Hallway Motion — kept- # Front Door — REMOVED (drop)+ # Front Door — REMOVED (no user attribute → hard delete)# Kitchen Outlet — kept+ # ★ Office Light — ABSENT here; with a user attribute+ # anchored on the HI side it takes+ # the preserve path → Detached# <new> Patio Switch — ADDED (create)self._add_hass_light_switch( profile, 'Garage Light' , '01.AA.01' )self._add_hass_dimmer( profile, 'Den Reading Lamp' , '01.AA.02' )@@ -195,13 +259,18 @@ class Command(BaseCommand):# Front Door (01.AA.04) intentionally absent.self._add_hass_outlet( profile, 'Kitchen Outlet' , '01.AA.05' )self._add_hass_light_switch( profile, 'Patio Switch' , '01.AA.06' )+ # Office Light (01.AA.10) intentionally absent — its HI-side+ # entity has the user-anchored custom attribute and takes+ # the detach path on the first sync after switching here.# HomeBox deltas:# Cordless Drill — kept (same item_id, same content)# Stud Finder — same item_id, manufacturer changed# (attribute update path)- # Soldering Iron — REMOVED (item_id absent)+ # Soldering Iron — REMOVED (item_id absent, no user attr)# Spare Bulbs — kept (same item_id, same content)+ # ★ Multimeter — ABSENT (item_id absent) → Detached on+ # the HI side via user-attribute anchor# <new> Caulk Gun — ADDED (new item_id)# Identity carries via ``item_id`` (the simulator's stable# API id), not row order — so the order here doesn't matter@@ -232,15 +301,24 @@ class Command(BaseCommand):description = '10-oz cartridge gun, dripless',quantity = 1,)+ # 'multimeter' (item_id) intentionally absent — Detached+ # via user-attribute anchor on the HI side.# ZoneMinder deltas:- # ZM Server — kept- # Front Door Camera — RENAMED to "Front Porch Camera"- # Driveway Camera — REMOVED- # <new> Backyard Cam — ADDED+ # ZM Server — kept+ # Front Door Camera — RENAMED to "Front Porch Camera"+ # Driveway Camera — REMOVED+ # ★ Backyard Camera — ABSENT (monitor_id 5 absent) →+ # Detached via user-attribute anchor+ # <new> Garage Camera — ADDED (monitor_id 3); deliberately+ # not named "Backyard Camera" to+ # avoid colliding with the+ # ★-prefixed Detached anchor when+ # flipping back.self._add_zm_server( profile )self._add_zm_monitor( profile, 'Front Porch Camera' , monitor_id = 1 )- self._add_zm_monitor( profile, 'Backyard Camera' , monitor_id = 3 )+ self._add_zm_monitor( profile, 'Garage Camera' , monitor_id = 3 )+ # monitor_id 5 (Backyard Camera) intentionally absent.return profile.db_sim_entities.count()diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex fbc091cf..eeec4eb1 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -2105,6 +2105,26 @@ g[hover] {height: auto;}+/* Smaller variant for inline contexts (entity detail badges,+ list-row item indicators) where 24px is too dominant. */+.hi-integration-logo--inline {+ max-height: 18px;+ max-width: 18px;+ width: auto;+ height: auto;+}++/* Detached variant: same dimensions as --inline, faded to signal+ the previously-attached state. Paired with the+ "Detached from <integration>" badge. */+.hi-integration-logo--detached {+ max-height: 18px;+ max-width: 18px;+ width: auto;+ height: auto;+ opacity: 0.6;+}+.hi-uppercase-label {letter-spacing: 0.05em;}