Home Information - Your home, your data, organized.
Python
Integration Capabilities framework (#355) (#359)
Tony C35c6f8532c9b
diff --git a/docs/dev/integrations/frigate.md b/docs/dev/integrations/frigate.mdindex ccf0bbe6..c0cc3d99 100644--- a/docs/dev/integrations/frigate.md+++ b/docs/dev/integrations/frigate.md@@ -28,7 +28,7 @@ User-facing setup lives in- `src/hi/services/frigate/frigate_client.py` — `FrigateClient`.Encapsulated HTTP client wrapping the Frigate REST API.- `src/hi/services/frigate/frigate_sync.py` —- `FrigateSynchronizer`. Drives Import / Refresh; per-camera entity+ `FrigateSynchronizer`. Drives sync; per-camera entitycreation in `_create_camera_entity`.- `src/hi/services/frigate/frigate_converter.py` —`FrigateConverter`. Wire-format ↔ HI model translation. Owns thediff --git a/docs/dev/integrations/home-assistant.md b/docs/dev/integrations/home-assistant.mdindex 77c9cb78..730f7e2c 100644--- a/docs/dev/integrations/home-assistant.md+++ b/docs/dev/integrations/home-assistant.md@@ -27,7 +27,7 @@ User-facing setup and troubleshooting live inintegration-specific complexity lives here. Aggregates multi-stateHA devices into a single HI item where it can.- `src/hi/services/hass/hass_sync.py` — `HassSynchronizer`. Drives- the Import / Refresh flow; delegates to the converter for the+ the sync flow; delegates to the converter for theper-item shape.- `src/hi/services/hass/monitors.py` — `HassMonitor`. Periodic pollagainst `/api/states`; produces `SensorResponse` events for statediff --git a/docs/dev/integrations/homebox.md b/docs/dev/integrations/homebox.mdindex 6c912e70..d49144db 100644--- a/docs/dev/integrations/homebox.md+++ b/docs/dev/integrations/homebox.md@@ -8,7 +8,7 @@ than HA or ZM: there are no per-item sensors or controllers and noreal-time state changes to track. Items imported from HomeBox areread-only by design — they exist for placement and reference. As aresult, `HomeBoxMonitor` does only a periodic reachability probe;-all entity churn happens via user-initiated Import / Refresh.+all entity churn happens via user-initiated sync.User-facing setup and troubleshooting live in[`docs/integrations/homebox.md`](../../integrations/homebox.md).@@ -26,7 +26,7 @@ User-facing setup and troubleshooting live inHomeBox items into HI items, including custom field expansion asread-only attributes.- `src/hi/services/homebox/hb_sync.py` — `HomeBoxSynchronizer`.- Drives Import / Refresh.+ Drives sync.- `src/hi/services/homebox/monitors.py` — `HomeBoxMonitor`. Periodicreachability probe only; no state polling.- `src/hi/services/homebox/hb_controller.py` — `HomeBoxController`.@@ -54,11 +54,11 @@ error message in `HbClient` when responses are not JSON.in HI; their HomeBox-sourced fields appear as read-only attributes.The integration metadata sets `can_add_custom_attributes = False`on the metadata to prevent users from adding HI-side attributes- that would not survive a Refresh; see `hb_metadata.py`.+ that would not survive a sync; see `hb_metadata.py`.- **Attachment downloads.** Files attached to a HomeBox item(manuals, receipts, photos) are downloaded into HI's media storage- at Import / Refresh time. Updates to the file in HomeBox propagate- only on the next Refresh.+ at sync time. Updates to the file in HomeBox propagate only on+ the next sync.## Testing approachdiff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.mdindex d45fe933..98338d37 100644--- a/docs/dev/integrations/integration-guidelines.md+++ b/docs/dev/integrations/integration-guidelines.md@@ -9,6 +9,13 @@ Each integration is a Django app in `hi/services/` directory. The `hi.integratio- **integration_key**: Associates entities/sensors with external systems- **detail_attrs**: Opaque data blob - only the integration uses this data+### Capability model+Each integration declares its `IntegrationCapability` set on `IntegrationMetaData.capabilities` (`hi/integrations/enums.py`). Today only `CONNECT` is used — live mirror of an upstream system. `IMPORT` (one-shot copy of upstream items into HI) is reserved; its abstract protocol and workflow land with the first concrete consumer (issue #358).++Per-attribute `IntegrationAttributeType` declarations may carry an optional `capabilities` set to restrict which capability's UI surfaces the attribute. Default is `ALL_CAPABILITIES`; existing declarations remain unaffected.++`Entity.data_source` (an `EntityDataSource` value: `INTERNAL` or `EXTERNAL`, see `hi/apps/entity/enums.py`) records per-entity provenance. Today only HomeBox-Connect entities are `EXTERNAL` (HomeBox refuses HI-side edits); native and HA/ZM/Frigate entities are `INTERNAL`. The field is the hook for the cross-capability transition flows that arrive with `IMPORT`.+### One-to-many state compositionA single upstream state may decompose into multiple HI EntityStates when the upstream protocol packs several independently-controllable values into one entity (e.g., a color light's brightness + hue + saturation + color temperature). The framework supports this via:@@ -135,7 +142,7 @@ the user-facing landing page at [`docs/Integrations.md`](../../Integrations.md).## Gateway Implementation Patterns### Gateway Methods-**activate()**: Validate config, test connection, initialize resources+**activate()**: Validate config, validate access, initialize resources**deactivate()**: Clean up entities, close connections, update status**manage()**: Handle POST actions (sync, test, config), render management UIdiff --git a/docs/dev/integrations/zoneminder.md b/docs/dev/integrations/zoneminder.mdindex d4b3cc94..223521a5 100644--- a/docs/dev/integrations/zoneminder.md+++ b/docs/dev/integrations/zoneminder.md@@ -30,9 +30,9 @@ User-facing setup, CORS, and SSL troubleshooting live in- `src/hi/services/zoneminder/pyzm_client/` — vendored Python clientfor ZM's REST API and `cgi-bin/nph-zms` streaming endpoints.- `src/hi/services/zoneminder/zm_sync.py` — `ZoneMinderSynchronizer`.- Drives Import / Refresh; per-monitor entity creation in+ Drives sync; per-monitor entity creation in`_create_monitor_entity` (this is also the entry point used by the- auto-reconnect path on Refresh).+ auto-reconnect path on sync).- `src/hi/services/zoneminder/monitors.py` — `ZoneMinderMonitor`.Periodic poll for monitor state, function changes, and events;emits `SensorResponse` updates for movement sensor state changes.diff --git a/docs/dev/testing/test-simulator.md b/docs/dev/testing/test-simulator.mdindex 3288bd96..b04e6299 100644--- a/docs/dev/testing/test-simulator.md+++ b/docs/dev/testing/test-simulator.md@@ -29,7 +29,7 @@ integrations talk to. It mounts service-shaped HTTP endpoints under`http://127.0.0.1:7411/services/<service>/...` that respond with thesame shapes the real services would, sourced from a curated**SimProfile**. Switching profiles changes what the integrations see-on their next Import or Refresh, which is the lever for exercising+on their next sync, which is the lever for exercisingsync behavior end-to-end.The simulator is a separate Django app with its own database (see the@@ -114,7 +114,7 @@ table below is a short orientation.The `baseline ↔ baseline-changed` pair is the canonical workflow forexercising every sync-result category. The command's docstringspells out the exact step-by-step (which entities to add custom-attributes to, what each Refresh shows in the result modal); read+attributes to, what each sync shows in the result modal); readit directly when running the workflow rather than trying to keep acopy of the steps here in sync.diff --git a/docs/integrations/_template.md b/docs/integrations/_template.mdindex e12634c6..abf756c9 100644--- a/docs/integrations/_template.md+++ b/docs/integrations/_template.md@@ -65,17 +65,17 @@ get wrong (scheme, port, path suffix, trailing slash).## Setup walkthroughWhat the user does in HI to enable the integration once they have-their credentials, and what to expect on the first **Import**. Keep+their credentials, and what to expect on the first **Connect**. Keepthis brief — it is mostly continuity from the previous section into-the post-import state.+the post-connect state.The standard first step is opening HI's integration picker — linkback to [Enabling an integration](../Integrations.md#enabling-an-integration)for the conditional UI flow rather than restating it here, so a UIchange only needs to be reflected in one place.-Use the user-facing terms: **Import** for the first run and-**Refresh** for subsequent runs (matching the modal labels). Avoid+Use the user-facing terms: **Connect** for the first run and+**Update** for subsequent runs (matching the button labels). Avoid"sync" in user-facing copy.## Troubleshootingdiff --git a/docs/integrations/frigate.md b/docs/integrations/frigate.mdindex 20bf4151..4e885b78 100644--- a/docs/integrations/frigate.md+++ b/docs/integrations/frigate.md@@ -50,13 +50,12 @@ page.[Enabling an integration](../Integrations.md#enabling-an-integration))and choose **Frigate**.2. Fill in the fields above and save.-3. **HI** walks you through a series of modals to confirm the- **Import** action, pull each Frigate camera as an **HI** camera- item, and place the imported cameras into a location view or+3. Click **CONNECT** to pull each Frigate camera as an **HI** camera+ item and place the imported cameras into a location view orcollection.To pick up upstream changes later (new cameras, renames, removals),-click **Refresh** on the integration's manage page.+click **UPDATE** on the integration's manage page.## Troubleshooting@@ -100,7 +99,7 @@ The **Base URL** is wrong, or Frigate is not reachable from the **HI**host. Verify by opening the URL in a browser from the **HI** hostand confirming Frigate's web UI loads.-### Refresh imports zero cameras+### Update finds zero camerasFrigate's `/api/config` returned an empty `cameras` map. Confirmyour `config.yml` defines at least one camera and that Frigate isdiff --git a/docs/integrations/home-assistant.md b/docs/integrations/home-assistant.mdindex 9756b779..a2ef26c7 100644--- a/docs/integrations/home-assistant.md+++ b/docs/integrations/home-assistant.md@@ -56,14 +56,13 @@ See HA's official guide for screenshots and updates if the UI changes:[Enabling an integration](../Integrations.md#enabling-an-integration))and choose **Home Assistant**.2. Fill in the four fields above and save.-3. HI walks you through a series of modals to confirm the **Import**- action, pull HA entities that match the allowlist, and place the- imported items into a location view or collection. Capability- detection uses heuristics over HA's domain and device class- metadata.+3. Click **CONNECT** to pull HA entities matching the allowlist and+ place the imported items into a location view or collection.+ Capability detection uses heuristics over HA's domain and device+ class metadata.To pick up changes from HA later (new entities, renames, removals),-click **REFRESH** on the integration's manage page.+click **UPDATE** on the integration's manage page.## Troubleshootingdiff --git a/docs/integrations/homebox.md b/docs/integrations/homebox.mdindex f5fe299c..b0042268 100644--- a/docs/integrations/homebox.md+++ b/docs/integrations/homebox.md@@ -41,14 +41,13 @@ HomeBox web interface — there is no separate API token to obtain.[Enabling an integration](../Integrations.md#enabling-an-integration))and choose **HomeBox**.2. Fill in the three fields above and save.-3. HI walks you through a series of modals to confirm the **Import**- action, pull each HomeBox item as an HI item, and place the- imported items into a location view or collection. Custom fields- become read-only attributes; attached files are downloaded to- HI's media storage.+3. Click **CONNECT** to pull each HomeBox item as an HI item and+ place the imported items into a location view or collection.+ Custom fields become read-only attributes; attached files are+ downloaded to HI's media storage.To pick up changes from HomeBox later (new items, renames,-removals), click **REFRESH** on the integration's manage page.+removals), click **UPDATE** on the integration's manage page.## Troubleshooting@@ -78,8 +77,8 @@ the same credentials.controllers, or alarm events for HomeBox items — they existprimarily for placement and reference.- Custom attributes added in HI on a HomeBox-imported item are- preserved across Refresh, but HomeBox-sourced fields cannot be- edited from within HI; edit them in HomeBox and Refresh.-- Attached files are downloaded at import / Refresh time. Updates to- a file in HomeBox (replacing a manual PDF, for instance) require a- Refresh to propagate.+ preserved across updates, but HomeBox-sourced fields cannot be+ edited from within HI; edit them in HomeBox and click **UPDATE**.+- Attached files are downloaded at Connect and on each Update.+ Replacing a file in HomeBox (a manual PDF, for instance) requires+ an Update to propagate.diff --git a/docs/integrations/zoneminder.md b/docs/integrations/zoneminder.mdindex 06a2f7b9..142a0c6d 100644--- a/docs/integrations/zoneminder.md+++ b/docs/integrations/zoneminder.md@@ -48,12 +48,12 @@ separate API token mechanism in ZoneMinder.[Enabling an integration](../Integrations.md#enabling-an-integration))and choose **ZoneMinder**.2. Fill in the six fields above and save.-3. HI walks you through a series of modals to confirm the **Import**- action, pull each ZM monitor as an HI camera item, and place the- imported cameras into a location view or collection.+3. Click **CONNECT** to pull each ZM monitor as an HI camera item+ and place the imported cameras into a location view or+ collection.To pick up changes from ZoneMinder later (new monitors, renames,-removals), click **REFRESH** on the integration's manage page.+removals), click **UPDATE** on the integration's manage page.## Troubleshooting@@ -103,7 +103,7 @@ the ZM portal directly with the same credentials, then check- HI does not run any image analysis or motion detection — all motionevents originate from ZM. Configure detection sensitivity andzones in ZM itself.-- ZM monitor renames in the upstream are propagated on Refresh; ZM+- ZM monitor renames in the upstream are propagated on Update; ZMmonitor deletes remove the corresponding HI camera unless the userhas added custom data to it (in which case it is preserved asdetached, with a "Detached from ZoneMinder" indicator).diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex d12f914a..1a915beb 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -198,6 +198,12 @@ class EntityType(LabeledEnum):return f'entity/modals/entity_status_{self.name.lower()}.html'+class EntityDataSource(LabeledEnum):++ INTERNAL = ('Internal', 'HI owns the editable representation.')+ EXTERNAL = ('External', 'Upstream constrains HI-side edits.')++class EntityStateValue(LabeledEnum):# Alarm-style values (e.g., ACTIVE, OPEN, SMOKE_DETECTED) are# rendered as the ``status`` attribute on both the SVG icondiff --git a/src/hi/apps/entity/migrations/0021_entity_data_source.py b/src/hi/apps/entity/migrations/0021_entity_data_source.pynew file mode 100644index 00000000..861d55a0--- /dev/null+++ b/src/hi/apps/entity/migrations/0021_entity_data_source.py@@ -0,0 +1,48 @@+import logging++from django.db import migrations, models+++def backfill_data_source(apps, schema_editor):+ """Mark integration-attached entities that disallow internal+ attributes as EXTERNAL. All others keep the column default+ (INTERNAL). Today this affects only HomeBox-Connect entities."""+ logger = logging.getLogger('hi.apps.entity.migrations.0021')++ Entity = apps.get_model('entity', 'Entity')++ updated = Entity.objects.filter(+ integration_id__isnull=False,+ allow_internal_attributes=False,+ ).exclude(+ integration_id='',+ ).update(+ data_source_str='external',+ )++ logger.info(+ f'EntityDataSource backfill: marked {updated} entity row(s) EXTERNAL.'+ )+++class Migration(migrations.Migration):++ dependencies = [+ ('entity', '0020_entity_allow_internal_attributes'),+ ]++ operations = [+ migrations.AddField(+ model_name='entity',+ name='data_source_str',+ field=models.CharField(+ default='internal',+ max_length=16,+ verbose_name='Data Source',+ ),+ ),+ migrations.RunPython(+ code=backfill_data_source,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex 3bef5982..9ec1cfc8 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -16,6 +16,7 @@ from hi.integrations.models import IntegrationDetailsModelfrom hi.enums import ItemTypefrom .enums import (+ EntityDataSource,EntityType,EntityStateRole,EntityStateType,@@ -57,6 +58,12 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):'Allow Internal Attributes?',default = True,)+ data_source_str = models.CharField(+ 'Data Source',+ max_length = 16,+ null = False, blank = False,+ default = str(EntityDataSource.INTERNAL),+ )has_video_stream = models.BooleanField('Has Video Stream',default = False,@@ -127,6 +134,15 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):self.entity_type_str = str(entity_type)return+ @property+ def data_source(self) -> EntityDataSource:+ return EntityDataSource.from_name_safe( self.data_source_str )++ @data_source.setter+ def data_source( self, data_source : EntityDataSource ):+ self.data_source_str = str(data_source)+ return+@propertydef has_native_video_stream(self) -> bool:"""Explicit-name alias for ``has_video_stream`` for the rarediff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.pyindex c3eb2059..da52da6e 100644--- a/src/hi/apps/entity/tests/test_models.py+++ b/src/hi/apps/entity/tests/test_models.py@@ -1,9 +1,12 @@+import importlibimport jsonimport logging++from django.apps import apps as django_appsfrom django.db import IntegrityErrorfrom hi.apps.entity.models import Entity, EntityAttribute, EntityState-from hi.apps.entity.enums import EntityStateRole, EntityType, EntityStateType+from hi.apps.entity.enums import EntityDataSource, EntityStateRole, EntityType, EntityStateTypefrom hi.apps.attribute.enums import AttributeValueTypefrom hi.testing.base_test_case import BaseTestCase@@ -76,16 +79,79 @@ class TestEntity(BaseTestCase):integration_id='test_device_001',integration_name='test_integration',)-+# Test getter converts string to enumself.assertEqual(entity.entity_type, EntityType.LIGHT)-+# Test setter converts enum to string (lowercase)entity.entity_type = EntityType.CAMERAself.assertEqual(entity.entity_type_str, str(EntityType.CAMERA).lower())self.assertEqual(entity.entity_type, EntityType.CAMERA)return+ def test_data_source_defaults_to_internal(self):+ entity = Entity.objects.create(+ name='Default Source Entity',+ entity_type_str=str(EntityType.OTHER),+ integration_id='ds_default_001',+ integration_name='test_integration',+ )+ self.assertEqual(entity.data_source, EntityDataSource.INTERNAL)+ self.assertEqual(entity.data_source_str, str(EntityDataSource.INTERNAL))+ return++ def test_data_source_property_conversion(self):+ entity = Entity.objects.create(+ name='Source Entity',+ entity_type_str=str(EntityType.OTHER),+ integration_id='ds_conv_001',+ integration_name='test_integration',+ )+ entity.data_source = EntityDataSource.EXTERNAL+ self.assertEqual(entity.data_source_str, str(EntityDataSource.EXTERNAL))+ self.assertEqual(entity.data_source, EntityDataSource.EXTERNAL)+ entity.data_source = EntityDataSource.INTERNAL+ self.assertEqual(entity.data_source, EntityDataSource.INTERNAL)+ return++ def test_migration_0021_backfill_marks_external_only_when_integration_disallows_internal_attrs(self):+ # Migration 0021's backfill rule: integration-attached entities+ # whose integration disallows internal attributes get marked+ # EXTERNAL. Everything else stays at the column default (INTERNAL).+ # Today this picks out HomeBox-Connect entities and leaves+ # native + HA/ZM/Frigate alone.+ native = Entity.objects.create(+ name='Native',+ entity_type_str=str(EntityType.OTHER),+ )+ hass_like = Entity.objects.create(+ name='HASS-like',+ entity_type_str=str(EntityType.OTHER),+ integration_id='hass',+ integration_name='hass_thing',+ allow_internal_attributes=True,+ )+ hb_like = Entity.objects.create(+ name='HB-like',+ entity_type_str=str(EntityType.OTHER),+ integration_id='hb',+ integration_name='hb_item_1',+ allow_internal_attributes=False,+ )++ mig = importlib.import_module(+ 'hi.apps.entity.migrations.0021_entity_data_source',+ )+ mig.backfill_data_source(django_apps, schema_editor=None)++ native.refresh_from_db()+ hass_like.refresh_from_db()+ hb_like.refresh_from_db()+ self.assertEqual(native.data_source, EntityDataSource.INTERNAL)+ self.assertEqual(hass_like.data_source, EntityDataSource.INTERNAL)+ self.assertEqual(hb_like.data_source, EntityDataSource.EXTERNAL)+ return+def test_entity_type_property_handles_unknown_types_gracefully(self):"""Test entity_type property with unknown type - should provide fallback behavior."""entity = Entity.objects.create(diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex e3ecbd2e..8bb1c285 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -433,7 +433,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):)def _make_structured_view_data(self):- from hi.integrations.external_view_data import (+ from hi.integrations.connect.external_view_data import (NameValuePair, AttachmentRef, StructuredViewData,)return StructuredViewData(@@ -454,7 +454,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):)def _make_minimal_view_data(self):- from hi.integrations.external_view_data import MinimalViewData+ from hi.integrations.connect.external_view_data import MinimalViewDatareturn MinimalViewData(deep_link_url='https://upstream.example/items/99')def test_native_entity_omits_section_and_skips_lookup(self):@@ -549,7 +549,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):"""``MinimalViewData.error_message`` renders in the modal sothe operator sees the failure reason inline rather than onlyin server logs."""- from hi.integrations.external_view_data import MinimalViewData+ from hi.integrations.connect.external_view_data import MinimalViewDataurl = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})@@ -659,7 +659,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):verify the include call site honors the instance attribute bypointing at a template that emits a distinctive marker, thenasserting the marker appears in the rendered output."""- from hi.integrations.external_view_data import CustomTemplateViewData+ from hi.integrations.connect.external_view_data import CustomTemplateViewDatacustom = CustomTemplateViewData(template_name='integrations/external_data/entity/minimal.html',diff --git a/src/hi/integrations/connect/__init__.py b/src/hi/integrations/connect/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/connect/entity_operations.pysimilarity index 99%rename from src/hi/integrations/entity_operations.pyrename to src/hi/integrations/connect/entity_operations.pyindex 9b0a6030..57cebf6b 100644--- a/src/hi/integrations/entity_operations.py+++ b/src/hi/integrations/connect/entity_operations.py@@ -24,9 +24,10 @@ from hi.apps.entity.models import Entity, EntityState, EntityStateDelegationfrom hi.apps.sense.models import Sensorfrom hi.apps.control.models import Controller-from .event_definition_operations import EventDefinitionOperations+from hi.integrations.event_definition_operations import EventDefinitionOperations+from hi.integrations.transient_models import IntegrationKey, IntegrationRemovalSummary+from .sync_result import IntegrationSyncResult-from .transient_models import IntegrationKey, IntegrationRemovalSummaryfrom .user_data_detector import EntityUserDataDetectorlogger = logging.getLogger(__name__)diff --git a/src/hi/integrations/external_view_data.py b/src/hi/integrations/connect/external_view_data.pysimilarity index 100%rename from src/hi/integrations/external_view_data.pyrename to src/hi/integrations/connect/external_view_data.pydiff --git a/src/hi/integrations/integration_attribute_edit_context.py b/src/hi/integrations/connect/integration_attribute_edit_context.pysimilarity index 76%rename from src/hi/integrations/integration_attribute_edit_context.pyrename to src/hi/integrations/connect/integration_attribute_edit_context.pyindex 72d088be..e52fa6a0 100644--- a/src/hi/integrations/integration_attribute_edit_context.py+++ b/src/hi/integrations/connect/integration_attribute_edit_context.py@@ -14,9 +14,12 @@ from hi.apps.attribute.forms import AttributeUploadFormfrom hi.apps.attribute.models import AttributeModelfrom hi.apps.system.health_status import HealthStatus-from .forms import IntegrationAttributeRegularFormSet+from hi.integrations.enums import IntegrationCapability+from hi.integrations.forms import IntegrationAttributeRegularFormSet+from hi.integrations.models import Integration, IntegrationAttribute+from hi.integrations.transient_models import IntegrationKey+from .integration_data import IntegrationData-from .models import Integration, IntegrationAttributeclass IntegrationAttributeItemEditContext(AttributeItemEditContext):@@ -29,30 +32,19 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):def __init__( self,integration_data : IntegrationData,+ capability : IntegrationCapability,health_status : HealthStatus = None,update_button_label : str = 'UPDATE',suppress_history : bool = False,show_secrets : bool = False,- is_review_mode : bool = False,- pre_sync_url : Optional[str] = None,) -> None:- """- Initialize context for Integration attribute editing.-- Review-mode flags (`is_review_mode` + `pre_sync_url`) drive the- Review Config back-from-pre-sync flow: when set, the modal's- cancel slot becomes a CONTINUE action that returns to the- pre-sync modal instead of dismissing. First-time Configure- leaves them unset and keeps the CANCEL/dismiss behavior.- """super().__init__( owner_type = 'integration', owner = integration_data.integration )self.integration_data = integration_data+ self._capability = capabilityself._health_status = health_statusself._update_button_label = update_button_labelself._suppress_history = suppress_historyself._show_secrets = show_secrets- self._is_review_mode = is_review_mode- self._pre_sync_url = pre_sync_urlreturn@@ -89,15 +81,30 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):return IntegrationAttributeRegularFormSet(form_data,instance = self.integration,+ queryset = self._capability_filtered_attribute_queryset(),prefix = self.formset_prefix,form_kwargs={'show_as_editable': True,- 'allow_reordering': False, # Disable reordering for system-defined attributes- 'suppress_history': self._suppress_history, # While enabling, no history- 'show_secrets': self._show_secrets, # While enable, plain password view+ 'allow_reordering': False,+ 'suppress_history': self._suppress_history,+ 'show_secrets': self._show_secrets,})+ def _capability_filtered_attribute_queryset(self):+ AttributeType = self.integration_data.integration_metadata.attribute_type+ key_strs = [+ IntegrationKey(+ integration_id = self.integration.integration_id,+ integration_name = str( member ),+ ).integration_key_str+ for member in AttributeType+ if self._capability in member.capabilities+ ]+ return self.integration.attributes.filter(+ integration_key_str__in = key_strs,+ )+@propertydef attribute_upload_form_class(self) -> Type[AttributeUploadForm]:# No file uploads for Integration attributes (as of yet)@@ -113,7 +120,5 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):template_context.update({'integration_data': self.integration_data,'health_status': self._health_status,- 'is_review_mode': self._is_review_mode,- 'pre_sync_url': self._pre_sync_url,})return template_contextdiff --git a/src/hi/integrations/integration_controller.py b/src/hi/integrations/connect/integration_controller.pysimilarity index 68%rename from src/hi/integrations/integration_controller.pyrename to src/hi/integrations/connect/integration_controller.pyindex 6a4b1bf4..a4e380fa 100644--- a/src/hi/integrations/integration_controller.py+++ b/src/hi/integrations/connect/integration_controller.py@@ -1,5 +1,5 @@-from .transient_models import IntegrationDetails-from .transient_models import IntegrationControlResult+from hi.integrations.transient_models import IntegrationDetails+from hi.integrations.transient_models import IntegrationControlResultclass IntegrationController:diff --git a/src/hi/integrations/integration_data.py b/src/hi/integrations/connect/integration_data.pysimilarity index 88%rename from src/hi/integrations/integration_data.pyrename to src/hi/integrations/connect/integration_data.pyindex 15430bc6..d76bd8b2 100644--- a/src/hi/integrations/integration_data.py+++ b/src/hi/integrations/connect/integration_data.py@@ -1,8 +1,9 @@from dataclasses import dataclass+from hi.integrations.models import Integration+from hi.integrations.transient_models import IntegrationMetaData+from .integration_gateway import IntegrationGateway-from .models import Integration-from .transient_models import IntegrationMetaData@dataclassdiff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/connect/integration_gateway.pysimilarity index 91%rename from src/hi/integrations/integration_gateway.pyrename to src/hi/integrations/connect/integration_gateway.pyindex 63061790..5459e1fa 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/connect/integration_gateway.py@@ -10,8 +10,8 @@ from .external_view_data import ExternalViewDatafrom .integration_controller import IntegrationControllerfrom .integration_manage_view_pane import IntegrationManageViewPanefrom .integration_synchronizer import IntegrationSynchronizer-from .models import IntegrationAttribute-from .transient_models import (+from hi.integrations.models import IntegrationAttribute+from hi.integrations.transient_models import (ConnectionTestResult,IntegrationMetaData,IntegrationValidationResult,@@ -70,20 +70,20 @@ class IntegrationGateway:Schema-only validation of the proposed configuration. Must NOTperform network operations. Returns success if the attribute setis structurally usable; returns an error otherwise. For live- connection probing, see test_connection().+ access validation, see validate_access()."""raise NotImplementedError('Subclasses must override this method')- def test_connection(+ def validate_access(self,integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float],) -> ConnectionTestResult:"""- Live connection probe against the proposed configuration. Must- respect the bounded timeout. Used at attribute-save time- (Configure / Reconfigure) and before relaunching monitors- (Resume).+ Live probe to validate access to the upstream system using the+ proposed configuration. Must respect the bounded timeout. Used+ at attribute-save time (Configure / Reconfigure) and before+ relaunching monitors (Resume)."""raise NotImplementedError('Subclasses must override this method')diff --git a/src/hi/integrations/integration_manage_view_pane.py b/src/hi/integrations/connect/integration_manage_view_pane.pysimilarity index 100%rename from src/hi/integrations/integration_manage_view_pane.pyrename to src/hi/integrations/connect/integration_manage_view_pane.pydiff --git a/src/hi/integrations/integration_synchronizer.py b/src/hi/integrations/connect/integration_synchronizer.pysimilarity index 93%rename from src/hi/integrations/integration_synchronizer.pyrename to src/hi/integrations/connect/integration_synchronizer.pyindex afdb9c3c..de0d0558 100644--- a/src/hi/integrations/integration_synchronizer.py+++ b/src/hi/integrations/connect/integration_synchronizer.py@@ -27,7 +27,7 @@ from hi.apps.entity.models import Entityfrom .entity_operations import EntityIntegrationOperationsfrom .sync_check import IntegrationSyncCheck, SyncDeltafrom .sync_result import IntegrationSyncResult-from .transient_models import IntegrationKey, IntegrationMetaData+from hi.integrations.transient_models import IntegrationKey, IntegrationMetaDatalogger = logging.getLogger(__name__)@@ -54,13 +54,13 @@ class IntegrationSynchronizer:# docstring above for the rationale.SYNCHRONIZATION_LOCK_NAME = 'integrations_sync'- def get_description(self, is_initial_import: bool) -> Optional[str]:+ def get_description(self, is_initial_connect: bool) -> Optional[str]:"""Optional copy describing what this integration's sync will do,surfaced to the operator in the framework's pre-syncconfirmation modal alongside a generic lead message.- `is_initial_import` distinguishes the first-time IMPORT (no+ `is_initial_connect` distinguishes the first-time IMPORT (noentities have been imported yet) from subsequent REFRESHoperations. The two contexts mean different things to theoperator and integrations are encouraged to provide tailored@@ -69,21 +69,22 @@ class IntegrationSynchronizer:"""return None- def get_result_title(self, is_initial_import: bool) -> str:+ def get_result_title(self, is_initial_connect: bool) -> str:"""- Short, generic header for the sync result modal: 'Import- Result' for the first-time path, 'Refresh Result' otherwise.- The integration's identity is surfaced in the modal body- (logo + label) rather than the title bar — keeps the title- bar contrast predictable regardless of integration. Override- only if a specific integration genuinely needs custom copy.+ Short, generic header for the sync result modal: 'Connect+ Result' for the first-time path, 'Update Check Result'+ otherwise. The integration's identity is surfaced in the+ modal body (logo + label) rather than the title bar — keeps+ the title bar contrast predictable regardless of integration.+ Override only if a specific integration genuinely needs custom+ copy."""- if is_initial_import:- return 'Import Result'- return 'Refresh Result'+ if is_initial_connect:+ return 'Connect Result'+ return 'Update Check Result'def sync(self,- is_initial_import : bool,+ is_initial_connect : bool,preserve_user_data : bool = True,) -> IntegrationSyncResult:"""@@ -91,7 +92,7 @@ class IntegrationSynchronizer:with the sync lock and standard error handling. Subclassesoverride `_sync_impl` rather than this method.- ``is_initial_import`` is the operator-intent flag from the+ ``is_initial_connect`` is the operator-intent flag from thesync flow (Import for first-time, Refresh otherwise);threaded down so each subclass can title its resultconsistently.@@ -111,11 +112,11 @@ class IntegrationSynchronizer:try:with ExclusionLockContext(name=self.SYNCHRONIZATION_LOCK_NAME):logger.debug(f'{self.__class__.__name__} sync started.')- result = self._sync_impl(is_initial_import=is_initial_import)+ result = self._sync_impl(is_initial_connect=is_initial_connect)except RuntimeError as e:logger.exception(e)result = IntegrationSyncResult(- title=self.get_result_title(is_initial_import=is_initial_import),+ title=self.get_result_title(is_initial_connect=is_initial_connect),error_list=[str(e)],)finally:@@ -169,7 +170,7 @@ class IntegrationSynchronizer:committed enough changes to invalidate process-level state."""return- def _sync_impl(self, is_initial_import: bool) -> IntegrationSyncResult:+ def _sync_impl(self, is_initial_connect: bool) -> IntegrationSyncResult:"""Integration-specific sync work. Subclasses must override.Called with the synchronization lock held.diff --git a/src/hi/integrations/monitors.py b/src/hi/integrations/connect/monitors.pysimilarity index 98%rename from src/hi/integrations/monitors.pyrename to src/hi/integrations/connect/monitors.pyindex 666c0737..4bfeeb30 100644--- a/src/hi/integrations/monitors.py+++ b/src/hi/integrations/connect/monitors.py@@ -70,7 +70,7 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):async def do_work(self):# Imported here to avoid an import cycle: IntegrationManager# imports this module to start the monitor on init.- from .integration_manager import IntegrationManager+ from hi.integrations.integration_manager import IntegrationManagermanager = IntegrationManager()integration_data_list = manager.get_integration_data_list( enabled_only = True )diff --git a/src/hi/integrations/placement_request.py b/src/hi/integrations/connect/placement_request.pysimilarity index 94%rename from src/hi/integrations/placement_request.pyrename to src/hi/integrations/connect/placement_request.pyindex fdcbd8de..b78c70cf 100644--- a/src/hi/integrations/placement_request.py+++ b/src/hi/integrations/connect/placement_request.py@@ -6,7 +6,7 @@ The placement modal carries two related concerns that this moduleowns:* ``PlacementUrlParams`` — the URL/form-param contract- (``is_initial_import``, ``entity_ids``). Single source of truth+ (``is_initial_connect``, ``entity_ids``). Single source of truthfor key names and value encodings; build URLs and parse requestsvia this class rather than handling raw strings.@@ -62,29 +62,29 @@ class PlacementUrlParams:this class rather than handling raw strings. Renaming a keyor changing an encoding happens in exactly one place.- Scope: the URL query params (``?is_initial_import=…&entity_ids=…``)+ Scope: the URL query params (``?is_initial_connect=…&entity_ids=…``)and the matching hidden form fields the placement modal POSTsback. Does *not* cover the per-entity / per-group form fieldsconsumed by ``PlacementFormParser`` — those have their owncontract owned by that parser."""- KEY_IS_INITIAL_IMPORT = 'is_initial_import'+ KEY_IS_INITIAL_CONNECT = 'is_initial_connect'KEY_ENTITY_IDS = 'entity_ids'ENTITY_IDS_SEP = ','TRUE_VALUE = '1'FALSE_VALUE = '0'- is_initial_import : bool = False+ is_initial_connect : bool = Falseentity_ids : List[int] = field(default_factory=list)def to_query_dict(self) -> Dict[str, str]:"""Sparse query dict — keys are omitted when their valueis the default, keeping URLs free of redundant- ``?is_initial_import=0`` cruft."""+ ``?is_initial_connect=0`` cruft."""result : Dict[str, str] = {}- if self.is_initial_import:- result[self.KEY_IS_INITIAL_IMPORT] = self.TRUE_VALUE+ if self.is_initial_connect:+ result[self.KEY_IS_INITIAL_CONNECT] = self.TRUE_VALUEif self.entity_ids:result[self.KEY_ENTITY_IDS] = self.ENTITY_IDS_SEP.join(str(i) for i in self.entity_ids@@ -97,11 +97,11 @@ class PlacementUrlParams:qd = self.to_query_dict()return f'{base_url}?{urlencode(qd)}' if qd else base_url- def is_initial_import_form_value(self) -> str:- """The hidden-form-field encoding of ``is_initial_import``+ def is_initial_connect_form_value(self) -> str:+ """The hidden-form-field encoding of ``is_initial_connect``for templates that need to round-trip the flag through aPOST."""- return self.TRUE_VALUE if self.is_initial_import else self.FALSE_VALUE+ return self.TRUE_VALUE if self.is_initial_connect else self.FALSE_VALUE@classmethoddef from_data(cls, data) -> 'PlacementUrlParams':@@ -109,7 +109,7 @@ class PlacementUrlParams:QueryDict-like). Malformed ``entity_ids`` raises BadRequestso a tampered request fails loudly rather than silentlywidening scope."""- is_initial = str_to_bool( data.get( cls.KEY_IS_INITIAL_IMPORT, '' ) )+ is_initial = str_to_bool( data.get( cls.KEY_IS_INITIAL_CONNECT, '' ) )raw = ( data.get( cls.KEY_ENTITY_IDS, '' ) or '' ).strip()entity_ids : List[int] = []if raw:@@ -121,7 +121,7 @@ class PlacementUrlParams:]except ValueError:raise BadRequest( f'Invalid {cls.KEY_ENTITY_IDS} parameter.' )- return cls( is_initial_import = is_initial, entity_ids = entity_ids )+ return cls( is_initial_connect = is_initial, entity_ids = entity_ids )class PlacementFormParser:diff --git a/src/hi/integrations/sync_check.py b/src/hi/integrations/connect/sync_check.pysimilarity index 91%rename from src/hi/integrations/sync_check.pyrename to src/hi/integrations/connect/sync_check.pyindex b3ac3064..68d31194 100644--- a/src/hi/integrations/sync_check.py+++ b/src/hi/integrations/connect/sync_check.py@@ -32,7 +32,7 @@ from django.core.cache import cacheimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.enums import LabeledEnum-from .transient_models import IntegrationKey+from hi.integrations.transient_models import IntegrationKeylogger = logging.getLogger(__name__)@@ -141,10 +141,31 @@ class IntegrationSyncCheck:@classmethoddef get_state( cls, integration_id : str ) -> Optional[ SyncCheckResult ]:"""Return the most recent cached result, or None if no probe- has written one (or the entry has expired)."""+ has written one (or the entry has expired).++ Tolerates unreadable cache entries. The cached value is a+ pickled dataclass, which means a class rename, module move,+ or shape change can make existing entries fail to deserialize+ in-place. Without a guard, every read of a stale entry would+ propagate the unpickle exception out through the manage page.+ Catch broadly, evict the bad key so the next request runs+ clean, and degrade to a cache miss — the next probe cycle (or+ a successful Refresh) writes fresh state."""if not integration_id:return None- return cache.get( cls._cache_key( integration_id ) )+ cache_key = cls._cache_key( integration_id )+ try:+ return cache.get( cache_key )+ except Exception as e:+ logger.warning(+ f'sync-check cache entry unreadable for {integration_id}: '+ f'{e}; evicting and treating as miss'+ )+ try:+ cache.delete( cache_key )+ except Exception:+ pass+ return None@classmethoddef set_state( cls,@@ -231,7 +252,7 @@ class IntegrationSyncCheck:from hi.apps.security.enums import SecurityLevelfrom hi.apps.sense.transient_models import SensorResponse- from .transient_models import IntegrationKey+ from hi.integrations.transient_models import IntegrationKeyalarm_integration_key = IntegrationKey(integration_id = 'integrations',@@ -317,8 +338,8 @@ class IntegrationSyncCheck:def _summary_message( delta : SyncDelta,integration_label : str ) -> str:"""Pure-information summary of the most recent check. The- Refresh call-to-action is rendered as a real link by the- manage-page banner template (so clicking it opens the+ update-check call-to-action is rendered as a real link by+ the manage-page banner template (so clicking it opens thepre-sync modal); it is intentionally not embedded in thisstring. The same string flows into the sidebar tooltip,where a "click here" suffix would be misleading."""diff --git a/src/hi/integrations/sync_result.py b/src/hi/integrations/connect/sync_result.pysimilarity index 100%rename from src/hi/integrations/sync_result.pyrename to src/hi/integrations/connect/sync_result.pydiff --git a/src/hi/integrations/user_data_detector.py b/src/hi/integrations/connect/user_data_detector.pysimilarity index 100%rename from src/hi/integrations/user_data_detector.pyrename to src/hi/integrations/connect/user_data_detector.pydiff --git a/src/hi/integrations/view_mixins.py b/src/hi/integrations/connect/view_mixins.pysimilarity index 80%rename from src/hi/integrations/view_mixins.pyrename to src/hi/integrations/connect/view_mixins.pyindex 6109c2a2..8836c4ef 100644--- a/src/hi/integrations/view_mixins.py+++ b/src/hi/integrations/connect/view_mixins.py@@ -1,14 +1,21 @@+from typing import FrozenSet, Optional+from django.db.models import Countfrom django.http import Http404from django.urls import reversefrom hi.apps.collection.collection_manager import CollectionManagerfrom hi.apps.collection.models import Collection, CollectionEntity-from hi.apps.entity.models import EntityView+from hi.apps.entity.models import Entity, EntityViewfrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.models import Location, LocationView+from hi.apps.sense.sensor_response_manager import SensorResponseManager+from hi.views import page_not_found_response++from hi.integrations.enums import IntegrationCapability+from hi.integrations.integration_manager import IntegrationManager+from hi.integrations.integration_metadata_cache import IntegrationMetadataCache-from .integration_manager import IntegrationManagerfrom .placement_request import PlacementUrlParams@@ -22,12 +29,70 @@ class IntegrationViewMixin:except KeyError:raise Http404()return-- def get_integration_data_list( self, enabled_only = False ):++ def get_integration_data_list(+ self,+ enabled_only : bool = False,+ capabilities : Optional[ FrozenSet[ IntegrationCapability ] ] = None,+ ):return IntegrationManager().get_integration_data_list(enabled_only = enabled_only,+ capabilities = capabilities,)+ def render_sync_result( self,+ request,+ integration_data,+ preserve_user_data : bool = True ):+ """Run the integration's synchronizer and render the+ sync-result modal. Shared by the initial-connect flow+ (IntegrationEnableView.post after enable) and the update-check+ flow (IntegrationSyncView.post after pre-sync confirm).++ Returns the modal response directly, including the placement+ URL for the 'Place N new items' CTA when sync produced new+ entities. Cache invalidations run in a ``finally`` so a+ partial-commit failure during sync also flushes."""+ synchronizer = integration_data.integration_gateway.get_synchronizer()+ if synchronizer is None:+ return page_not_found_response( request )++ is_initial_connect = not Entity.objects.filter(+ integration_id = integration_data.integration_id,+ ).exists()++ try:+ sync_result = synchronizer.sync(+ is_initial_connect = is_initial_connect,+ preserve_user_data = preserve_user_data,+ )+ finally:+ IntegrationMetadataCache().invalidate()+ SensorResponseManager().invalidate_local_sensor_cache()++ new_entity_ids = (+ sync_result.placement_input.all_entity_ids()+ if sync_result.placement_input is not None else []+ )+ placement_url = PlacementUrlParams(+ is_initial_connect = is_initial_connect,+ entity_ids = new_entity_ids,+ ).append_to_url( reverse(+ 'integrations_placement',+ kwargs = { 'integration_id': integration_data.integration_id },+ ) )++ return self.modal_response(+ request,+ context = {+ 'sync_result': sync_result,+ 'integration_data': integration_data,+ 'is_initial_connect': is_initial_connect,+ 'placement_url': placement_url,+ },+ template_name = 'integrations/modals/sync_result.html',+ )+def validate_attributes_extra_helper( self,attr_item_context,regular_attributes_formset,@@ -36,8 +101,8 @@ class IntegrationViewMixin:Validate the proposed integration configuration in two stages:1. Schema-level check via gateway.validate_configuration (offline,fast). Catches structural problems with the attribute set.- 2. Live connection probe via gateway.test_connection bounded by- IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS. Catches+ 2. Live access validation via gateway.validate_access bounded+ by IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS. Catchesunreachable upstream / bad credentials so the user sees thespecific reason inline rather than experiencing a silentsave followed by a delayed background error.@@ -76,13 +141,13 @@ class IntegrationViewMixin:)return- # Stage 2: live connection probe with bounded timeout.- test_result = gateway.test_connection(+ # Stage 2: live access validation with bounded timeout.+ test_result = gateway.validate_access(integration_attributes = integration_attributes,timeout_secs = IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS,)if not test_result.is_success:- error_message = test_result.message or 'Connection test failed'+ error_message = test_result.message or 'Access validation failed'regular_attributes_formset._non_form_errors.append(f'{error_title}: {error_message}')@@ -103,7 +168,7 @@ class IntegrationPlacementViewMixin:request,integration_data,placement_input,- is_initial_import : bool,+ is_initial_connect : bool,entity_id_filter = None ):"""Render the placement modal seeded with an``EntityPlacementInput``. Dropdowns offer both LocationView@@ -124,7 +189,7 @@ class IntegrationPlacementViewMixin:)top_default_value = self._compute_top_default_value(integration_id = integration_data.integration_id,- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,)# Decompose the tagged value into per-kind ids so the# template can do direct integer comparisons in the@@ -158,7 +223,7 @@ class IntegrationPlacementViewMixin:'new_collection_name': new_collection_name,'inventory_preview': inventory_preview,'placement_url': placement_url,- 'is_initial_import': is_initial_import,+ 'is_initial_connect': is_initial_connect,},template_name = 'integrations/modals/placement.html',)@@ -166,15 +231,15 @@ class IntegrationPlacementViewMixin:def render_dismiss_confirm( self,request,integration_data,- is_initial_import : bool,+ is_initial_connect : bool,entity_ids = None ):"""Render the NOT NOW confirmation modal. GO BACK targets- the placement GET endpoint, with is_initial_import and+ the placement GET endpoint, with is_initial_connect and(when present) the entity-id scope threaded through asquery parameters so the operator returns to the same setthey were viewing."""placement_url = PlacementUrlParams(- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,entity_ids = list( entity_ids ) if entity_ids else [],).append_to_url( reverse('integrations_placement',@@ -193,7 +258,7 @@ class IntegrationPlacementViewMixin:request,integration_data,outcome,- is_initial_import : bool ):+ is_initial_connect : bool ):"""Render the post-dispatch summary modal from a``PlacementOutcome``.@@ -219,7 +284,7 @@ class IntegrationPlacementViewMixin:context = {'integration_data': integration_data,'outcome': outcome,- 'is_initial_import': is_initial_import,+ 'is_initial_connect': is_initial_connect,'primary_action': primary_action,'secondary_action_list': secondary_action_list,},@@ -266,20 +331,20 @@ class IntegrationPlacementViewMixin:def _compute_top_default_value( self,integration_id : str,- is_initial_import : bool ) -> str:+ is_initial_connect : bool ) -> str:"""Smart default for the placement's top dropdown.- On Initial Import the operator has no existing target — pre-+ On Initial Connect the operator has no existing target — pre-select '+ New view' so they can click APPLY without furtherinput.- On Refresh, prefer whichever existing target (LocationView+ On update check, prefer whichever existing target (LocationViewOR Collection) currently holds the most entities for thisintegration. Ties broken by id ascending (deterministic).Falls back to '' (Don't place) when no existing target holdsany of this integration's entities — operator picks."""- if is_initial_import:+ if is_initial_connect:return '__new_view__'view_counts = list(diff --git a/src/hi/integrations/views.py b/src/hi/integrations/connect/views.pysimilarity index 74%rename from src/hi/integrations/views.pyrename to src/hi/integrations/connect/views.pyindex 8e92818b..690042ce 100644--- a/src/hi/integrations/views.py+++ b/src/hi/integrations/connect/views.py@@ -21,15 +21,17 @@ from hi.apps.entity.models import Entityfrom hi.apps.location.models import LocationViewfrom hi.apps.sense.sensor_response_manager import SensorResponseManager-from .placement_request import PlacementFormParser, PlacementUrlParams+from hi.integrations.enums import IntegrationCapability, IntegrationDisableMode+from hi.integrations.exceptions import IntegrationConnectionError+from hi.integrations.integration_manager import IntegrationManager+from hi.integrations.integration_metadata_cache import IntegrationMetadataCache+from hi.integrations.models import IntegrationAttribute+from .entity_operations import EntityIntegrationOperations-from .enums import IntegrationDisableMode-from .exceptions import IntegrationConnectionErrorfrom .integration_attribute_edit_context import IntegrationAttributeItemEditContext-from .integration_manager import IntegrationManager-from .integration_metadata_cache import IntegrationMetadataCache-from .models import IntegrationAttribute+from .placement_request import PlacementFormParser, PlacementUrlParamsfrom .sync_check import IntegrationSyncCheck+from .sync_result import IntegrationSyncResultfrom .view_mixins import IntegrationPlacementViewMixin, IntegrationViewMixinlogger = logging.getLogger(__name__)@@ -45,7 +47,9 @@ class IntegrationHomeView( ConfigPageView, IntegrationViewMixin ):def get_main_template_context( self, request, *args, **kwargs ):- integration_data = IntegrationManager().get_default_integration_data()+ integration_data = IntegrationManager().get_default_integration_data(+ capabilities = frozenset({ IntegrationCapability.CONNECT }),+ )if not integration_data:return dict()@@ -61,7 +65,9 @@ class IntegrationSelectView( HiModalView, IntegrationViewMixin ):def get( self, request, *args, **kwargs ):context = {- 'integration_data_list': self.get_integration_data_list(),+ 'integration_data_list': self.get_integration_data_list(+ capabilities = frozenset({ IntegrationCapability.CONNECT }),+ ),}return self.modal_response( request, context )@@ -85,22 +91,19 @@ class IntegrationHealthStatusView( HiModalView, IntegrationViewMixin ):class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):"""- Pre-sync confirmation modal. Surfaces the synchronizer's- description and offers Sync / Not now actions. Used as the last- step of the Configure flow (first-time sync) and from the IMPORT /- REFRESH button on the integration manage page (subsequent syncs).-- The modal does not display integration health: an unhealthy- integration's sync attempt will surface its failure inline with a- useful error message, and rendering health here would also expose- the brief race window between IntegrationManager.enable_integration- flipping is_enabled in the DB and the manager singleton's- notify_settings_changed reload (driven by a 0.1s post-commit- delayed signal processor — deliberately deferred to avoid a- different, worse class of problems).-- 404s when the integration does not provide a synchronizer (sync is- opt-in capability — not every integration supports it).+ Pre-sync confirmation modal for the manage-page UPDATE+ button. Surfaces the synchronizer's description and offers+ Sync / Not now actions. Not used in the first-time sync+ enable flow.++ On the update-check path the modal additionally surfaces the+ same SAFE / ALL policy choice the disable modal does when the+ integration has any user-data entities — the operator's choice+ expresses the policy applied at sync execution if any drops+ carry user data.++ 404s when the integration does not provide a synchronizer (sync+ is opt-in capability — not every integration supports it)."""def get_template_name( self ) -> str:@@ -115,40 +118,27 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):if synchronizer is None:return page_not_found_response( request )- is_initial_import = not Entity.objects.filter(+ is_initial_connect = not Entity.objects.filter(integration_id = integration_data.integration_id,).exists()sync_url = reverse('integrations_sync',kwargs = { 'integration_id': integration_data.integration_id },)- review_config_url = reverse(- 'integrations_enable',- kwargs = { 'integration_id': integration_data.integration_id },- )- # Refresh path: surface the same SAFE / ALL policy choice the- # disable modal does when the integration has any user-data- # entities. The summary is the integration's full footprint- # (not a per-sync prediction): the operator's choice- # expresses the policy applied at sync execution if any- # drops carry user data, which is the same question the- # disable modal asks. Skipped on the first-time import path- # since no entities exist yet.removal_summary = None- if not is_initial_import:+ if not is_initial_connect:removal_summary = EntityIntegrationOperations.summarize_for_removal(integration_id = integration_data.integration_id,)context = {'integration_data': integration_data,- 'is_initial_import': is_initial_import,+ 'is_initial_connect': is_initial_connect,'sync_description': synchronizer.get_description(- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,),'sync_url': sync_url,- 'review_config_url': review_config_url,'removal_summary': removal_summary,}return self.modal_response( request, context )@@ -180,20 +170,6 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin ):integration_data = self.get_integration_data(integration_id = integration_id,)- synchronizer = integration_data.integration_gateway.get_synchronizer()- if synchronizer is None:- return page_not_found_response( request )-- # Compute the operator-flow flag BEFORE running sync so the- # entities the sync is about to create don't change the- # answer. is_initial_import = "no entities for this- # integration before this sync ran"; threaded through to the- # placement GET URL so a downstream Place-items click- # carries the same operator intent.- is_initial_import = not Entity.objects.filter(- integration_id = integration_data.integration_id,- ).exists()-# Operator's per-Refresh policy for items that would be# dropped. True ("Refresh and Retain") preserves user-data# entities by detaching them; False ("Refresh and Remove")@@ -203,55 +179,10 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin ):preserve_user_data = str_to_bool(request.POST.get( 'preserve_user_data', 'true' ),)-- try:- sync_result = synchronizer.sync(- is_initial_import = is_initial_import,- preserve_user_data = preserve_user_data,- )- finally:- # Drop any cached metadata pinned by a poll that raced- # this sync — most importantly, the ``{'units': None}``- # negative entries that ``_lazy_fill`` caches on miss.- # Without this, the first poll for a newly-imported- # unit-bearing EntityState can lock in a bad entry for- # the process lifetime, showing raw (unconverted) values- # in the UI until the server restarts. ``finally`` so a- # partial-commit failure during sync also flushes.- IntegrationMetadataCache().invalidate()- # Drop the in-process Sensor lookup cache so subsequent- # polling reads pick up the new Sensor rows. Re-imported- # entities reuse their integration_keys but get new DB- # PKs and new EntityState links; without this, the- # polling status map keys responses by stale (deleted)- # EntityState PKs and the UI silently fails to update.- SensorResponseManager().invalidate_local_sensor_cache()-- # Scope the placement to just the entities this sync created.- # Without scoping, the placement's GET endpoint queries every- # unplaced entity for the integration, including pre-existing- # ones from prior incomplete placements.- new_entity_ids = (- sync_result.placement_input.all_entity_ids()- if sync_result.placement_input is not None else []- )- placement_url = PlacementUrlParams(- is_initial_import = is_initial_import,- entity_ids = new_entity_ids,- ).append_to_url( reverse(- 'integrations_placement',- kwargs = { 'integration_id': integration_data.integration_id },- ) )-- return self.modal_response(- request,- context = {- 'sync_result': sync_result,- 'integration_data': integration_data,- 'is_initial_import': is_initial_import,- 'placement_url': placement_url,- },- template_name = 'integrations/modals/sync_result.html',+ return self.render_sync_result(+ request = request,+ integration_data = integration_data,+ preserve_user_data = preserve_user_data,)@@ -289,7 +220,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,return page_not_found_response( request )url_params = PlacementUrlParams.from_data( request.GET )- is_initial_import = url_params.is_initial_import+ is_initial_connect = url_params.is_initial_connectentity_id_filter = set( url_params.entity_ids ) if url_params.entity_ids else Noneentities = EntityPlacementService.query_unplaced_entities(@@ -310,13 +241,13 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,request = request,integration_data = integration_data,synchronizer = synchronizer,- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,)return self.render_placement(request = request,integration_data = integration_data,placement_input = placement_input,- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,entity_id_filter = entity_id_filter,)@@ -326,7 +257,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,integration_id = integration_id,)url_params = PlacementUrlParams.from_data( request.POST )- is_initial_import = url_params.is_initial_import+ is_initial_connect = url_params.is_initial_connectif request.POST.get('action') == self.DISMISS_ACTION_VALUE:entity_ids = self._extract_placement_entity_ids( request )@@ -334,7 +265,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,request = request,integration_data = integration_data,entity_ids = entity_ids,- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,)decisions = PlacementFormParser.parse(@@ -345,7 +276,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,request = request,integration_data = integration_data,outcome = outcome,- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,)@staticmethod@@ -369,15 +300,14 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,return idsdef _render_empty( self, request, integration_data,- synchronizer, is_initial_import : bool ):+ synchronizer, is_initial_connect : bool ):"""No-unplaced-items acknowledgement: render the resultmodal with the integration's icon + a brief 'no items'info note rather than an empty placement. Counts stayzero so the modal lead reads 'Nothing new.'"""- from hi.integrations.sync_result import IntegrationSyncResultsync_result = IntegrationSyncResult(title = synchronizer.get_result_title(- is_initial_import = is_initial_import,+ is_initial_connect = is_initial_connect,),info_list = [ 'No items left to place.' ],)@@ -386,7 +316,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,context = {'sync_result': sync_result,'integration_data': integration_data,- 'is_initial_import': is_initial_import,+ 'is_initial_connect': is_initial_connect,},template_name = 'integrations/modals/sync_result.html',)@@ -427,36 +357,21 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditViereturn 'integrations/modals/integration_enable.html'def get(self, request, *args, **kwargs):-integration_manager = IntegrationManager()integration_id = kwargs.get('integration_id')integration_data = self.get_integration_data(integration_id = integration_id,)-- # Both first-time Configure (is_enabled=False) and Review Config- # from the pre-sync modal (is_enabled=True) land here. Review- # mode swaps CONFIGURE→UPDATE for the action button and replaces- # the dismiss-CANCEL with a CONTINUE that returns to pre-sync.- is_review_mode = integration_data.integration.is_enabled- pre_sync_url = (- reverse(- 'integrations_pre_sync',- kwargs = { 'integration_id': integration_data.integration_id },- ) if is_review_mode else None- )-integration_manager.ensure_all_attributes_exist(integration_metadata = integration_data.integration_metadata,integration = integration_data.integration,)attr_item_context = IntegrationAttributeItemEditContext(integration_data = integration_data,- update_button_label = 'UPDATE' if is_review_mode else 'CONFIGURE',+ capability = IntegrationCapability.CONNECT,+ update_button_label = 'CONNECT',suppress_history = True,show_secrets = True,- is_review_mode = is_review_mode,- pre_sync_url = pre_sync_url,)template_context = self.create_initial_template_context(attr_item_context= attr_item_context,@@ -469,27 +384,12 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVieintegration_data = self.get_integration_data(integration_id = integration_id,)-- # Both first-time Configure (is_enabled=False) and Review Config- # from the pre-sync modal (is_enabled=True) post here. Review- # mode flags drive the button label and the cancel→continue- # swap on form-error rerenders. enable_integration is- # idempotent, so the call below is safe in both contexts.- is_review_mode = integration_data.integration.is_enabled- pre_sync_url = (- reverse(- 'integrations_pre_sync',- kwargs = { 'integration_id': integration_data.integration_id },- ) if is_review_mode else None- )-attr_item_context = IntegrationAttributeItemEditContext(integration_data = integration_data,- update_button_label = 'UPDATE' if is_review_mode else 'CONFIGURE',+ capability = IntegrationCapability.CONNECT,+ update_button_label = 'CONNECT',suppress_history = True,show_secrets = True,- is_review_mode = is_review_mode,- pre_sync_url = pre_sync_url,)response = self.post_attribute_form(request = request,@@ -504,42 +404,18 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVieintegration_data = integration_data,)- # Configure flow last step: when the integration supports sync,- # transition directly into the pre-sync confirmation modal- # instead of redirecting to the manage page. attr.js's response- # handler (extended for `data.modal`) closes the Configure- # modal and opens the new modal in its place via antinode's- # AN.displayModal — same lifecycle antinode applies to its own- # modal-to-modal transitions.+ # Phase 7 collapse: when the integration supports sync, run it+ # right here and render the sync-result modal directly. The+ # previous Configure → Pre-Sync → Sync handshake is now one+ # CONNECT click. Synchronizer-less integrations keep the+ # original redirect-to-manage behavior.synchronizer = integration_data.integration_gateway.get_synchronizer()if synchronizer is not None:- is_initial_import = not Entity.objects.filter(- integration_id = integration_data.integration_id,- ).exists()- sync_url = reverse(- 'integrations_sync',- kwargs = { 'integration_id': integration_data.integration_id },- )- review_config_url = reverse(- 'integrations_enable',- kwargs = { 'integration_id': integration_data.integration_id },- )- return self.modal_response(- request,- context = {- 'integration_data': integration_data,- 'is_initial_import': is_initial_import,- 'sync_description': synchronizer.get_description(- is_initial_import = is_initial_import,- ),- 'sync_url': sync_url,- 'review_config_url': review_config_url,- },- template_name = 'integrations/modals/pre_sync_confirm.html',+ return self.render_sync_result(+ request = request,+ integration_data = integration_data,)- # Integrations without a synchronizer keep the original- # redirect-to-manage-page behavior.redirect_url = reverse( 'integrations_manage',kwargs = { 'integration_id': integration_id } )return AttributeRedirectResponse( url = redirect_url )@@ -665,19 +541,25 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEditintegration_id = integration_id,)else:- integration_data = integration_manager.get_default_integration_data()-+ integration_data = integration_manager.get_default_integration_data(+ capabilities = frozenset({ IntegrationCapability.CONNECT }),+ )+if not integration_data.integration.is_enabled:raise BadRequest( f'{integration_data.label} integration is not configured' )-+# Get health status from the integration gatewayhealth_status_provider = integration_data.integration_gateway.get_health_status_provider()-+attr_item_context = IntegrationAttributeItemEditContext(integration_data = integration_data,+ capability = IntegrationCapability.CONNECT,health_status = health_status_provider.health_status,)- integration_data_list = self.get_integration_data_list( enabled_only = True )+ integration_data_list = self.get_integration_data_list(+ enabled_only = True,+ capabilities = frozenset({ IntegrationCapability.CONNECT }),+ )manage_view_pane = integration_data.integration_gateway.get_manage_view_pane()manage_template_name = manage_view_pane.get_template_name()@@ -740,7 +622,9 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEditintegration_id = integration_id,)else:- integration_data = integration_manager.get_default_integration_data()+ integration_data = integration_manager.get_default_integration_data(+ capabilities = frozenset({ IntegrationCapability.CONNECT }),+ )if not integration_data.integration.is_enabled:raise BadRequest( f'{integration_data.label} integration is not configured' )@@ -750,6 +634,7 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEditattr_item_context = IntegrationAttributeItemEditContext(integration_data = integration_data,+ capability = IntegrationCapability.CONNECT,health_status = health_status_provider.health_status,)@@ -787,6 +672,7 @@ class IntegrationAttributeHistoryInlineView( View,)attr_item_context = IntegrationAttributeItemEditContext(integration_data = integration_data,+ capability = IntegrationCapability.CONNECT,)return self.get_history(request = request,@@ -815,6 +701,7 @@ class IntegrationAttributeRestoreInlineView( View,attr_item_context = IntegrationAttributeItemEditContext(integration_data = integration_data,+ capability = IntegrationCapability.CONNECT,)return self.post_restore(request = request,diff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.pyindex 9e93750a..b2327b50 100644--- a/src/hi/integrations/enums.py+++ b/src/hi/integrations/enums.py@@ -1,9 +1,18 @@-from typing import Dict+from typing import Dict, FrozenSet, Optionalfrom hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.common.enums import LabeledEnum+class IntegrationCapability( LabeledEnum ):++ CONNECT = ( 'Connect', 'Live mirror of an upstream system.' )+ IMPORT = ( 'Import', 'One-shot pull of upstream items into HI.' )+++ALL_CAPABILITIES = frozenset( IntegrationCapability )++class IntegrationDisableMode( LabeledEnum ):"""Mode used when removing (disabling) an integration. Controls how the@@ -32,7 +41,7 @@ class IntegrationDisableMode( LabeledEnum ):class IntegrationAttributeType( LabeledEnum ):""" Abstract base class for integrations ot define the required attributes they need. """-+def __init__( self,label : str,description : str,@@ -40,11 +49,13 @@ class IntegrationAttributeType( LabeledEnum ):value_range_dict : Dict[ str, str ],is_editable : bool,is_required : bool,- initial_value : str = '' ):+ initial_value : str = '',+ capabilities : Optional[ FrozenSet[ IntegrationCapability ] ] = None ):super().__init__( label, description )self.value_type = value_typeself.value_range_dict = value_range_dictself.is_editable = is_editableself.is_required = is_requiredself.initial_value = initial_value+ self.capabilities = capabilities if capabilities is not None else ALL_CAPABILITIESreturndiff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.pyindex 6c352db7..4442c3c1 100644--- a/src/hi/integrations/integration_manager.py+++ b/src/hi/integrations/integration_manager.py@@ -3,7 +3,7 @@ import asyncioimport jsonimport loggingimport threading-from typing import Dict, List+from typing import Dict, FrozenSet, List, Optionalfrom django.apps import appsfrom django.conf import settings@@ -18,11 +18,11 @@ from hi.apps.common.module_utils import import_module_safefrom hi.apps.entity.models import Entityfrom hi.apps.system.health_status_provider import HealthStatusProvider-from .entity_operations import EntityIntegrationOperations-from .enums import IntegrationAttributeType, IntegrationDisableMode+from .connect.entity_operations import EntityIntegrationOperations+from .enums import IntegrationAttributeType, IntegrationCapability, IntegrationDisableModefrom .exceptions import IntegrationConnectionError-from .integration_data import IntegrationData-from .integration_gateway import IntegrationGateway+from .connect.integration_data import IntegrationData+from .connect.integration_gateway import IntegrationGatewayfrom .transient_models import IntegrationKeyfrom .models import Integration, IntegrationAttributefrom .transient_models import IntegrationMetaData@@ -35,7 +35,7 @@ class IntegrationManager( Singleton ):START_DELAY_INTERVAL_SECS = 2# Bounded timeout (in seconds) used when an integration's gateway- # test_connection() probe is invoked synchronously during attribute-save+ # validate_access() probe is invoked synchronously during attribute-save# validation or before relaunching monitors. Kept short for interactive# save-time UX; can be promoted to a user-tunable setting later if# demand emerges.@@ -68,18 +68,34 @@ class IntegrationManager( Singleton ):sync_check_monitor.stop()return- def get_integration_data_list( self, enabled_only = False ) -> List[ IntegrationData ]:+ def get_integration_data_list(+ self,+ enabled_only : bool = False,+ capabilities : Optional[ FrozenSet[ IntegrationCapability ] ] = None,+ ) -> List[ IntegrationData ]:if enabled_only:integration_data_list = [ x for x in self._integration_data_map.values() if x.is_enabled ]else:integration_data_list = list( self._integration_data_map.values() )-+ if capabilities is not None:+ integration_data_list = [+ x for x in integration_data_list+ if x.integration_metadata.capabilities & capabilities+ ]integration_data_list.sort( key = lambda data : data.integration_metadata.label )return integration_data_list-- def get_default_integration_data( self ) -> IntegrationData:++ def get_default_integration_data(+ self,+ capabilities : Optional[ FrozenSet[ IntegrationCapability ] ] = None,+ ) -> IntegrationData:enabled_integration_data_list = [ x for x in self._integration_data_map.values()if x.is_enabled ]+ if capabilities is not None:+ enabled_integration_data_list = [+ x for x in enabled_integration_data_list+ if x.integration_metadata.capabilities & capabilities+ ]if not enabled_integration_data_list:return Noneenabled_integration_data_list.sort( key = lambda data : data.integration_metadata.label )@@ -251,7 +267,7 @@ class IntegrationManager( Singleton ):# monitor module imports IntegrationManager lazily inside its# do_work, but the manager only needs the class here for# construction.- from .monitors import IntegrationSyncCheckMonitor+ from .connect.monitors import IntegrationSyncCheckMonitorif settings.DEBUG and settings.SUPPRESS_MONITORS:logger.debug( 'Skipping sync-check monitor. See SUPPRESS_MONITORS = True' )@@ -584,7 +600,7 @@ class IntegrationManager( Singleton ):_launch_integration_monitor_task is idempotent when the monitor isalready running.- Probes upstream connectivity via the gateway's test_connection+ Probes upstream connectivity via the gateway's validate_accessbefore relaunching, so we fail fast (with a meaningful error tothe caller) rather than spinning up monitors that will immediatelyerror against an unreachable service. Raises@@ -605,13 +621,13 @@ class IntegrationManager( Singleton ):integration_attributes = list(integration_data.integration.attributes.all())- test_result = integration_data.integration_gateway.test_connection(+ test_result = integration_data.integration_gateway.validate_access(integration_attributes = integration_attributes,timeout_secs = self.HEALTH_CHECK_TIMEOUT_SECS,)if not test_result.is_success:raise IntegrationConnectionError(- test_result.message or 'Connection test failed during resume.'+ test_result.message or 'Access validation failed during resume.')with self._data_lock:diff --git a/src/hi/integrations/templates/integrations/modals/placement.html b/src/hi/integrations/templates/integrations/modals/placement.htmlindex 966c88f1..464e7bef 100644--- a/src/hi/integrations/templates/integrations/modals/placement.html+++ b/src/hi/integrations/templates/integrations/modals/placement.html@@ -50,7 +50,7 @@ Context:this modal; the form POSTs back to itand the view branches on the submitted``action`` value.- is_initial_import : bool (required)+ is_initial_connect : bool (required){% endcomment %}{% block title_text %}@@ -65,8 +65,8 @@ Place new itemsPre-sync intent threaded forward so the post-dispatch modaltitles itself consistently with what the operator clicked.{% endcomment %}- <input type="hidden" name="is_initial_import"- value="{{ is_initial_import|yesno:'1,0' }}">+ <input type="hidden" name="is_initial_connect"+ value="{{ is_initial_connect|yesno:'1,0' }}">{% endblock %}{% block body %}diff --git a/src/hi/integrations/templates/integrations/modals/placement_dismiss.html b/src/hi/integrations/templates/integrations/modals/placement_dismiss.htmlindex d11908d1..378ed015 100644--- a/src/hi/integrations/templates/integrations/modals/placement_dismiss.html+++ b/src/hi/integrations/templates/integrations/modals/placement_dismiss.html@@ -31,7 +31,7 @@ Items left unplaced{% block body %}<p>The new items from <strong>{{ integration_data.label }}</strong>- are imported but won't appear in any view yet. You can place them+ are connected but won't appear in any view yet. You can place themin views and collections at any time from edit mode.</p>{% endblock %}diff --git a/src/hi/integrations/templates/integrations/modals/post_placement.html b/src/hi/integrations/templates/integrations/modals/post_placement.htmlindex c5bcc8df..7ec6ed57 100644--- a/src/hi/integrations/templates/integrations/modals/post_placement.html+++ b/src/hi/integrations/templates/integrations/modals/post_placement.html@@ -22,14 +22,14 @@ Context:outcome : PlacementOutcome (required)primary_action : (PlacementSummary, url) | Nonesecondary_action_list : List[(PlacementSummary, url)]- is_initial_import : bool (required)+ is_initial_connect : bool (required){% endcomment %}{% block title_text %}-{% if is_initial_import %}-Import complete+{% if is_initial_connect %}+Connect completed{% else %}-Refresh complete+Update check complete{% endif %}{% endblock %}@@ -53,7 +53,7 @@ Refresh complete{% endif %}{% if primary_action and primary_action.0.is_view %}<p>- Imported items start at a default position in each view;+ Connected items start at a default position in each view;use <strong>Refine</strong> to drag them into place.</p>{% endif %}diff --git a/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html b/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.htmlindex 3a2a402f..29c1e8dd 100644--- a/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html+++ b/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html@@ -2,62 +2,41 @@{% load icons %}{% comment %}-Pre-sync confirmation modal for integrations.--Shown as the last step of the Configure flow (first-time import) and-when the operator clicks the IMPORT / REFRESH button on the-integration manage page (subsequent refreshes). The modal confirms+Pre-sync confirmation modal for the manage-page UPDATE+button. Not used for the first-time enable sync flow. The modal confirmsintent and explains what the operation will do; it does NOT surface-integration health. Health is surfaced on the manage page itself, and-an unhealthy integration's attempt will surface its failure inline-with a useful error message.--The first-time IMPORT and subsequent REFRESH paths are both rendered-by this template. They differ in title, lead text, and primary action-label, controlled by `is_initial_import`. The synchronizer's-description copy is also import/refresh-aware.+integration health.-The REVIEW CONFIG action is rendered only on the first-time path: in-that path the user just came from the Configure modal and may have-breezed past secondary configuration that the synchronizer's-description now calls out (e.g., HASS allowlist). REVIEW CONFIG-re-opens the same Configure modal as a "back one step" affordance;-saving from there returns to this modal. On the manage-page entry-path, the user came from the manage page and the inherited CANCEL-already takes them "back" to it.+`is_initial_connect` is still threaded because the manage page can+expose a CONNECT variant when the integration is enabled but has no+attached entities (e.g., entities deleted post-enable). That path+shares this template.-When `removal_summary.has_mixed_state` (Refresh path with at least-one user-data entity present), the modal symmetrically mirrors the-disable modal's policy choice: REFRESH AND RETAIN preserves dropped-user-data items by detaching, REFRESH AND REMOVE hard-deletes them.-The summary is the integration's full footprint (not a per-sync-prediction); the operator's choice expresses policy that applies at-sync execution if any drops carry user data.+When `removal_summary.has_mixed_state` (update-check path with at+least one user-data entity present), the modal mirrors the disable+modal's policy choice: RETAIN MISSING preserves dropped user-data+items by detaching, REMOVE MISSING hard-deletes them. The summary is+the integration's full footprint; the operator's choice expresses+policy that applies at sync execution if any drops carry user data.The form is opened in `preamble` and closed in `postamble` so eachaction button is a plain `<button name="preserve_user_data" value=…>`on the same form (mirrors the integration_disable.html pattern).-The REVIEW CONFIG anchor on the first-time path sits inside the-form harmlessly — it navigates rather than submitting.Context:integration_data : IntegrationData (required) — for label, id.- is_initial_import : bool (required) — True when no entities for+ is_initial_connect : bool (required) — True when no entities forthis integration have been imported yet- (initial IMPORT); False for subsequent- REFRESH operations.+ (initial CONNECT); False for subsequent+ update-check operations.sync_description : Optional[str] — per-integration text fromIntegrationSynchronizer.get_description.sync_url : str (required) — URL the form posts to.- review_config_url : str (required) — URL the REVIEW CONFIG- action opens (the integrations_enable- modal).removal_summary : Optional[IntegrationRemovalSummary] —integration's user-data classification.- None on the first-time import path; a- zero-count summary when no entities are- attached. Drives the Retain / Remove- choice on the Refresh path.+ None when no entities are attached. Drives+ the Retain / Remove choice on the+ update-check path.{% endcomment %}{% block preamble %}@@ -66,30 +45,31 @@ Context:{% endblock %}{% block title_text %}-{% if is_initial_import %}-Import from {{ integration_data.label }}?+{% if is_initial_connect %}+Connect to {{ integration_data.label }}?{% else %}-Refresh from {{ integration_data.label }}?+Check {{ integration_data.label }} for updates?{% endif %}{% endblock %}{% block body %}-{% if is_initial_import %}+{% if is_initial_connect %}<p>- Import will pull items from <strong>{{ integration_data.label }}</strong>- into Home Information for the first time. Imported items can be+ Connect will pull items from <strong>{{ integration_data.label }}</strong>+ into Home Information for the first time. Connected items can beplaced into your views in the next step.</p>{% else %}<p>- Refresh adds new items from <strong>{{ integration_data.label }}</strong>,- updates ones that have changed, and removes ones no longer present.+ Checking for updates adds new items from+ <strong>{{ integration_data.label }}</strong>, updates ones that+ have changed, and removes ones no longer present.</p>{% if removal_summary.has_mixed_state %}<p>This integration has <strong>{{ removal_summary.user_data_count }}</strong>{% if removal_summary.user_data_count == 1 %}item{% else %}items{% endif %}- with custom data you've added. If a Refresh would drop+ with custom data you've added. If an update would drop{% if removal_summary.user_data_count == 1 %}that item{% else %}any of them{% endif %}:</p><ul>@@ -113,14 +93,7 @@ Refresh from {{ integration_data.label }}?{% endblock %}{% block action_center %}-{% if is_initial_import %}-<a href="{{ review_config_url }}"- role="button"- class="btn btn-outline-primary"- data-async="modal">- {% icon "settings" size="lg" css_class="hi-icon-left" %}REVIEW CONFIG-</a>-{% elif removal_summary.has_mixed_state %}+{% if removal_summary.has_mixed_state %}<button type="submit" class="btn btn-outline-danger ml-2"name="preserve_user_data" value="false">{% icon "warning" size="sm" css_class="hi-icon-left" %}REMOVE MISSING@@ -129,9 +102,9 @@ Refresh from {{ integration_data.label }}?{% endblock %}{% block action_right %}-{% if is_initial_import %}+{% if is_initial_connect %}<button type="submit" class="btn btn-primary">- {% icon "upload" size="lg" css_class="hi-icon-left" %}IMPORT+ {% icon "upload" size="lg" css_class="hi-icon-left" %}CONNECT</button>{% elif removal_summary.has_mixed_state %}<button type="submit" class="btn btn-primary"@@ -140,7 +113,7 @@ Refresh from {{ integration_data.label }}?</button>{% else %}<button type="submit" class="btn btn-primary">- {% icon "sync" size="lg" css_class="hi-icon-left" %}REFRESH+ {% icon "sync" size="lg" css_class="hi-icon-left" %}UPDATE</button>{% endif %}{% endblock %}diff --git a/src/hi/integrations/templates/integrations/modals/sync_result.html b/src/hi/integrations/templates/integrations/modals/sync_result.htmlindex f2e25a39..46e40f2c 100644--- a/src/hi/integrations/templates/integrations/modals/sync_result.html+++ b/src/hi/integrations/templates/integrations/modals/sync_result.html@@ -18,7 +18,7 @@the footer is a single dismissal button.The modal title bar keeps the generic HI logo + short generic- title ('Import Result' / 'Refresh Result'); the integration's+ title ('Connect Result' / 'Update Check Result'); the integration'sidentity is surfaced as a body subtitle row (logo + label) wherethe white background gives the transparent integration logospredictable contrast.@@ -59,7 +59,7 @@<div class="text-center mb-4"><div class="text-danger mb-1 hi-sync-result-hero-icon">⚠</div><h3 class="text-danger mb-1">- {% if is_initial_import %}Import failed{% else %}Refresh failed{% endif %}+ {% if is_initial_connect %}Connect failed{% else %}Update check failed{% endif %}</h3><div class="text-muted small">{{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.@@ -69,7 +69,7 @@<div class="text-center mb-4"><div class="text-warning mb-1 hi-sync-result-hero-icon">⚠</div><h3 class="text-warning mb-1">- {% if is_initial_import %}Import completed with errors{% else %}Refresh completed with errors{% endif %}+ {% if is_initial_connect %}Connect completed with errors{% else %}Update check completed with errors{% endif %}</h3><div class="text-muted small">{{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.@@ -79,13 +79,13 @@<div class="text-center mb-4"><div class="text-muted mb-1 hi-sync-result-hero-icon">—</div><h3 class="text-muted mb-1">- {% if is_initial_import %}Nothing to import{% else %}Nothing new{% endif %}+ {% if is_initial_connect %}No items found.{% else %}Nothing new{% endif %}</h3><div class="text-muted small">- {% if is_initial_import %}- No items found upstream.+ {% if is_initial_connect %}+ The connection succeeded but the upstream source returned no items.{% else %}- No changes since the last refresh.+ No changes since the last update check.{% endif %}</div></div>@@ -93,7 +93,7 @@<div class="text-center mb-3"><div class="text-success mb-1 hi-sync-result-hero-icon">✓</div><h3 class="text-success mb-1">- {% if is_initial_import %}Import complete{% else %}Refresh complete{% endif %}+ {% if is_initial_connect %}Connect complete{% else %}Update check complete{% endif %}</h3></div>diff --git a/src/hi/integrations/templates/integrations/pages/integration_manage.html b/src/hi/integrations/templates/integrations/pages/integration_manage.htmlindex 0a441242..77a84615 100644--- a/src/hi/integrations/templates/integrations/pages/integration_manage.html+++ b/src/hi/integrations/templates/integrations/pages/integration_manage.html@@ -64,7 +64,7 @@Click<a href="{% url 'integrations_pre_sync' integration_id=core.integration_data.integration_id %}"class="alert-link"- data-async="modal">REFRESH</a>.+ data-async="modal">Update</a>.</div>{% endif %}{% include core.manage_view_template_name %}diff --git a/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.html b/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.htmlindex f6e455bc..92c49445 100644--- a/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.html+++ b/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.html@@ -6,19 +6,11 @@{% block additional_actions %}{% if show_modal_cancel %}-{% if is_review_mode %}-<a role="button" {% if autofocus %}autofocus="autofocus"{% endif %}- class="btn btn-outline-tertiary" href="{{ pre_sync_url }}"- data-async="modal">- CONTINUE {% icon "chevron-right" size="sm" css_class="hi-icon-right" %}-</a>-{% else %}<a id="hi-modal-cancel" role="button" {% if autofocus %}autofocus="autofocus"{% endif %}class="btn btn-outline-tertiary" href="#" data-dismiss="modal">{% icon "cancel" size="sm" css_class="hi-icon-left" %}CANCEL</a>{% endif %}-{% endif %}<!-- Integration Health Status Display -->{% if health_status %}diff --git a/src/hi/integrations/templates/integrations/panes/sync_actions.html b/src/hi/integrations/templates/integrations/panes/sync_actions.htmlindex e6c26dac..d385890a 100644--- a/src/hi/integrations/templates/integrations/panes/sync_actions.html+++ b/src/hi/integrations/templates/integrations/panes/sync_actions.html@@ -1,6 +1,6 @@{% load icons %}{% comment %}- Shared IMPORT / REFRESH framework action.+ Shared CONNECT / UPDATE framework action.Sync is a framework concern; integrations participate by providing anIntegrationSynchronizer from their gateway's get_synchronizer().@@ -8,14 +8,14 @@(b) the gateway returning a synchronizer. Integrations whose gatewayreturns None (sync is opt-in) get no button.- Label flips on `core.has_entities`: IMPORT for the first-time path,- REFRESH for subsequent re-syncs. The framework manage view computes- has_entities into the `core` context.+ Label flips on `core.has_entities`: CONNECT for the first-time path,+ UPDATE for subsequent re-syncs. The framework manage+ view computes has_entities into the `core` context.When the Issue #283 sync-check probe has detected upstream drift- (`core.sync_check_result.needs_sync`), the REFRESH variant+ (`core.sync_check_result.needs_sync`), the update-check variantpromotes from outline-secondary to solid btn-primary so it pulls- the eye. The IMPORT variant is always primary since there is+ the eye. The CONNECT variant is always primary since there isnothing to compare against on a first run.{% endcomment %}{% if core.integration_data.is_enabled and core.integration_data.integration_gateway.get_synchronizer %}@@ -24,9 +24,9 @@role="button"data-async="modal">{% if core.has_entities %}- {% icon "sync" size="lg" css_class="hi-icon-left" %}REFRESH+ {% icon "sync" size="lg" css_class="hi-icon-left" %}UPDATE{% else %}- {% icon "upload" size="lg" css_class="hi-icon-left" %}IMPORT+ {% icon "upload" size="lg" css_class="hi-icon-left" %}CONNECT{% endif %}</a>{% endif %}diff --git a/src/hi/integrations/tests/test_entity_operations.py b/src/hi/integrations/tests/test_entity_operations.pyindex b392cb9f..e3f6d168 100644--- a/src/hi/integrations/tests/test_entity_operations.py+++ b/src/hi/integrations/tests/test_entity_operations.py@@ -15,7 +15,7 @@ from hi.apps.attribute.enums import AttributeType, AttributeValueTypefrom hi.apps.entity.models import Entity, EntityAttribute, EntityState, EntityStateDelegationfrom hi.apps.event.models import EventClause, EventDefinitionfrom hi.apps.sense.models import Sensor-from hi.integrations.entity_operations import EntityIntegrationOperations+from hi.integrations.connect.entity_operations import EntityIntegrationOperationslogging.disable(logging.CRITICAL)@@ -388,7 +388,7 @@ class FindReconnectCandidatesTests(TestCase):)upstream_key = self._make_upstream_key('light.kitchen')- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResultresult = IntegrationSyncResult(title='Test')candidates = EntityIntegrationOperations.find_reconnect_candidates(@@ -424,7 +424,7 @@ class FindReconnectCandidatesTests(TestCase):ambiguous_key = self._make_upstream_key('light.ambiguous')unmatched_key = self._make_upstream_key('light.never_existed')- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResultresult = IntegrationSyncResult(title='Mixed')candidates = EntityIntegrationOperations.find_reconnect_candidates(diff --git a/src/hi/integrations/tests/test_external_view_data.py b/src/hi/integrations/tests/test_external_view_data.pyindex cf398491..1e6ce79c 100644--- a/src/hi/integrations/tests/test_external_view_data.py+++ b/src/hi/integrations/tests/test_external_view_data.py@@ -11,14 +11,14 @@ import loggingfrom django.test import TestCase-from hi.integrations.external_view_data import (+from hi.integrations.connect.external_view_data import (AttachmentRef,CustomTemplateViewData,MinimalViewData,NameValuePair,StructuredViewData,)-from hi.integrations.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_gateway import IntegrationGatewaylogging.disable(logging.CRITICAL)diff --git a/src/hi/integrations/tests/test_initializers.py b/src/hi/integrations/tests/test_initializers.pyindex 4ebbbe6a..50156c8d 100644--- a/src/hi/integrations/tests/test_initializers.py+++ b/src/hi/integrations/tests/test_initializers.py@@ -5,7 +5,7 @@ from django.test import TestCasefrom hi.apps.attribute.enums import AttributeValueTypefrom hi.integrations.enums import IntegrationAttributeTypefrom hi.integrations.initializers import IntegrationInitializer-from hi.integrations.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manager import IntegrationManagerfrom hi.integrations.models import Integration, IntegrationAttributefrom hi.integrations.transient_models import IntegrationMetaDatadiff --git a/src/hi/integrations/tests/test_integration_attribute_edit_context.py b/src/hi/integrations/tests/test_integration_attribute_edit_context.pynew file mode 100644index 00000000..61d2e261--- /dev/null+++ b/src/hi/integrations/tests/test_integration_attribute_edit_context.py@@ -0,0 +1,108 @@+"""+Unit tests for IntegrationAttributeItemEditContext capability filtering.+"""++import logging++from django.test import TestCase++from hi.apps.attribute.enums import AttributeValueType+from hi.integrations.connect.integration_attribute_edit_context import (+ IntegrationAttributeItemEditContext,+)+from hi.integrations.connect.integration_data import IntegrationData+from hi.integrations.connect.integration_gateway import IntegrationGateway+from hi.integrations.enums import (+ ALL_CAPABILITIES,+ IntegrationAttributeType,+ IntegrationCapability,+)+from hi.integrations.models import Integration, IntegrationAttribute+from hi.integrations.transient_models import (+ ConnectionTestResult,+ IntegrationKey,+ IntegrationMetaData,+)++logging.disable(logging.CRITICAL)+++class MixedCapAttributeType(IntegrationAttributeType):+ """AttributeType with one member per capability shape (Connect-only,+ Import-only, both)."""++ CONNECT_FIELD = (+ 'Connect Field', '', AttributeValueType.TEXT, None, True, True, '',+ frozenset({ IntegrationCapability.CONNECT }),+ )+ IMPORT_FIELD = (+ 'Import Field', '', AttributeValueType.TEXT, None, True, True, '',+ frozenset({ IntegrationCapability.IMPORT }),+ )+ SHARED_FIELD = (+ 'Shared Field', '', AttributeValueType.TEXT, None, True, True, '',+ ALL_CAPABILITIES,+ )+++class _MixedCapGateway(IntegrationGateway):++ INTEGRATION_ID = 'mixed_cap'++ def get_metadata(self):+ return IntegrationMetaData(+ integration_id=self.INTEGRATION_ID,+ label='Mixed Cap',+ attribute_type=MixedCapAttributeType,+ allow_entity_deletion=True,+ capabilities=ALL_CAPABILITIES,+ )++ def validate_access(self, integration_attributes, timeout_secs):+ return ConnectionTestResult.success()+++class CapabilityFilteredFormsetTests(TestCase):++ def setUp(self):+ self.integration = Integration.objects.create(+ integration_id=_MixedCapGateway.INTEGRATION_ID,+ is_enabled=True,+ )+ for member in MixedCapAttributeType:+ IntegrationAttribute.objects.create(+ integration=self.integration,+ name=member.label,+ value='',+ value_type_str=str(member.value_type),+ integration_key_str=IntegrationKey(+ integration_id=self.integration.integration_id,+ integration_name=str(member),+ ).integration_key_str,+ )+ self.integration_data = IntegrationData(+ integration_gateway=_MixedCapGateway(),+ integration=self.integration,+ )++ def _attribute_names_for(self, capability):+ edit_context = IntegrationAttributeItemEditContext(+ integration_data=self.integration_data,+ capability=capability,+ )+ return sorted(+ attr.integration_key.integration_name+ for attr in edit_context._capability_filtered_attribute_queryset()+ )++ def test_connect_context_excludes_import_only(self):+ self.assertEqual(+ self._attribute_names_for(IntegrationCapability.CONNECT),+ ['connect_field', 'shared_field'],+ )++ def test_import_context_excludes_connect_only(self):+ self.assertEqual(+ self._attribute_names_for(IntegrationCapability.IMPORT),+ ['import_field', 'shared_field'],+ )diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.pyindex 61f52081..c273dd1a 100644--- a/src/hi/integrations/tests/test_integration_manager.py+++ b/src/hi/integrations/tests/test_integration_manager.py@@ -14,15 +14,19 @@ from hi.apps.entity.models import Entity, EntityAttribute, EntityStatefrom hi.apps.event.models import EventClause, EventDefinitionfrom hi.integrations.exceptions import IntegrationConnectionErrorfrom hi.integrations.integration_manager import IntegrationManager-from hi.integrations.integration_data import IntegrationData-from hi.integrations.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_data import IntegrationData+from hi.integrations.connect.integration_gateway import IntegrationGatewayfrom hi.integrations.models import Integration, IntegrationAttributefrom hi.integrations.transient_models import (ConnectionTestResult,IntegrationMetaData,IntegrationKey,)-from hi.integrations.enums import IntegrationAttributeType, IntegrationDisableMode+from hi.integrations.enums import (+ IntegrationAttributeType,+ IntegrationCapability,+ IntegrationDisableMode,+)logging.disable(logging.CRITICAL)@@ -37,22 +41,27 @@ class MockIntegrationGateway(IntegrationGateway):"""Mock integration gateway for testing."""def __init__(self, integration_id='test_integration', label='Test Integration',- connection_test_result=None):+ connection_test_result=None, capabilities=None):self.integration_id = integration_idself.label = label# Default to a passing probe so existing resume/pause tests don't- # need to know about the new test_connection step.+ # need to know about the new validate_access step.self.connection_test_result = (connection_test_result if connection_test_result is not Noneelse ConnectionTestResult.success())+ self.capabilities = (+ capabilities if capabilities is not None+ else frozenset({ IntegrationCapability.CONNECT })+ )def get_metadata(self):return IntegrationMetaData(integration_id=self.integration_id,label=self.label,attribute_type=MockIntegrationAttributeType,- allow_entity_deletion=True+ allow_entity_deletion=True,+ capabilities=self.capabilities,)def get_manage_view_pane(self):@@ -64,7 +73,7 @@ class MockIntegrationGateway(IntegrationGateway):def get_controller(self):return Mock()- def test_connection(self, integration_attributes, timeout_secs):+ def validate_access(self, integration_attributes, timeout_secs):return self.connection_test_result@@ -173,6 +182,62 @@ class IntegrationManagerTestCase(TestCase):self.assertEqual([data.integration_id for data in enabled_integrations],['beta_integration', 'zebra_integration'])+ def test_integration_data_list_capability_filter(self):+ manager = IntegrationManager()++ connect_int = Integration.objects.create(+ integration_id='connect_int', is_enabled=True,+ )+ import_int = Integration.objects.create(+ integration_id='import_int', is_enabled=True,+ )+ both_int = Integration.objects.create(+ integration_id='both_int', is_enabled=True,+ )++ manager._integration_data_map = {+ 'connect_int': IntegrationData(+ integration_gateway=MockIntegrationGateway(+ 'connect_int', 'Connect Service',+ capabilities=frozenset({ IntegrationCapability.CONNECT }),+ ),+ integration=connect_int,+ ),+ 'import_int': IntegrationData(+ integration_gateway=MockIntegrationGateway(+ 'import_int', 'Import Service',+ capabilities=frozenset({ IntegrationCapability.IMPORT }),+ ),+ integration=import_int,+ ),+ 'both_int': IntegrationData(+ integration_gateway=MockIntegrationGateway(+ 'both_int', 'Both Service',+ capabilities=frozenset({+ IntegrationCapability.CONNECT,+ IntegrationCapability.IMPORT,+ }),+ ),+ integration=both_int,+ ),+ }++ connect_filtered = manager.get_integration_data_list(+ capabilities=frozenset({ IntegrationCapability.CONNECT }),+ )+ self.assertEqual(+ sorted([d.integration_id for d in connect_filtered]),+ ['both_int', 'connect_int'],+ )++ import_filtered = manager.get_integration_data_list(+ capabilities=frozenset({ IntegrationCapability.IMPORT }),+ )+ self.assertEqual(+ sorted([d.integration_id for d in import_filtered]),+ ['both_int', 'import_int'],+ )+def test_get_default_integration_data(self):"""Test default integration selection logic."""manager = IntegrationManager()@@ -975,7 +1040,7 @@ class IntegrationManagerTestCase(TestCase):self.assertTrue(integration.is_paused)def test_resume_integration_passes_bounded_timeout_to_gateway(self):- """Resume must invoke test_connection with the configured bounded timeout."""+ """Resume must invoke validate_access with the configured bounded timeout."""manager = IntegrationManager()manager.reset_for_testing()@@ -987,7 +1052,7 @@ class IntegrationManagerTestCase(TestCase):gateway = MockIntegrationGateway('resume_timeout_test')data = IntegrationData(integration_gateway=gateway, integration=integration)- with patch.object(gateway, 'test_connection',+ with patch.object(gateway, 'validate_access',return_value=ConnectionTestResult.success()) as mock_probe:with patch.object(manager, '_launch_integration_monitor_task'):manager.resume_integration(data)@@ -1016,7 +1081,7 @@ class IntegrationManagerTestCase(TestCase):data = IntegrationData(integration_gateway=gateway, integration=integration)# Simulate a concurrent disable that lands BETWEEN the lock-free- # probe and the lock-acquired state mutation. test_connection's+ # probe and the lock-acquired state mutation. validate_access's# side_effect mutates the DB row to is_enabled=False right before# returning success, then resume_integration's inside-lock# refresh_from_db() picks that up.@@ -1025,7 +1090,7 @@ class IntegrationManagerTestCase(TestCase):integration.save()return ConnectionTestResult.success()- with patch.object(gateway, 'test_connection',+ with patch.object(gateway, 'validate_access',side_effect=disable_during_probe):with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:with self.assertRaises(IntegrationConnectionError) as context:diff --git a/src/hi/integrations/tests/test_integration_synchronizer.py b/src/hi/integrations/tests/test_integration_synchronizer.pyindex 307d0018..496b1f90 100644--- a/src/hi/integrations/tests/test_integration_synchronizer.py+++ b/src/hi/integrations/tests/test_integration_synchronizer.py@@ -27,8 +27,8 @@ from hi.apps.entity.models import Entity, EntityAttribute, EntityStatefrom hi.apps.event.models import EventClause, EventDefinitionfrom hi.apps.sense.models import Sensorfrom hi.apps.control.models import Controller-from hi.integrations.integration_synchronizer import IntegrationSynchronizer-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -51,12 +51,12 @@ class TestSynchronizer(IntegrationSynchronizer):def get_integration_metadata(self):return _stub_integration_metadata()- def get_result_title(self, is_initial_import=False):+ def get_result_title(self, is_initial_connect=False):return 'Test Sync Result'- def _sync_impl(self, is_initial_import=False):+ def _sync_impl(self, is_initial_connect=False):return IntegrationSyncResult(- title=self.get_result_title(is_initial_import=is_initial_import),+ title=self.get_result_title(is_initial_connect=is_initial_connect),)@@ -1410,7 +1410,7 @@ class IntegrationSynchronizerReconnectCycleTests(TestCase):``_rebuild_integration_components`` override mirrors what areal integration converter does: set integration_key on theexisting entity and save."""- from hi.integrations.entity_operations import EntityIntegrationOperations+ from hi.integrations.connect.entity_operations import EntityIntegrationOperationsfrom hi.integrations.transient_models import IntegrationKeyintegration_id = self.INTEGRATION_ID@@ -1531,7 +1531,7 @@ class IntegrationSynchronizerReconnectCycleTests(TestCase):with user data via the same code path as sync-timepreservation, so reconnect must work for those too. Pinnedin the corrected #281 issue's edge-cases section."""- from hi.integrations.entity_operations import EntityIntegrationOperations+ from hi.integrations.connect.entity_operations import EntityIntegrationOperationssynchronizer = self._build_synchronizer()result = IntegrationSyncResult(title='Disable Cycle')diff --git a/src/hi/integrations/tests/test_placement_form.py b/src/hi/integrations/tests/test_placement_form.pyindex 7db55c88..fb581e77 100644--- a/src/hi/integrations/tests/test_placement_form.py+++ b/src/hi/integrations/tests/test_placement_form.py@@ -13,7 +13,7 @@ from django.test import TestCasefrom hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationView-from hi.integrations.placement_request import PlacementFormParser+from hi.integrations.connect.placement_request import PlacementFormParserlogging.disable(logging.CRITICAL)@@ -252,7 +252,7 @@ class PlacementFormParserTests(TestCase):# state. The patched return is the test's existing Location;# the parser then creates a real LocationView attached to it.with patch(- 'hi.integrations.placement_request.LocationManager',+ 'hi.integrations.connect.placement_request.LocationManager',) as mock_manager_cls:instance = mock_manager_cls.return_valueinstance.get_default_location.return_value = self.locationdiff --git a/src/hi/integrations/tests/test_placement_request.py b/src/hi/integrations/tests/test_placement_request.pyindex d1fac3c4..fba9b92b 100644--- a/src/hi/integrations/tests/test_placement_request.py+++ b/src/hi/integrations/tests/test_placement_request.py@@ -14,7 +14,7 @@ from django.core.exceptions import BadRequestfrom django.http import QueryDictfrom django.test import SimpleTestCase-from hi.integrations.placement_request import PlacementUrlParams+from hi.integrations.connect.placement_request import PlacementUrlParamslogging.disable(logging.CRITICAL)@@ -24,15 +24,15 @@ class PlacementUrlParamsToQueryDictTests(SimpleTestCase):def test_defaults_produce_empty_dict(self):"""Sparse encoding: a default-constructed params objectcontributes no query keys. Keeps URLs free of redundant- ``?is_initial_import=0`` cruft."""+ ``?is_initial_connect=0`` cruft."""params = PlacementUrlParams()self.assertEqual(params.to_query_dict(), {})- def test_is_initial_import_only_emits_its_key(self):- params = PlacementUrlParams(is_initial_import=True)+ def test_is_initial_connect_only_emits_its_key(self):+ params = PlacementUrlParams(is_initial_connect=True)self.assertEqual(params.to_query_dict(),- {PlacementUrlParams.KEY_IS_INITIAL_IMPORT: PlacementUrlParams.TRUE_VALUE},+ {PlacementUrlParams.KEY_IS_INITIAL_CONNECT: PlacementUrlParams.TRUE_VALUE},)def test_entity_ids_only_emits_its_key(self):@@ -43,11 +43,11 @@ class PlacementUrlParamsToQueryDictTests(SimpleTestCase):)def test_both_fields_populated(self):- params = PlacementUrlParams(is_initial_import=True, entity_ids=[7, 8])+ params = PlacementUrlParams(is_initial_connect=True, entity_ids=[7, 8])self.assertEqual(params.to_query_dict(),{- PlacementUrlParams.KEY_IS_INITIAL_IMPORT: PlacementUrlParams.TRUE_VALUE,+ PlacementUrlParams.KEY_IS_INITIAL_CONNECT: PlacementUrlParams.TRUE_VALUE,PlacementUrlParams.KEY_ENTITY_IDS: '7,8',},)@@ -66,10 +66,10 @@ class PlacementUrlParamsAppendToUrlTests(SimpleTestCase):"""Goes through ``django.utils.http.urlencode`` so thecomma in ``entity_ids`` is encoded to %2C — protects againstany future field whose value contains URL-reserved chars."""- params = PlacementUrlParams(is_initial_import=True, entity_ids=[1, 2])+ params = PlacementUrlParams(is_initial_connect=True, entity_ids=[1, 2])url = params.append_to_url('/placement/test')self.assertTrue(url.startswith('/placement/test?'))- self.assertIn('is_initial_import=1', url)+ self.assertIn('is_initial_connect=1', url)# Comma is URL-encoded by urlencode.self.assertIn('entity_ids=1%2C2', url)@@ -84,29 +84,29 @@ class PlacementUrlParamsFromDataTests(SimpleTestCase):"""The contract guarantee: ``to_query_dict`` →``QueryDict`` → ``from_data`` reconstructs an equivalentparams object. Any encoder/decoder asymmetry breaks this."""- original = PlacementUrlParams(is_initial_import=True, entity_ids=[3, 1, 4])+ original = PlacementUrlParams(is_initial_connect=True, entity_ids=[3, 1, 4])qd = QueryDict(mutable=True)for k, v in original.to_query_dict().items():qd[k] = vroundtripped = PlacementUrlParams.from_data(qd)self.assertEqual(original, roundtripped)- def test_is_initial_import_accepts_robust_truthy_spellings(self):+ def test_is_initial_connect_accepts_robust_truthy_spellings(self):"""``str_to_bool`` accepts '1', 'true', 'yes', etc. so ahand-crafted URL or a future encoding change on the producerside doesn't silently parse as False."""for truthy in ('1', 'true', 'TRUE', 'yes', 'on'):with self.subTest(value=truthy):- qd = QueryDict(f'is_initial_import={truthy}')- self.assertTrue(PlacementUrlParams.from_data(qd).is_initial_import)+ qd = QueryDict(f'is_initial_connect={truthy}')+ self.assertTrue(PlacementUrlParams.from_data(qd).is_initial_connect)- def test_is_initial_import_falsy_values(self):+ def test_is_initial_connect_falsy_values(self):"""Anything not-truthy parses as False, including thecanonical FALSE_VALUE encoding and absence."""for falsy in ('0', 'false', 'no', '', 'garbage'):with self.subTest(value=falsy):- qd = QueryDict(f'is_initial_import={falsy}')- self.assertFalse(PlacementUrlParams.from_data(qd).is_initial_import)+ qd = QueryDict(f'is_initial_connect={falsy}')+ self.assertFalse(PlacementUrlParams.from_data(qd).is_initial_connect)def test_entity_ids_parses_comma_separated_integers(self):qd = QueryDict('entity_ids=10,20,30')@@ -130,23 +130,23 @@ class PlacementUrlParamsFromDataTests(SimpleTestCase):PlacementUrlParams.from_data(qd)def test_entity_ids_absent_returns_empty_list(self):- qd = QueryDict('is_initial_import=1')+ qd = QueryDict('is_initial_connect=1')result = PlacementUrlParams.from_data(qd)self.assertEqual(result.entity_ids, [])class PlacementUrlParamsFormValueTests(SimpleTestCase):- def test_is_initial_import_form_value_true_returns_true_value(self):- params = PlacementUrlParams(is_initial_import=True)+ def test_is_initial_connect_form_value_true_returns_true_value(self):+ params = PlacementUrlParams(is_initial_connect=True)self.assertEqual(- params.is_initial_import_form_value(),+ params.is_initial_connect_form_value(),PlacementUrlParams.TRUE_VALUE,)- def test_is_initial_import_form_value_false_returns_false_value(self):- params = PlacementUrlParams(is_initial_import=False)+ def test_is_initial_connect_form_value_false_returns_false_value(self):+ params = PlacementUrlParams(is_initial_connect=False)self.assertEqual(- params.is_initial_import_form_value(),+ params.is_initial_connect_form_value(),PlacementUrlParams.FALSE_VALUE,)diff --git a/src/hi/integrations/tests/test_sync_check.py b/src/hi/integrations/tests/test_sync_check.pyindex bfffdf02..1fa761b7 100644--- a/src/hi/integrations/tests/test_sync_check.py+++ b/src/hi/integrations/tests/test_sync_check.py@@ -15,13 +15,13 @@ from unittest.mock import Mock, patchfrom django.core.cache import cachefrom django.test import TestCase-from hi.integrations.sync_check import (+from hi.integrations.connect.sync_check import (IntegrationSyncCheck,SyncCheckOutcome,SyncCheckResult,SyncDelta,)-from hi.integrations.monitors import IntegrationSyncCheckMonitor+from hi.integrations.connect.monitors import IntegrationSyncCheckMonitorfrom hi.integrations.transient_models import IntegrationKey@@ -131,10 +131,11 @@ class BuildResultAndSummaryTests(TestCase):integration_label='Home Assistant',)self.assertIn('3 new items upstream', result.summary_message)- # The Refresh call-to-action is intentionally NOT in the- # summary string — it is rendered as a real link by the+ # The update-check call-to-action is intentionally NOT in+ # the summary string — it is rendered as a real link by the# manage-page banner template.- self.assertNotIn('REFRESH', result.summary_message)+ self.assertNotIn('UPDATE', result.summary_message)+ self.assertNotIn('Update', result.summary_message)def test_singular_pluralization(self):result = IntegrationSyncCheck.build_result(@@ -232,6 +233,20 @@ class CacheHelperTests(TestCase):IntegrationSyncCheck.clear_state('')# No exceptions; nothing to assert beyond reaching here.+ def test_unreadable_cache_entry_is_evicted_and_returns_none(self):+ # A pickled entry written before a class rename / module move+ # will fail to deserialize on read. The defensive guard in+ # get_state must catch, evict the bad key, and degrade to a+ # cache miss rather than propagate the exception.+ cache_key = IntegrationSyncCheck._cache_key(self.INTEGRATION_A)+ with patch.object(cache, 'get', side_effect=ModuleNotFoundError(+ "No module named 'hi.integrations.old_path'")):+ with patch.object(cache, 'delete') as mock_delete:+ self.assertIsNone(+ IntegrationSyncCheck.get_state(self.INTEGRATION_A),+ )+ mock_delete.assert_called_once_with(cache_key)+def test_record_sync_complete_writes_zero_delta_with_timestamp(self):# Pre-populate a stale "needs sync" state.IntegrationSyncCheck.set_state(@@ -643,7 +658,7 @@ class IntegrationSynchronizerPostSyncHookTests(TestCase):returns the given result. We test sync() (the public entrypoint) so the post-hook fires the same way it does inproduction."""- from hi.integrations.integration_synchronizer import IntegrationSynchronizer+ from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizerfrom hi.integrations.transient_models import IntegrationMetaDataclass _TestSynchronizer(IntegrationSynchronizer):@@ -657,13 +672,13 @@ class IntegrationSynchronizerPostSyncHookTests(TestCase):allow_entity_deletion=True,)- def _sync_impl(self, is_initial_import):+ def _sync_impl(self, is_initial_connect):return sync_impl_resultreturn _TestSynchronizer()def test_successful_sync_records_zero_delta_completion(self):- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResult# Pre-populate a stale "needs sync" state.IntegrationSyncCheck.set_state(@@ -674,17 +689,17 @@ class IntegrationSynchronizerPostSyncHookTests(TestCase):),)synchronizer = self._make_synchronizer(- sync_impl_result=IntegrationSyncResult(title='Refresh Result'),+ sync_impl_result=IntegrationSyncResult(title='Update Check Result'),)- synchronizer.sync(is_initial_import=False)+ synchronizer.sync(is_initial_connect=False)loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_ID)self.assertIsNotNone(loaded)self.assertFalse(loaded.needs_sync)def test_failed_sync_leaves_cache_alone(self):- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResult# Pre-populate a stale needs-sync state.stale = IntegrationSyncCheck.build_result(@@ -697,12 +712,12 @@ class IntegrationSynchronizerPostSyncHookTests(TestCase):)synchronizer = self._make_synchronizer(sync_impl_result=IntegrationSyncResult(- title='Refresh Result',+ title='Update Check Result',error_list=['something went wrong'],),)- synchronizer.sync(is_initial_import=False)+ synchronizer.sync(is_initial_connect=False)loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_ID)self.assertIsNotNone(loaded)diff --git a/src/hi/integrations/tests/test_sync_result.py b/src/hi/integrations/tests/test_sync_result.pyindex bd15905f..ef575b0a 100644--- a/src/hi/integrations/tests/test_sync_result.py+++ b/src/hi/integrations/tests/test_sync_result.py@@ -20,7 +20,7 @@ from hi.apps.entity.entity_placement import (EntityPlacementInput,EntityPlacementItem,)-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.sync_result import IntegrationSyncResultlogging.disable(logging.CRITICAL)diff --git a/src/hi/integrations/tests/test_transient_models.py b/src/hi/integrations/tests/test_transient_models.pyindex ff5a02ca..c9b55ada 100644--- a/src/hi/integrations/tests/test_transient_models.py+++ b/src/hi/integrations/tests/test_transient_models.py@@ -494,3 +494,13 @@ class IntegrationMetaDataTestCase(TestCase):# Test that attribute_type is a class (IntegrationAttributeType subclass)self.assertTrue(hasattr(metadata.attribute_type, '__bases__'))self.assertIn(IntegrationAttributeType, metadata.attribute_type.__bases__)++ def test_capabilities_empty_set_raises(self):+ with self.assertRaises(ValueError):+ IntegrationMetaData(+ integration_id='cap_empty',+ label='Cap Empty',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True,+ capabilities=frozenset(),+ )diff --git a/src/hi/integrations/tests/test_user_data_detector.py b/src/hi/integrations/tests/test_user_data_detector.pyindex 1a9d5ac6..1a240bc2 100644--- a/src/hi/integrations/tests/test_user_data_detector.py+++ b/src/hi/integrations/tests/test_user_data_detector.py@@ -11,7 +11,7 @@ from hi.apps.attribute.enums import AttributeTypefrom hi.apps.entity.models import Entity, EntityAttribute, EntityStatefrom hi.apps.sense.models import Sensorfrom hi.apps.control.models import Controller-from hi.integrations.user_data_detector import EntityUserDataDetector+from hi.integrations.connect.user_data_detector import EntityUserDataDetectorlogging.disable(logging.CRITICAL)diff --git a/src/hi/integrations/tests/test_view_mixins.py b/src/hi/integrations/tests/test_view_mixins.pyindex bc2f01e3..b02fb65a 100644--- a/src/hi/integrations/tests/test_view_mixins.py+++ b/src/hi/integrations/tests/test_view_mixins.py@@ -3,7 +3,7 @@ Tests for IntegrationViewMixin.validate_attributes_extra_helper, thetwo-stage save-time validation entry point.Stage 1: gateway.validate_configuration (schema-only, fast, offline)-Stage 2: gateway.test_connection (live probe, bounded timeout)+Stage 2: gateway.validate_access (live probe, bounded timeout)Both stages must surface their failure inline as a non-form error so theuser sees the cause without a silent save followed by a delayed background@@ -21,7 +21,7 @@ from hi.integrations.transient_models import (ConnectionTestResult,IntegrationValidationResult,)-from hi.integrations.view_mixins import IntegrationViewMixin+from hi.integrations.connect.view_mixins import IntegrationViewMixinlogging.disable(logging.CRITICAL)@@ -63,7 +63,7 @@ class ValidateAttributesExtraHelperTest(SimpleTestCase):gateway.validate_configuration.return_value = (IntegrationValidationResult.success())- gateway.test_connection.return_value = ConnectionTestResult.success()+ gateway.validate_access.return_value = ConnectionTestResult.success()formset = _build_formset([{'value': 'token'}])ctx = _build_attr_item_context(gateway)@@ -76,8 +76,8 @@ class ValidateAttributesExtraHelperTest(SimpleTestCase):self.assertEqual(formset._non_form_errors, [])gateway.validate_configuration.assert_called_once()- gateway.test_connection.assert_called_once()- kwargs = gateway.test_connection.call_args.kwargs+ gateway.validate_access.assert_called_once()+ kwargs = gateway.validate_access.call_args.kwargsself.assertEqual(kwargs['timeout_secs'],IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS)@@ -100,7 +100,7 @@ class ValidateAttributesExtraHelperTest(SimpleTestCase):error_title='Test',)- gateway.test_connection.assert_not_called()+ gateway.validate_access.assert_not_called()self.assertEqual(len(formset._non_form_errors), 1)self.assertIn('Missing API URL', formset._non_form_errors[0])@@ -110,7 +110,7 @@ class ValidateAttributesExtraHelperTest(SimpleTestCase):gateway.validate_configuration.return_value = (IntegrationValidationResult.success())- gateway.test_connection.return_value = ConnectionTestResult.failure(+ gateway.validate_access.return_value = ConnectionTestResult.failure('Cannot connect to upstream')@@ -123,13 +123,13 @@ class ValidateAttributesExtraHelperTest(SimpleTestCase):error_title='Test',)- gateway.test_connection.assert_called_once()+ gateway.validate_access.assert_called_once()self.assertEqual(len(formset._non_form_errors), 1)self.assertIn('Cannot connect to upstream', formset._non_form_errors[0])def test_unexpected_gateway_exception_propagates(self):"""- validate_configuration / test_connection are required by their+ validate_configuration / validate_access are required by theircontracts to convert internal exceptions into result objects(IntegrationValidationResult.error / ConnectionTestResult.failure).If a gateway impl is buggy and throws anyway, the helper does NOTdiff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.pyindex e0fd5939..4d80d98d 100644--- a/src/hi/integrations/tests/test_views.py+++ b/src/hi/integrations/tests/test_views.py@@ -9,8 +9,8 @@ from django.urls import reversefrom hi.apps.attribute.enums import AttributeValueTypefrom hi.integrations.enums import IntegrationAttributeType, IntegrationDisableMode-from hi.integrations.integration_data import IntegrationData-from hi.integrations.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_data import IntegrationData+from hi.integrations.connect.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manager import IntegrationManagerfrom hi.integrations.models import Integrationfrom hi.integrations.transient_models import IntegrationMetaData@@ -203,15 +203,15 @@ class _SyncTestSynchronizer:self._description = descriptionself.sync_called = False- def get_description(self, is_initial_import):- self.last_is_initial_import = is_initial_import+ def get_description(self, is_initial_connect):+ self.last_is_initial_connect = is_initial_connectreturn self._description- def get_result_title(self, is_initial_import):+ def get_result_title(self, is_initial_connect):return 'Test Sync Result'- def sync(self, is_initial_import=False, preserve_user_data=True):- from hi.integrations.sync_result import IntegrationSyncResult+ def sync(self, is_initial_connect=False, preserve_user_data=True):+ from hi.integrations.connect.sync_result import IntegrationSyncResultself.sync_called = Trueself.last_preserve_user_data = preserve_user_datareturn IntegrationSyncResult(@@ -289,9 +289,9 @@ class _SyncIncapableGateway(IntegrationGateway):class PreSyncViewTests(SyncViewTestCase):"""Framework pre-sync confirmation modal. Renders the synchronizer- description plus IMPORT/REFRESH and (first-time only) REVIEW- CONFIG actions; 404s when the integration does not provide a- synchronizer.+ description plus CONNECT/Check-for-updates and (first-time only)+ REVIEW CONFIG actions; 404s when the integration does not provide+ a synchronizer."""INTEGRATION_ID = 'sync_view_test'@@ -339,32 +339,12 @@ class PreSyncViewTests(SyncViewTestCase):response = self.client.get(self._url())self.assertEqual(response.status_code, 404)- def test_review_config_action_present_on_initial_import(self):- """REVIEW CONFIG button is shown only on the first-time path.-- With no entities for this integration, is_initial_import=True- and the REVIEW CONFIG affordance must appear so the user can- return to the configure step.- """- response = self.client.get(self._url())- self.assertSuccessResponse(response)- self.assertIn('REVIEW CONFIG', response.content.decode())-- def test_review_config_action_absent_after_initial_import(self):- """REVIEW CONFIG is omitted on the manage-page entry path.-- With at least one entity already imported, is_initial_import- is False; the user came from the manage page and CANCEL takes- them back, so REVIEW CONFIG is unnecessary.- """- from hi.apps.entity.enums import EntityType- from hi.apps.entity.models import Entity- Entity.objects.create(- integration_id=self.INTEGRATION_ID,- integration_name='already_imported',- name='Already Imported',- entity_type_str=EntityType.default_value(),- )+ def test_review_config_action_never_rendered(self):+ """The first-time CONNECT path is collapsed into+ IntegrationEnableView (Phase 7); pre-sync is now only the+ update-check path. REVIEW CONFIG was an artifact of the+ first-time round-trip and must no longer render anywhere+ in this template."""response = self.client.get(self._url())self.assertSuccessResponse(response)self.assertNotIn('REVIEW CONFIG', response.content.decode())@@ -386,7 +366,7 @@ class PreSyncViewTests(SyncViewTestCase):response = self.client.get(self._url())self.assertSuccessResponse(response)body = response.content.decode()- self.assertIn('>REFRESH<', body.replace('\n', ''))+ self.assertIn('>UPDATE', body)self.assertNotIn('RETAIN MISSING', body)self.assertNotIn('REMOVE MISSING', body)@@ -491,21 +471,22 @@ class SyncViewTests(SyncViewTestCase):# ---------------------------------------------------------------------------class EnableViewReviewConfigTests(SyncViewTestCase):+class EnableViewTests(SyncViewTestCase):"""- IntegrationEnableView accepts both first-time Configure and Review- Config (post-enable). The button label switches with state, and- the post-enable GET no longer 400s.+ IntegrationEnableView: Phase 7 collapse. The view renders the+ config form with a CONNECT action button regardless of the+ integration's is_enabled state; the legacy review-mode round+ trip (UPDATE label + CONTINUE-to-pre-sync) is gone."""- INTEGRATION_ID = 'enable_review_view_test'+ INTEGRATION_ID = 'enable_view_test'def setUp(self):super().setUp()IntegrationManager().reset_for_testing()self.integration = Integration.objects.create(integration_id=self.INTEGRATION_ID,- is_enabled=True,+ is_enabled=False,is_paused=False,)self.gateway = _SyncCapableGateway(integration_id=self.INTEGRATION_ID)@@ -520,50 +501,65 @@ class EnableViewReviewConfigTests(SyncViewTestCase):kwargs={'integration_id': self.INTEGRATION_ID},)- def test_get_post_enable_does_not_400(self):- """Removed is_enabled BadRequest: GET on an enabled integration- must return 200 so Review Config can re-render the form."""- response = self.client.get(self._url())- self.assertSuccessResponse(response)-- def test_get_post_enable_renders_update_button_label(self):- """Review-mode GET uses 'UPDATE' as the action label, not 'CONFIGURE'."""+ def test_get_renders_connect_action_label(self):+ # Asserts the visible action label is CONNECT. Internal CSS / HTML+ # comment text in shared attribute-form components may include+ # the substrings 'update'/'UPDATE'; this test pins the visible+ # button text without false positives on framework boilerplate.response = self.client.get(self._url())self.assertSuccessResponse(response)body = response.content.decode()- self.assertIn('UPDATE', body)+ self.assertIn('>\n CONNECT\n </button>', body)self.assertNotIn('CONFIGURE', body)+ self.assertNotIn('CONTINUE', body)- def test_get_post_enable_renders_continue_action(self):- """Review-mode GET replaces the dismiss CANCEL with a CONTINUE- action that returns to the pre-sync modal. Without this swap a- user reviewing config with no changes has only SAVE (which- re-saves) or CANCEL (which aborts the whole sync flow) — both- wrong for the read-only review path."""- response = self.client.get(self._url())- self.assertSuccessResponse(response)- body = response.content.decode()- self.assertIn('CONTINUE', body)- # Cancel button has id="hi-modal-cancel"; its absence in review- # mode is what we're pinning here.- self.assertNotIn('hi-modal-cancel', body)- # The CONTINUE action must point at the pre-sync URL.- self.assertIn(- reverse('integrations_pre_sync', kwargs={'integration_id': self.INTEGRATION_ID}),- body,- )-- def test_get_first_time_renders_configure_button_label(self):- """First-time GET (is_enabled=False) keeps the original- 'CONFIGURE' label and the dismiss CANCEL."""- self.integration.is_enabled = False+ def test_get_works_when_already_enabled(self):+ self.integration.is_enabled = Trueself.integration.save()response = self.client.get(self._url())self.assertSuccessResponse(response)body = response.content.decode()- self.assertIn('CONFIGURE', body)+ self.assertIn('CONNECT', body)self.assertIn('hi-modal-cancel', body)- self.assertNotIn('CONTINUE', body)++ def test_post_enables_and_runs_sync_when_synchronizer_exists(self):+ # Phase 7 collapse: a successful CONNECT POST enables the+ # integration and immediately invokes the synchronizer. The+ # attribute-form processing is short-circuited via patch since+ # the formset plumbing has its own coverage; the new wiring+ # under test is the enable → sync chain plus the sync-result+ # modal render.+ from django.http import HttpResponse+ from hi.integrations.connect.views import IntegrationEnableView+ with patch.object(+ IntegrationEnableView, 'post_attribute_form',+ return_value=HttpResponse(status=200),+ ):+ response = self.client.post(self._url(), {})+ self.assertSuccessResponse(response)+ self.integration.refresh_from_db()+ self.assertTrue(self.integration.is_enabled)+ self.assertTrue(self.gateway._synchronizer.sync_called)+ self.assertIn('sync-result', response.content.decode().lower())++ def test_post_skips_sync_when_synchronizer_absent(self):+ # Synchronizer-less integrations enable and return the legacy+ # redirect path instead of routing through sync.+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(+ integration_gateway=_SyncIncapableGateway(self.INTEGRATION_ID),+ integration=self.integration,+ )+ from django.http import HttpResponse+ from hi.integrations.connect.views import IntegrationEnableView+ with patch.object(+ IntegrationEnableView, 'post_attribute_form',+ return_value=HttpResponse(status=200),+ ):+ response = self.client.post(self._url(), {})+ self.integration.refresh_from_db()+ self.assertTrue(self.integration.is_enabled)+ # No synchronizer → no sync_result modal in the response body.+ self.assertNotIn('sync-result', response.content.decode().lower())# --------------------------------------------------------------------------@@ -582,13 +578,13 @@ class _PlacementTestSynchronizer:self._sync_result = sync_resultself.sync_called = False- def get_description(self, is_initial_import):+ def get_description(self, is_initial_connect):return None- def get_result_title(self, is_initial_import):+ def get_result_title(self, is_initial_connect):return 'Placement Test'- def sync(self, is_initial_import=False, preserve_user_data=True):+ def sync(self, is_initial_connect=False, preserve_user_data=True):self.sync_called = Trueself.last_preserve_user_data = preserve_user_datareturn self._sync_result@@ -643,7 +639,7 @@ class PlacementFlowTests(SyncViewTestCase):from hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationView- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResultself.integration = Integration.objects.create(integration_id=self.INTEGRATION_ID,@@ -751,10 +747,10 @@ class PlacementFlowTests(SyncViewTestCase):self.assertSuccessResponse(response)body = response.content.decode()# Result-modal markers (NOT placement markers).- # Hero copy is is_initial_import-aware. Test setup leaves+ # Hero copy is is_initial_connect-aware. Test setup leaves# Entity rows in the DB so the sync view sees this as a- # Refresh, not an Initial Import.- self.assertIn('Refresh complete', body)+ # update check, not an Initial Connect.+ self.assertIn('Update check complete', body)self.assertIn('Place Later', body)self.assertIn('Place 4 new items', body)self.assertIn(self._placement_url(), body)@@ -767,7 +763,7 @@ class PlacementFlowTests(SyncViewTestCase):no 'Place items' CTA. Single centered OK is the only footeraction (matches the project's 'acknowledge info, dismiss'single-button convention)."""- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResultself.synchronizer._sync_result = IntegrationSyncResult(title='Empty')response = self.client.post(self._sync_url())self.assertSuccessResponse(response)@@ -781,7 +777,7 @@ class PlacementFlowTests(SyncViewTestCase):placement when there are also creates — every change kindis enumerated in the result modal even though the modalultimately routes the operator to placement."""- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResultself.synchronizer._sync_result = IntegrationSyncResult(title='Mixed Result',created_list=['Brand New Light'],@@ -967,7 +963,7 @@ class PlacementDismissAndShowTests(SyncViewTestCase):from hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationView- from hi.integrations.sync_result import IntegrationSyncResult+ from hi.integrations.connect.sync_result import IntegrationSyncResultself.integration = Integration.objects.create(integration_id=self.INTEGRATION_ID,@@ -1041,11 +1037,11 @@ class PlacementDismissAndShowTests(SyncViewTestCase):"""The placement form's NOT NOW button (action=dismiss)routes back to the same placement URL where the view'sPOST handler renders the confirmation modal. GO BACK links- to the placement GET with is_initial_import threaded+ to the placement GET with is_initial_connect threadedthrough."""response = self.client.post(self._placement_url(), {'action': 'dismiss',- 'is_initial_import': '1',+ 'is_initial_connect': '1',})self.assertSuccessResponse(response)body = response.content.decode()@@ -1053,8 +1049,8 @@ class PlacementDismissAndShowTests(SyncViewTestCase):self.assertIn('Items left unplaced', body)self.assertIn('GO BACK', body)self.assertIn('OK, PLACE LATER', body)- # GO BACK targets the placement GET with is_initial_import=1.- self.assertIn(self._placement_url() + '?is_initial_import=1', body)+ # GO BACK targets the placement GET with is_initial_connect=1.+ self.assertIn(self._placement_url() + '?is_initial_connect=1', body)def test_placement_get_renders_from_unplaced_entities(self):"""The GET placement queries entities for the integration@@ -1300,7 +1296,7 @@ class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):)def test_banner_renders_when_sync_check_reports_drift(self):- from hi.integrations.sync_check import (+ from hi.integrations.connect.sync_check import (IntegrationSyncCheck,SyncDelta,)@@ -1320,15 +1316,15 @@ class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):self.assertSuccessResponse(response)body = response.content.decode()self.assertIn('1 new item upstream', body)- # The "REFRESH" call-to-action is rendered as an inline- # anchor that links to the pre-sync modal, so the rendered- # HTML carries both the link text and the URL.+ # The "Update" call-to-action is rendered as an+ # inline anchor that links to the pre-sync modal, so the+ # rendered HTML carries both the link text and the URL.self.assertIn(reverse('integrations_pre_sync',kwargs={'integration_id': self.INTEGRATION_ID}),body,)- self.assertIn('>REFRESH</a>', body)+ self.assertIn('>Update</a>', body)def _refresh_link_url(self):return reverse(@@ -1349,7 +1345,7 @@ class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):def test_no_banner_when_in_sync(self):# Probe has run and confirmed in-sync (zero-delta); the# banner is gated on needs_sync, so it must not appear.- from hi.integrations.sync_check import IntegrationSyncCheck+ from hi.integrations.connect.sync_check import IntegrationSyncCheckIntegrationSyncCheck.record_sync_complete(integration_id=self.INTEGRATION_ID,integration_label='Sync View Test Integration',diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.pyindex 232252ff..4b32e802 100644--- a/src/hi/integrations/transient_models.py+++ b/src/hi/integrations/transient_models.py@@ -1,9 +1,9 @@from dataclasses import dataclassfrom datetime import datetime-from typing import Dict, List, Optional+from typing import Dict, FrozenSet, List, Optionalfrom hi.apps.system.enums import HealthStatusType-from .enums import IntegrationAttributeType+from .enums import IntegrationAttributeType, IntegrationCapability@dataclass@@ -15,6 +15,16 @@ class IntegrationMetaData:allow_entity_deletion : boolallow_internal_attributes : bool = Truelogo_static_path : str = 'img/integrations/default.svg'+ capabilities : FrozenSet[IntegrationCapability] = frozenset({+ IntegrationCapability.CONNECT,+ })++ def __post_init__(self):+ if not self.capabilities:+ raise ValueError(+ f"Integration '{self.integration_id}' must declare at "+ f"least one IntegrationCapability."+ )@dataclassdiff --git a/src/hi/integrations/urls.py b/src/hi/integrations/urls.pyindex ab71e87d..7f9a360c 100644--- a/src/hi/integrations/urls.py+++ b/src/hi/integrations/urls.py@@ -4,7 +4,7 @@ from django.urls import re_path, includefrom hi.apps.common.module_utils import import_module_safe-from . import views+from .connect import viewsurlpatterns = [diff --git a/src/hi/services/frigate/frigate_client.py b/src/hi/services/frigate/frigate_client.pyindex 39f43a9a..076d7e6a 100644--- a/src/hi/services/frigate/frigate_client.py+++ b/src/hi/services/frigate/frigate_client.py@@ -54,7 +54,7 @@ class FrigateClient:def base_url(self) -> str:return self._base_url- # ---- Reachability probe (used by test_connection) ------------------+ # ---- Reachability probe (used by validate_access) ------------------def ping(self) -> None:"""Lightweight reachability probe against ``/api/config``.@@ -62,7 +62,7 @@ class FrigateClient:Confirms the base URL points at a Frigate instance (or whateveris fronting it) and that the response is JSON-shaped — a 200with HTML usually means the URL is fronting the Frigate web UI- rather than the API, and we want ``test_connection`` to fail+ rather than the API, and we want ``validate_access`` to failat save time instead of letting the polling path JSONDecodelater. Returns ``None`` on success; raises ``ValueError`` witha diagnostic message on failure. Network errors propagate."""@@ -146,7 +146,7 @@ class FrigateClient:"""GET ``path`` against the configured base URL and returnparsed JSON. Status code, content-type, and JSON-parse errorsall raise ``ValueError`` with diagnostic messages that include- the path so monitor / test_connection paths can record what+ the path so monitor / validate_access paths can record whatfailed."""url = f'{self._base_url}{path}'response = get(diff --git a/src/hi/services/frigate/frigate_controller.py b/src/hi/services/frigate/frigate_controller.pyindex 7aa4c763..7454ef35 100644--- a/src/hi/services/frigate/frigate_controller.py+++ b/src/hi/services/frigate/frigate_controller.py@@ -1,6 +1,6 @@import logging-from hi.integrations.integration_controller import IntegrationController+from hi.integrations.connect.integration_controller import IntegrationControllerfrom hi.integrations.transient_models import (IntegrationControlResult,IntegrationDetails,diff --git a/src/hi/services/frigate/frigate_manage_view_pane.py b/src/hi/services/frigate/frigate_manage_view_pane.pyindex 4d037556..06a89e03 100644--- a/src/hi/services/frigate/frigate_manage_view_pane.py+++ b/src/hi/services/frigate/frigate_manage_view_pane.py@@ -1,7 +1,7 @@from typing import Dict-from hi.integrations.integration_data import IntegrationData-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_data import IntegrationData+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPaneclass FrigateManageViewPane( IntegrationManageViewPane ):diff --git a/src/hi/services/frigate/frigate_manager.py b/src/hi/services/frigate/frigate_manager.pyindex c8b816ad..9d2dc80d 100644--- a/src/hi/services/frigate/frigate_manager.py+++ b/src/hi/services/frigate/frigate_manager.py@@ -39,7 +39,7 @@ class FrigateManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusregistered listeners. Mirrors ``ZoneMinderManager`` in role.Scaffolding stub: ``_reload_implementation`` is a no-op,- ``test_connection`` returns a "not yet implemented" failure, and+ ``validate_access`` returns a "not yet implemented" failure, and``validate_configuration`` does the minimum schema check (BASE_URLmust be present). Filled out incrementally during feature work."""@@ -289,12 +289,12 @@ class FrigateManager( SingletonManager, AggregateHealthProvider, ApiHealthStatus)return IntegrationValidationResult.success()- def test_connection(+ def validate_access(self,integration_attributes : List[ IntegrationAttribute ],timeout_secs : Optional[ float ],) -> ConnectionTestResult:- """Live probe against the configured base URL.+ """Live access validation against the configured base URL.Builds a temporary ``FrigateClient`` from the proposedattributes and calls ``ping()``. Bounded by ``timeout_secs``@@ -308,7 +308,7 @@ class FrigateManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusexcept ValueError as e:return ConnectionTestResult.failure( str( e ) )except Exception as e:- logger.exception( f'Error building Frigate client for test_connection: {e}' )+ logger.exception( f'Error building Frigate client for validate_access: {e}' )return ConnectionTestResult.failure( f'Configuration error: {e}' )try:diff --git a/src/hi/services/frigate/frigate_sync.py b/src/hi/services/frigate/frigate_sync.pyindex c1c90bfc..67a90597 100644--- a/src/hi/services/frigate/frigate_sync.py+++ b/src/hi/services/frigate/frigate_sync.py@@ -13,9 +13,9 @@ from hi.apps.entity.entity_placement import (from hi.apps.entity.models import Entityfrom hi.apps.model_helper import HiModelHelper-from hi.integrations.integration_synchronizer import IntegrationSynchronizer-from hi.integrations.sync_check import IntegrationSyncCheck, SyncDelta-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom .frigate_manager import FrigateManager@@ -42,8 +42,8 @@ class FrigateSynchronizer( IntegrationSynchronizer, FrigateMixin ):def get_integration_metadata(self):return FrigateMetaData- def get_description(self, is_initial_import : bool) -> Optional[ str ]:- if is_initial_import:+ def get_description(self, is_initial_connect : bool) -> Optional[ str ]:+ if is_initial_connect:return ('Each Frigate camera becomes a HI camera entity with'' motion and object-presence sensors.'@@ -95,9 +95,9 @@ class FrigateSynchronizer( IntegrationSynchronizer, FrigateMixin ):).values_list( 'integration_id', 'integration_name' )}- def _sync_impl( self, is_initial_import : bool ) -> IntegrationSyncResult:+ def _sync_impl( self, is_initial_connect : bool ) -> IntegrationSyncResult:result = IntegrationSyncResult(- title = self.get_result_title( is_initial_import = is_initial_import ),+ title = self.get_result_title( is_initial_connect = is_initial_connect ),)frigate_manager = self.frigate_manager()if frigate_manager.frigate_client is None:diff --git a/src/hi/services/frigate/integration.py b/src/hi/services/frigate/integration.pyindex adf111d7..6a471f8e 100644--- a/src/hi/services/frigate/integration.py+++ b/src/hi/services/frigate/integration.py@@ -9,10 +9,10 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.system.enums import HealthStatusTypefrom hi.apps.system.health_status_provider import HealthStatusProvider-from hi.integrations.integration_controller import IntegrationController-from hi.integrations.integration_gateway import IntegrationGateway-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane-from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.integration_controller import IntegrationController+from hi.integrations.connect.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizerfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import (ConnectionTestResult,@@ -84,19 +84,19 @@ class FrigateGateway( IntegrationGateway, FrigateMixin ):error_message = f'Configuration validation failed: {e}',)- def test_connection(+ def validate_access(self,integration_attributes : List[ IntegrationAttribute ],timeout_secs : Optional[ float ],) -> ConnectionTestResult:try:- return FrigateManager().test_connection(+ return FrigateManager().validate_access(integration_attributes = integration_attributes,timeout_secs = timeout_secs,)except Exception as e:- logger.exception( f'Error in Frigate connection test: {e}' )- return ConnectionTestResult.failure( f'Connection test error: {e}' )+ logger.exception( f'Error in Frigate access validation: {e}' )+ return ConnectionTestResult.failure( f'Access validation error: {e}' )def get_entity_video_snapshot(self, entity : Entity) -> Optional[ VideoSnapshot ]:"""Live still-frame for the Frigate camera backing this entitydiff --git a/src/hi/services/frigate/tests/test_frigate_sync.py b/src/hi/services/frigate/tests/test_frigate_sync.pyindex aa7ff5e7..67a3b862 100644--- a/src/hi/services/frigate/tests/test_frigate_sync.py+++ b/src/hi/services/frigate/tests/test_frigate_sync.py@@ -48,8 +48,8 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_returns_error_when_client_missing(self):self.mock_manager.frigate_client = None- result = self.synchronizer._sync_impl( is_initial_import = True )- self.assertEqual( result.title, 'Import Result' )+ result = self.synchronizer._sync_impl( is_initial_connect = True )+ self.assertEqual( result.title, 'Connect Result' )self.assertEqual( len( result.error_list ), 1 )self.assertIn( 'integration disabled', result.error_list[0].lower() )self.assertEqual( Entity.objects.count(), 0 )@@ -61,7 +61,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):API), so OBJECT_PRESENCE subsumes the "is motion happening"signal and a separate MOVEMENT sensor would always mirror it."""self._set_upstream_cameras( [ 'front_yard' ] )- result = self.synchronizer._sync_impl( is_initial_import = True )+ result = self.synchronizer._sync_impl( is_initial_connect = True )entities = list( Entity.objects.filter(integration_id = FrigateMetaData.integration_id,@@ -105,12 +105,12 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_is_idempotent_for_existing_cameras(self):self._set_upstream_cameras( [ 'front_yard' ] )- first = self.synchronizer._sync_impl( is_initial_import = True )+ first = self.synchronizer._sync_impl( is_initial_connect = True )self.assertEqual( len( first.created_list ), 1 )# Second sync against the same upstream — no new entities,# no new sensors, and no error rows.- second = self.synchronizer._sync_impl( is_initial_import = False )+ second = self.synchronizer._sync_impl( is_initial_connect = False )self.assertEqual( second.created_list, [] )self.assertEqual( second.error_list, [] )self.assertEqual(@@ -127,7 +127,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_removes_entities_for_cameras_no_longer_present(self):self._set_upstream_cameras( [ 'front_yard', 'back_door' ] )- self.synchronizer._sync_impl( is_initial_import = True )+ self.synchronizer._sync_impl( is_initial_connect = True )self.assertEqual(Entity.objects.filter(integration_id = FrigateMetaData.integration_id,@@ -137,7 +137,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):# Drop 'back_door' upstream. Refresh sync should remove it.self._set_upstream_cameras( [ 'front_yard' ] )- result = self.synchronizer._sync_impl( is_initial_import = False )+ result = self.synchronizer._sync_impl( is_initial_connect = False )remaining_names = list( Entity.objects.filter(integration_id = FrigateMetaData.integration_id,@@ -147,7 +147,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_preserves_user_edited_name_on_update(self):self._set_upstream_cameras( [ 'front_yard' ] )- self.synchronizer._sync_impl( is_initial_import = True )+ self.synchronizer._sync_impl( is_initial_connect = True )entity = Entity.objects.get(integration_id = FrigateMetaData.integration_id,@@ -159,7 +159,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):entity.video_snapshot_stream_fps = Noneentity.save()- result = self.synchronizer._sync_impl( is_initial_import = False )+ result = self.synchronizer._sync_impl( is_initial_connect = False )entity.refresh_from_db()self.assertEqual( entity.name, 'Front Porch' )@@ -177,7 +177,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):Live View pane routes to the snapshot-as-stream branchinstead of the (broken) native-stream branch."""self._set_upstream_cameras( [ 'front_yard' ] )- self.synchronizer._sync_impl( is_initial_import = True )+ self.synchronizer._sync_impl( is_initial_connect = True )entity = Entity.objects.get(integration_id = FrigateMetaData.integration_id,@@ -185,7 +185,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):entity.has_video_stream = True # simulate the stale shapeentity.save( update_fields = [ 'has_video_stream' ] )- self.synchronizer._sync_impl( is_initial_import = False )+ self.synchronizer._sync_impl( is_initial_connect = False )entity.refresh_from_db()self.assertFalse( entity.has_video_stream )@@ -197,7 +197,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):( 'front_yard', { 'enabled': True, 'friendly_name': 'Front Yard' } ),( 'back_door', { 'enabled': True } ), # no friendly_name])- self.synchronizer._sync_impl( is_initial_import = True )+ self.synchronizer._sync_impl( is_initial_connect = True )names_by_key = dict( Entity.objects.filter(integration_id = FrigateMetaData.integration_id,@@ -208,7 +208,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_creates_multiple_camera_entities(self):self._set_upstream_cameras( [ 'front_yard', 'back_door', 'driveway' ] )- result = self.synchronizer._sync_impl( is_initial_import = True )+ result = self.synchronizer._sync_impl( is_initial_connect = True )names = set( Entity.objects.filter(integration_id = FrigateMetaData.integration_id,@@ -225,7 +225,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_skips_event_definition_when_alarm_events_disabled(self):# Default in setUp is should_add_alarm_events=False.self._set_upstream_cameras( [ 'front_yard' ] )- self.synchronizer._sync_impl( is_initial_import = True )+ self.synchronizer._sync_impl( is_initial_connect = True )self.assertEqual(EventDefinition.objects.filter(integration_id = FrigateMetaData.integration_id,@@ -236,7 +236,7 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_creates_event_definition_when_alarm_events_enabled(self):self.mock_manager.should_add_alarm_events = Trueself._set_upstream_cameras( [ 'front_yard' ] )- self.synchronizer._sync_impl( is_initial_import = True )+ self.synchronizer._sync_impl( is_initial_connect = True )event_definitions = list( EventDefinition.objects.filter(integration_id = FrigateMetaData.integration_id,@@ -262,8 +262,8 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):def test_sync_is_idempotent_for_event_definitions(self):self.mock_manager.should_add_alarm_events = Trueself._set_upstream_cameras( [ 'front_yard' ] )- self.synchronizer._sync_impl( is_initial_import = True )- self.synchronizer._sync_impl( is_initial_import = False )+ self.synchronizer._sync_impl( is_initial_connect = True )+ self.synchronizer._sync_impl( is_initial_connect = False )# Second sync against the same upstream — no new event# definitions; existing entity's update path doesn't# re-create the definition.diff --git a/src/hi/services/hass/hass_client.py b/src/hi/services/hass/hass_client.pyindex b1ff08b5..5626366b 100644--- a/src/hi/services/hass/hass_client.py+++ b/src/hi/services/hass/hass_client.py@@ -79,7 +79,7 @@ class HassClient:Also validates that the response body is JSON-shaped. A 200 withan HTML body means we are talking to something that is not theHASS API (misconfigured proxy, captive portal, wrong base URL),- and we want test_connection to fail at save time rather than+ and we want validate_access to fail at save time rather thanletting the runtime sync path JSONDecodeError later."""url = f'{self._api_base_url}/api/'diff --git a/src/hi/services/hass/hass_controller.py b/src/hi/services/hass/hass_controller.pyindex 79d298c1..991a711d 100644--- a/src/hi/services/hass/hass_controller.py+++ b/src/hi/services/hass/hass_controller.py@@ -1,6 +1,6 @@import logging-from hi.integrations.integration_controller import IntegrationController+from hi.integrations.connect.integration_controller import IntegrationControllerfrom hi.integrations.transient_models import IntegrationDetailsfrom hi.integrations.transient_models import IntegrationControlResultdiff --git a/src/hi/services/hass/hass_manage_view_pane.py b/src/hi/services/hass/hass_manage_view_pane.pyindex 51302a19..62bb037c 100644--- a/src/hi/services/hass/hass_manage_view_pane.py+++ b/src/hi/services/hass/hass_manage_view_pane.py@@ -1,7 +1,7 @@from typing import Dict-from hi.integrations.integration_data import IntegrationData-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_data import IntegrationData+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPaneclass HassManageViewPane( IntegrationManageViewPane ):diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.pyindex caca4dbe..6cc570bd 100644--- a/src/hi/services/hass/hass_manager.py+++ b/src/hi/services/hass/hass_manager.py@@ -273,7 +273,7 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusPro"""Schema-only validation. Confirms required attributes are presentand structurally usable. Does NOT touch the network — for live- connection probing, see test_connection().+ access validation, see validate_access()."""try:self._build_hass_attr_type_to_attribute_map(@@ -294,12 +294,12 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProerror_message=f'Configuration validation failed: {e}')- def test_connection(+ def validate_access(self,integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float]) -> ConnectionTestResult:"""- Live connection probe with bounded timeout. Builds a temporary+ Live access validation with bounded timeout. Builds a temporaryHassClient against the proposed attributes and exercises thelightweight `/api/` ping endpoint."""@@ -316,7 +316,7 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProif validation_result.is_valid:return ConnectionTestResult.success()return ConnectionTestResult.failure(- validation_result.error_message or 'Connection test failed'+ validation_result.error_message or 'Access validation failed')except IntegrationAttributeError as e:@@ -324,8 +324,8 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProexcept IntegrationError as e:return ConnectionTestResult.failure(str(e))except Exception as e:- logger.exception(f'Error in HASS connection test: {e}')- return ConnectionTestResult.failure(f'Connection test error: {e}')+ logger.exception(f'Error in HASS access validation: {e}')+ return ConnectionTestResult.failure(f'Access validation error: {e}')def _build_hass_attr_type_to_attribute_map(self,diff --git a/src/hi/services/hass/hass_sync.py b/src/hi/services/hass/hass_sync.pyindex cf36688c..85f4d6ae 100644--- a/src/hi/services/hass/hass_sync.py+++ b/src/hi/services/hass/hass_sync.py@@ -12,9 +12,9 @@ from hi.apps.entity.entity_placement import (EntityPlacementGroup,)-from hi.integrations.integration_synchronizer import IntegrationSynchronizer-from hi.integrations.sync_check import IntegrationSyncCheck, SyncDelta-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom .hass_converter import HassConverter@@ -30,8 +30,8 @@ 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:+ def get_description(self, is_initial_connect: bool) -> Optional[str]:+ if is_initial_connect:return 'Only items matching your Allowed Item Types setting will be imported.'return 'Only items matching your Allowed Item Types setting are compared.'@@ -92,10 +92,10 @@ class HassSynchronizer( IntegrationSynchronizer, HassMixin ):hass_manager.reload()return- def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:+ def _sync_impl( self, is_initial_connect: bool ) -> IntegrationSyncResult:hass_manager = self.hass_manager()result = IntegrationSyncResult(- title = self.get_result_title( is_initial_import = is_initial_import ),+ title = self.get_result_title( is_initial_connect = is_initial_connect ),)hass_client = hass_manager.hass_clientdiff --git a/src/hi/services/hass/integration.py b/src/hi/services/hass/integration.pyindex 24dccc2f..47730e1d 100644--- a/src/hi/services/hass/integration.py+++ b/src/hi/services/hass/integration.py@@ -6,10 +6,10 @@ from hi.apps.entity.transient_models import VideoSnapshotfrom hi.apps.system.enums import HealthStatusTypefrom hi.apps.system.health_status_provider import HealthStatusProvider-from hi.integrations.integration_controller import IntegrationController-from hi.integrations.integration_gateway import IntegrationGateway-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane-from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.integration_controller import IntegrationController+from hi.integrations.connect.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizerfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import (ConnectionTestResult,@@ -74,21 +74,21 @@ class HassGateway( IntegrationGateway ):error_message=f'Configuration validation failed: {e}')- def test_connection(+ def validate_access(self,integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float],) -> ConnectionTestResult:- """Live connection probe; delegates to HassManager."""+ """Live access validation probe; delegates to HassManager."""try:hass_manager = HassManager()- return hass_manager.test_connection(+ return hass_manager.validate_access(integration_attributes=integration_attributes,timeout_secs=timeout_secs,)except Exception as e:- logger.exception(f'Error in HASS connection test: {e}')- return ConnectionTestResult.failure(f'Connection test error: {e}')+ logger.exception(f'Error in HASS access validation: {e}')+ return ConnectionTestResult.failure(f'Access validation error: {e}')def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:if not entity.has_video_snapshot:diff --git a/src/hi/services/hass/tests/test_hass_client_factory.py b/src/hi/services/hass/tests/test_hass_client_factory.pyindex ce6073c4..cbcacb73 100644--- a/src/hi/services/hass/tests/test_hass_client_factory.py+++ b/src/hi/services/hass/tests/test_hass_client_factory.py@@ -124,7 +124,7 @@ class TestHassClientFactory(TestCase):Guards against the 'wrong base URL / misconfigured proxy' casewhere an upstream returns a friendly 200 HTML page. We want- test_connection to surface this at save time rather than letting+ validate_access to surface this at save time rather than lettingthe runtime sync path JSONDecodeError later."""mock_response = Mock()diff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.pyindex a646fb38..333c0ff0 100644--- a/src/hi/services/hass/tests/test_hass_converter_create.py+++ b/src/hi/services/hass/tests/test_hass_converter_create.py@@ -19,7 +19,7 @@ from hi.apps.attribute.enums import AttributeType, AttributeValueTypefrom hi.apps.entity.enums import EntityStateTypefrom hi.apps.entity.models import Entity, EntityAttribute, EntityStatefrom hi.apps.event.models import EventDefinition-from hi.integrations.entity_operations import EntityIntegrationOperations+from hi.integrations.connect.entity_operations import EntityIntegrationOperationsfrom hi.services.hass.hass_converter import HassConverterfrom hi.services.hass.hass_metadata import HassMetaDatafrom hi.services.hass.hass_models import HassDevicediff --git a/src/hi/services/hass/tests/test_hass_sync.py b/src/hi/services/hass/tests/test_hass_sync.pyindex ce371b2e..b6ea441d 100644--- a/src/hi/services/hass/tests/test_hass_sync.py+++ b/src/hi/services/hass/tests/test_hass_sync.py@@ -5,7 +5,7 @@ from unittest.mock import Mock, patchfrom django.test import TestCasefrom hi.apps.entity.models import Entity-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.hass.hass_sync import HassSynchronizer@@ -42,7 +42,7 @@ class TestHassSynchronizerSyncMethod(TestCase):def setUp(self):self.synchronizer = HassSynchronizer()- @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')+ @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')@patch.object(HassSynchronizer, '_sync_impl')def test_sync_handles_runtime_error(self, mock_sync_impl, mock_lock_context):"""Test sync method handles RuntimeError exceptions"""@@ -55,12 +55,12 @@ class TestHassSynchronizerSyncMethod(TestCase):mock_context.__exit__ = Mock(return_value=False)mock_lock_context.return_value = mock_context- result = self.synchronizer.sync(is_initial_import=True)+ result = self.synchronizer.sync(is_initial_connect=True)# Verify error handlingself.assertIn('Database connection failed', result.error_list[0])- @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')+ @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')@patch.object(HassSynchronizer, '_sync_impl')def test_sync_returns_error_result_on_exception(self, mock_sync_impl, mock_lock_context):"""Test sync method returns proper error result when _sync_impl raises exception"""@@ -73,7 +73,7 @@ class TestHassSynchronizerSyncMethod(TestCase):mock_context.__exit__ = Mock(return_value=False)mock_lock_context.return_value = mock_context- result = self.synchronizer.sync(is_initial_import=True)+ result = self.synchronizer.sync(is_initial_connect=True)# Verify actual error result structure and contentself.assertEqual(len(result.error_list), 1)@@ -167,7 +167,7 @@ class TestHassSynchronizerTransactionBehavior(TestCase):mock_atomic.return_value.__enter__ = Mock()mock_atomic.return_value.__exit__ = Mock()- result = self.synchronizer._sync_impl(is_initial_import=True)+ result = self.synchronizer._sync_impl(is_initial_connect=True)# Verify atomic transaction was used exactly oncemock_atomic.assert_called_once()@@ -201,7 +201,7 @@ class TestHassSynchronizerTransactionBehavior(TestCase):# Transaction should propagate the exception (allowing rollback)with self.assertRaises(Exception) as context:- self.synchronizer._sync_impl(is_initial_import=True)+ self.synchronizer._sync_impl(is_initial_connect=True)self.assertEqual(str(context.exception), "Entity creation failed")@@ -237,7 +237,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):mock_hass_manager.return_value = mock_managerwith self.assertRaises(Exception) as context:- self.synchronizer._sync_impl(is_initial_import=True)+ self.synchronizer._sync_impl(is_initial_connect=True)self.assertEqual(str(context.exception), "API connection failed")@@ -261,7 +261,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):mock_states_to_devices.side_effect = ValueError("Invalid state data format")with self.assertRaises(ValueError) as context:- self.synchronizer._sync_impl(is_initial_import=True)+ self.synchronizer._sync_impl(is_initial_connect=True)self.assertEqual(str(context.exception), "Invalid state data format")diff --git a/src/hi/services/homebox/connector/hb_connector.py b/src/hi/services/homebox/connector/hb_connector.pyindex 9e934876..0880ec49 100644--- a/src/hi/services/homebox/connector/hb_connector.py+++ b/src/hi/services/homebox/connector/hb_connector.py@@ -10,7 +10,7 @@ from urllib.parse import urljoinfrom django.urls import reversefrom hi.apps.entity.models import Entity-from hi.integrations.external_view_data import (+from hi.integrations.connect.external_view_data import (AttachmentRef,ExternalViewData,MinimalViewData,diff --git a/src/hi/services/homebox/connector/hb_entity_factory.py b/src/hi/services/homebox/connector/hb_entity_factory.pynew file mode 100644index 00000000..424743a4--- /dev/null+++ b/src/hi/services/homebox/connector/hb_entity_factory.py@@ -0,0 +1,83 @@+from typing import List, Optional+import logging++from django.db import transaction++from hi.apps.entity.models import Entity++from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.shared.hb_converter import HbConverter+from hi.services.homebox.shared.hb_models import HbItem++logger = logging.getLogger(__name__)+++class HbEntityFactory:+ """Builds and updates HI Entity rows from HomeBox upstream items."""++ @classmethod+ 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 = HbConverter.hb_item_to_integration_key( hb_item = hb_item )+ entity_payload = HbConverter.hb_item_to_entity_payload( hb_item = hb_item )++ if entity is None:+ entity = Entity(+ name = HbConverter.hb_item_to_entity_name( hb_item = hb_item ),+ entity_type_str = str( HbConverter.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.allow_internal_attributes = HbMetaData.allow_internal_attributes+ entity.save()++ return entity++ @classmethod+ def update_models_for_hb_item( cls, entity : Entity, hb_item ) -> List[str]:+ messages = list()++ with transaction.atomic():+ entity_name = HbConverter.hb_item_to_entity_name( hb_item = hb_item )+ if entity.name != entity_name:+ messages.append( f'Name changed for {entity}. Setting to "{entity_name}"' )+ entity.name = entity_name++ desired_entity_type = HbConverter.hb_item_to_entity_type( hb_item = hb_item )+ if entity.entity_type != desired_entity_type:+ messages.append( f'Entity type changed for {entity}. Setting to "{desired_entity_type}"' )+ entity.entity_type = desired_entity_type++ if entity.allow_internal_attributes != HbMetaData.allow_internal_attributes:+ messages.append( f'allow_internal_attributes changed for {entity}.' )+ entity.allow_internal_attributes = HbMetaData.allow_internal_attributes++ new_payload = HbConverter.hb_item_to_entity_payload( hb_item = hb_item )+ if entity.integration_payload != new_payload:+ entity.integration_payload = new_payload+ messages.append( f'Integration payload updated for {entity}.' )++ if messages:+ entity.save()++ return messagesdiff --git a/src/hi/services/homebox/importer/hb_sync.py b/src/hi/services/homebox/connector/hb_sync.pysimilarity index 51%rename from src/hi/services/homebox/importer/hb_sync.pyrename to src/hi/services/homebox/connector/hb_sync.pyindex 6302366a..9b5d8f5a 100644--- a/src/hi/services/homebox/importer/hb_sync.py+++ b/src/hi/services/homebox/connector/hb_sync.py@@ -4,18 +4,18 @@ from typing import Dict, List, Optionalfrom asgiref.sync import sync_to_asyncfrom django.db import transaction-from hi.apps.entity.models import Entity, EntityAttribute+from hi.apps.entity.models import Entity-from hi.integrations.integration_synchronizer import IntegrationSynchronizer-from hi.integrations.sync_check import IntegrationSyncCheck, SyncDelta-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.homebox.shared.hb_converter import HbConverterfrom hi.services.homebox.hb_metadata import HbMetaDatafrom hi.services.homebox.hb_mixins import HomeBoxMixinfrom hi.services.homebox.shared.hb_models import HbItem-from .hb_importer import HbImporter+from .hb_entity_factory import HbEntityFactorylogger = logging.getLogger(__name__)@@ -25,7 +25,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):def get_integration_metadata(self):return HbMetaData- def get_description(self, is_initial_import: bool) -> Optional[str]:+ def get_description(self, is_initial_connect: bool) -> Optional[str]:return ('HomeBox Labels and Locations are kept as metadata on ''each item, not as separate organizational concepts in HI.'@@ -82,10 +82,10 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):).values_list( 'integration_id', 'integration_name' )}- def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:+ def _sync_impl( self, is_initial_connect: bool ) -> IntegrationSyncResult:hb_manager = self.hb_manager()result = IntegrationSyncResult(- title = self.get_result_title( is_initial_import = is_initial_import ),+ title = self.get_result_title( is_initial_connect = is_initial_connect ),)if not hb_manager.hb_client:@@ -195,10 +195,10 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):entity : Entity,upstream : HbItem,result : IntegrationSyncResult ):- """Reconnect hook: dispatch to ``HbImporter`` with the existing+ """Reconnect hook: dispatch to ``HbEntityFactory`` with the existingentity so integration-owned components are repopulated on thepreviously-disconnected entity rather than creating a new one."""- HbImporter.create_models_for_hb_item(+ HbEntityFactory.create_models_for_hb_item(hb_item = upstream,entity = entity,)@@ -227,7 +227,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):def _create_entity( self,item : HbItem,result : IntegrationSyncResult ) -> Entity:- entity = HbImporter.create_models_for_hb_item( hb_item = item )+ entity = HbEntityFactory.create_models_for_hb_item( hb_item = item )result.created_list.append( entity.name )return entity@@ -238,7 +238,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):# update_models_for_hb_item returns a list of change# description strings — non-empty means at least one# operator-visible change was made.- change_messages = HbImporter.update_models_for_hb_item(+ change_messages = HbEntityFactory.update_models_for_hb_item(entity = entity, hb_item = item,)if change_messages and entity.name not in result.updated_list:@@ -250,206 +250,3 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):result : IntegrationSyncResult ):self._remove_entity_intelligently( entity, result )return-- def _sync_helper_entity_attributes( self,- entity: Entity,- hb_item: HbItem,- result: IntegrationSyncResult ):- attribute_message_list = list()-- integration_key_to_regular_field = dict()- hb_field_list = HbConverter.hb_item_to_attribute_field_list( hb_item = hb_item )- for order_id, hb_field in enumerate( hb_field_list ):- if not isinstance( hb_field, dict ):- continue-- integration_key = HbConverter.hb_field_to_integration_key( hb_field = hb_field )- if integration_key:- integration_key_to_regular_field[integration_key] = (hb_field, order_id)-- integration_key_to_attachment = dict()- attachment_list = HbConverter.hb_item_to_attachment_field_list( hb_item = hb_item )- field_count = len( hb_field_list )- for order_id, hb_attachment in enumerate( attachment_list, start = field_count ):- if not isinstance( hb_attachment, dict ):- continue-- integration_key = HbConverter.hb_attachment_to_integration_key( hb_attachment = hb_attachment )- if integration_key:- integration_key_to_attachment[integration_key] = ( hb_attachment, order_id )-- active_integration_keys = set(integration_key_to_regular_field.keys())- active_integration_keys.update(integration_key_to_attachment.keys())-- integration_key_to_attr = self._get_existing_hb_attributes(entity = entity)-- with transaction.atomic():-- for integration_key, field_data in integration_key_to_regular_field.items():- hb_field, order_id = field_data- attribute = integration_key_to_attr.get( integration_key )-- if attribute:- self._update_attribute(- attribute = attribute,- hb_field = hb_field,- order_id = order_id,- message_list = attribute_message_list,- updated_prefix = 'Field attribute updated',- )- else:- created_attribute = self._create_attribute(- entity = entity,- hb_field = hb_field,- order_id = order_id,- )- if created_attribute:- integration_key_to_attr[integration_key] = created_attribute- attribute_message_list.append(- f'Field attribute added: {created_attribute.name}'- )- continue-- for integration_key, hb_attachment_tuple in integration_key_to_attachment.items():- hb_attachment, order_id = hb_attachment_tuple- attribute = integration_key_to_attr.get( integration_key )-- if attribute:- self._update_attachment_attribute(- attribute = attribute,- hb_attachment = hb_attachment,- order_id = order_id,- message_list = attribute_message_list,- updated_prefix = 'Attachment attribute updated',- )- else:- created_attribute = self._create_attachment_attribute(- entity = entity,- hb_attachment = hb_attachment,- order_id = order_id,- )- if created_attribute:- integration_key_to_attr[integration_key] = created_attribute- attribute_message_list.append(- f'Attachment attribute added: {created_attribute.name}'- )- continue-- for field_key, attribute in list( integration_key_to_attr.items() ):- if attribute.entity_id != entity.id:- continue-- if field_key not in active_integration_keys:- self._remove_attribute( attribute = attribute, message_list = attribute_message_list )- del integration_key_to_attr[field_key]- continue-- # An attribute-level change still means this entity was- # modified by the sync. Mark it in updated_list (with dedup- # against the entity-level path above) so the operator- # sees the entity name. Skip the mark when this entity was- # just created — its attributes are new because the entity- # is new, not because of a refresh-time update. Per-attribute- # detail itself stays internal — entity-name granularity is- # the contract.- if (- attribute_message_list- and entity.name not in result.created_list- and entity.name not in result.updated_list- ):- result.updated_list.append( entity.name )- return-- def _get_existing_hb_attributes( self, entity: Entity ) -> Dict[ IntegrationKey, EntityAttribute ]:- integration_key_to_attribute = dict()-- queryset = entity.attributes.filter(- integration_key_str__isnull = False- ).exclude( integration_key_str = '' )-- for attribute in queryset:- try:- integration_key = IntegrationKey.from_string( attribute.integration_key_str )- except Exception:- logger.debug(- 'Ignoring entity attribute with invalid integration key: '- f'{attribute.integration_key_str}'- )- continue-- integration_key_to_attribute[integration_key] = attribute-- return integration_key_to_attribute-- def _create_attribute( self,- entity: Entity,- hb_field: dict,- order_id: int ) -> EntityAttribute:- return HbImporter.create_attribute_from_hb_field(- entity = entity,- hb_field = hb_field,- order_id = order_id,- )-- def _update_attribute( self,- attribute: EntityAttribute,- hb_field: dict,- order_id: int,- message_list: List[str],- updated_prefix: str ):- was_changed = HbImporter.update_attribute_from_hb_field(- attribute = attribute,- hb_field = hb_field,- order_id = order_id,- )- if was_changed:- message = (- f'{updated_prefix}: '- f'{HbConverter.hb_field_to_attribute_name( hb_field = hb_field )}'- )- message_list.append( message )- return-- def _remove_attribute( self,- attribute: EntityAttribute,- message_list: List[str] ):- # Hard-delete: these are integration-owned attributes (not- # editable by the user), so the SoftDeleteAttributeModel's- # default soft-delete + restore affordance doesn't apply.- # Soft-deleting would surface the row under "Deleted- # Attributes" with a restore button, and a restore creates- # an inconsistency between HI and the integration's source- # of truth.- old_name = attribute.name- attribute.delete( hard_delete = True )- message_list.append( f'Field attribute removed: {old_name}' )- return-- def _create_attachment_attribute( self,- entity: Entity,- hb_attachment: dict,- order_id: int ) -> EntityAttribute:- return HbImporter.create_attribute_from_hb_attachment(- entity = entity,- hb_attachment = hb_attachment,- order_id = order_id,- )-- def _update_attachment_attribute( self,- attribute: EntityAttribute,- hb_attachment: dict,- order_id: int,- message_list: List[str],- updated_prefix: str ):- was_changed = HbImporter.update_attribute_from_hb_attachment(- attribute = attribute,- hb_attachment = hb_attachment,- order_id = order_id,- )- if was_changed:- message = (- f'{updated_prefix}: '- f'{HbConverter.hb_attachment_to_attribute_name( hb_attachment = hb_attachment )}'- )- message_list.append( message )- returndiff --git a/src/hi/services/homebox/hb_controller.py b/src/hi/services/homebox/hb_controller.pyindex 81ff0eea..8c707a8a 100644--- a/src/hi/services/homebox/hb_controller.py+++ b/src/hi/services/homebox/hb_controller.py@@ -1,6 +1,6 @@import logging-from hi.integrations.integration_controller import IntegrationController+from hi.integrations.connect.integration_controller import IntegrationControllerfrom hi.integrations.transient_models import IntegrationDetailsfrom hi.integrations.transient_models import IntegrationControlResultdiff --git a/src/hi/services/homebox/hb_manage_view_pane.py b/src/hi/services/homebox/hb_manage_view_pane.pyindex 6d40dce5..99eb30f1 100644--- a/src/hi/services/homebox/hb_manage_view_pane.py+++ b/src/hi/services/homebox/hb_manage_view_pane.py@@ -1,7 +1,7 @@from typing import Dict-from hi.integrations.integration_data import IntegrationData-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_data import IntegrationData+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPaneclass HbManageViewPane( IntegrationManageViewPane ):diff --git a/src/hi/services/homebox/importer/hb_attribute_sync.py b/src/hi/services/homebox/importer/hb_attribute_sync.pynew file mode 100644index 00000000..65be2a55--- /dev/null+++ b/src/hi/services/homebox/importer/hb_attribute_sync.py@@ -0,0 +1,224 @@+"""Preserved attribute-sync code from the pre-#354 copy-on-sync+architecture. Dormant — no live caller. The HomeBox Importer in #358+will adapt these into the Importer protocol's run_import method.+"""+import logging+from typing import Dict, List++from django.db import transaction++from hi.apps.entity.models import Entity, EntityAttribute++from hi.integrations.connect.sync_result import IntegrationSyncResult+from hi.integrations.transient_models import IntegrationKey++from hi.services.homebox.shared.hb_converter import HbConverter+from hi.services.homebox.shared.hb_models import HbItem+from .hb_importer import HbImporter++logger = logging.getLogger(__name__)+++class HbAttributeSync:++ @classmethod+ def sync_entity_attributes( cls,+ entity: Entity,+ hb_item: HbItem,+ result: IntegrationSyncResult ):+ attribute_message_list = list()++ integration_key_to_regular_field = dict()+ hb_field_list = HbConverter.hb_item_to_attribute_field_list( hb_item = hb_item )+ for order_id, hb_field in enumerate( hb_field_list ):+ if not isinstance( hb_field, dict ):+ continue++ integration_key = HbConverter.hb_field_to_integration_key( hb_field = hb_field )+ if integration_key:+ integration_key_to_regular_field[integration_key] = (hb_field, order_id)++ integration_key_to_attachment = dict()+ attachment_list = HbConverter.hb_item_to_attachment_field_list( hb_item = hb_item )+ field_count = len( hb_field_list )+ for order_id, hb_attachment in enumerate( attachment_list, start = field_count ):+ if not isinstance( hb_attachment, dict ):+ continue++ integration_key = HbConverter.hb_attachment_to_integration_key( hb_attachment = hb_attachment )+ if integration_key:+ integration_key_to_attachment[integration_key] = ( hb_attachment, order_id )++ active_integration_keys = set(integration_key_to_regular_field.keys())+ active_integration_keys.update(integration_key_to_attachment.keys())++ integration_key_to_attr = cls.get_existing_hb_attributes( entity = entity )++ with transaction.atomic():++ for integration_key, field_data in integration_key_to_regular_field.items():+ hb_field, order_id = field_data+ attribute = integration_key_to_attr.get( integration_key )++ if attribute:+ cls.update_attribute(+ attribute = attribute,+ hb_field = hb_field,+ order_id = order_id,+ message_list = attribute_message_list,+ updated_prefix = 'Field attribute updated',+ )+ else:+ created_attribute = cls.create_attribute(+ entity = entity,+ hb_field = hb_field,+ order_id = order_id,+ )+ if created_attribute:+ integration_key_to_attr[integration_key] = created_attribute+ attribute_message_list.append(+ f'Field attribute added: {created_attribute.name}'+ )+ continue++ for integration_key, hb_attachment_tuple in integration_key_to_attachment.items():+ hb_attachment, order_id = hb_attachment_tuple+ attribute = integration_key_to_attr.get( integration_key )++ if attribute:+ cls.update_attachment_attribute(+ attribute = attribute,+ hb_attachment = hb_attachment,+ order_id = order_id,+ message_list = attribute_message_list,+ updated_prefix = 'Attachment attribute updated',+ )+ else:+ created_attribute = cls.create_attachment_attribute(+ entity = entity,+ hb_attachment = hb_attachment,+ order_id = order_id,+ )+ if created_attribute:+ integration_key_to_attr[integration_key] = created_attribute+ attribute_message_list.append(+ f'Attachment attribute added: {created_attribute.name}'+ )+ continue++ for field_key, attribute in list( integration_key_to_attr.items() ):+ if attribute.entity_id != entity.id:+ continue++ if field_key not in active_integration_keys:+ cls.remove_attribute( attribute = attribute, message_list = attribute_message_list )+ del integration_key_to_attr[field_key]+ continue++ if (+ attribute_message_list+ and entity.name not in result.created_list+ and entity.name not in result.updated_list+ ):+ result.updated_list.append( entity.name )+ return++ @classmethod+ def get_existing_hb_attributes( cls, entity: Entity ) -> Dict[ IntegrationKey, EntityAttribute ]:+ integration_key_to_attribute = dict()++ queryset = entity.attributes.filter(+ integration_key_str__isnull = False+ ).exclude( integration_key_str = '' )++ for attribute in queryset:+ try:+ integration_key = IntegrationKey.from_string( attribute.integration_key_str )+ except Exception:+ logger.debug(+ 'Ignoring entity attribute with invalid integration key: '+ f'{attribute.integration_key_str}'+ )+ continue++ integration_key_to_attribute[integration_key] = attribute++ return integration_key_to_attribute++ @classmethod+ def create_attribute( cls,+ entity: Entity,+ hb_field: dict,+ order_id: int ) -> EntityAttribute:+ return HbImporter.create_attribute_from_hb_field(+ entity = entity,+ hb_field = hb_field,+ order_id = order_id,+ )++ @classmethod+ def update_attribute( cls,+ attribute: EntityAttribute,+ hb_field: dict,+ order_id: int,+ message_list: List[str],+ updated_prefix: str ):+ was_changed = HbImporter.update_attribute_from_hb_field(+ attribute = attribute,+ hb_field = hb_field,+ order_id = order_id,+ )+ if was_changed:+ message = (+ f'{updated_prefix}: '+ f'{HbConverter.hb_field_to_attribute_name( hb_field = hb_field )}'+ )+ message_list.append( message )+ return++ @classmethod+ def remove_attribute( cls,+ attribute: EntityAttribute,+ message_list: List[str] ):+ # Hard-delete: these are integration-owned attributes (not+ # editable by the user), so the SoftDeleteAttributeModel's+ # default soft-delete + restore affordance doesn't apply.+ # Soft-deleting would surface the row under "Deleted+ # Attributes" with a restore button, and a restore creates+ # an inconsistency between HI and the integration's source+ # of truth.+ old_name = attribute.name+ attribute.delete( hard_delete = True )+ message_list.append( f'Field attribute removed: {old_name}' )+ return++ @classmethod+ def create_attachment_attribute( cls,+ entity: Entity,+ hb_attachment: dict,+ order_id: int ) -> EntityAttribute:+ return HbImporter.create_attribute_from_hb_attachment(+ entity = entity,+ hb_attachment = hb_attachment,+ order_id = order_id,+ )++ @classmethod+ def update_attachment_attribute( cls,+ attribute: EntityAttribute,+ hb_attachment: dict,+ order_id: int,+ message_list: List[str],+ updated_prefix: str ):+ was_changed = HbImporter.update_attribute_from_hb_attachment(+ attribute = attribute,+ hb_attachment = hb_attachment,+ order_id = order_id,+ )+ if was_changed:+ message = (+ f'{updated_prefix}: '+ f'{HbConverter.hb_attachment_to_attribute_name( hb_attachment = hb_attachment )}'+ )+ message_list.append( message )+ returndiff --git a/src/hi/services/homebox/importer/hb_importer.py b/src/hi/services/homebox/importer/hb_importer.pyindex 7aa7e5ec..f2b1d686 100644--- a/src/hi/services/homebox/importer/hb_importer.py+++ b/src/hi/services/homebox/importer/hb_importer.py@@ -1,86 +1,19 @@-from typing import Dict, List, Optional+"""HomeBox attribute-population classmethods. Dormant — these are+called only from the preserved attribute-sync helpers in+hb_attribute_sync.py. #358's Importer will exercise them via the+Importer protocol."""+from typing import Dict, Optionalimport logging-from django.db import transaction-from hi.apps.entity.models import Entity, EntityAttribute-from hi.services.homebox.hb_metadata import HbMetaDatafrom hi.services.homebox.shared.hb_converter import HbConverter-from hi.services.homebox.shared.hb_models import HbItemlogger = logging.getLogger(__name__)class HbImporter:- @classmethod- 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 = HbConverter.hb_item_to_integration_key( hb_item = hb_item )- entity_payload = HbConverter.hb_item_to_entity_payload( hb_item = hb_item )-- if entity is None:- entity = Entity(- name = HbConverter.hb_item_to_entity_name( hb_item = hb_item ),- entity_type_str = str( HbConverter.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.allow_internal_attributes = HbMetaData.allow_internal_attributes- entity.save()-- return entity-- @classmethod- def update_models_for_hb_item( cls, entity : Entity, hb_item ) -> List[str]:- messages = list()-- with transaction.atomic():- entity_name = HbConverter.hb_item_to_entity_name( hb_item = hb_item )- if entity.name != entity_name:- messages.append( f'Name changed for {entity}. Setting to "{entity_name}"' )- entity.name = entity_name-- desired_entity_type = HbConverter.hb_item_to_entity_type( hb_item = hb_item )- if entity.entity_type != desired_entity_type:- messages.append( f'Entity type changed for {entity}. Setting to "{desired_entity_type}"' )- entity.entity_type = desired_entity_type-- if entity.allow_internal_attributes != HbMetaData.allow_internal_attributes:- messages.append( f'allow_internal_attributes changed for {entity}.' )- entity.allow_internal_attributes = HbMetaData.allow_internal_attributes-- new_payload = HbConverter.hb_item_to_entity_payload( hb_item = hb_item )- if entity.integration_payload != new_payload:- entity.integration_payload = new_payload- messages.append( f'Integration payload updated for {entity}.' )-- if messages:- entity.save()-- return messages-@classmethoddef create_attribute_from_hb_field( cls,entity: Entity,diff --git a/src/hi/services/homebox/integration.py b/src/hi/services/homebox/integration.pyindex 4236b108..01b3a4e8 100644--- a/src/hi/services/homebox/integration.py+++ b/src/hi/services/homebox/integration.py@@ -5,11 +5,11 @@ from hi.apps.entity.models import Entityfrom hi.apps.system.enums import HealthStatusTypefrom hi.apps.system.health_status_provider import HealthStatusProvider-from hi.integrations.external_view_data import ExternalViewData-from hi.integrations.integration_controller import IntegrationController-from hi.integrations.integration_gateway import IntegrationGateway-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane-from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.external_view_data import ExternalViewData+from hi.integrations.connect.integration_controller import IntegrationController+from hi.integrations.connect.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizerfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import (ConnectionTestResult,@@ -22,7 +22,7 @@ from .hb_controller import HomeBoxControllerfrom .hb_manage_view_pane import HbManageViewPanefrom .shared.hb_manager import HomeBoxManagerfrom .hb_metadata import HbMetaData-from .importer.hb_sync import HomeBoxSynchronizer+from .connector.hb_sync import HomeBoxSynchronizerfrom .monitors import HomeBoxMonitorlogger = logging.getLogger(__name__)@@ -74,21 +74,21 @@ class HomeBoxGateway(IntegrationGateway):error_message=f'Configuration validation failed: {e}')- def test_connection(+ def validate_access(self,integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float],) -> ConnectionTestResult:- """Live connection probe; delegates to HomeBoxManager."""+ """Live access validation probe; delegates to HomeBoxManager."""try:hb_manager = HomeBoxManager()- return hb_manager.test_connection(+ return hb_manager.validate_access(integration_attributes = integration_attributes,timeout_secs = timeout_secs,)except Exception as e:- logger.exception(f'Error in HomeBox connection test: {e}')- return ConnectionTestResult.failure(f'Connection test error: {e}')+ logger.exception(f'Error in HomeBox access validation: {e}')+ return ConnectionTestResult.failure(f'Access validation error: {e}')def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:from .connector.hb_connector import HomeBoxConnectordiff --git a/src/hi/services/homebox/shared/hb_manager.py b/src/hi/services/homebox/shared/hb_manager.pyindex 28edafb3..33d34b2a 100644--- a/src/hi/services/homebox/shared/hb_manager.py+++ b/src/hi/services/homebox/shared/hb_manager.py@@ -227,7 +227,7 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatus"""Schema-only validation. Confirms required attributes are presentand structurally usable. Does NOT touch the network — for live- connection probing, see test_connection().+ access validation, see validate_access()."""try:self._build_hb_attr_type_to_attribute_map(@@ -248,12 +248,12 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatuserror_message=f'Configuration validation failed: {e}')- def test_connection(+ def validate_access(self,integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float]) -> ConnectionTestResult:"""- Live connection probe with bounded timeout. Builds a temporary+ Live access validation with bounded timeout. Builds a temporaryHbClient against the proposed attributes and exercises thelightweight items-summary endpoint."""@@ -270,7 +270,7 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusif validation_result.is_valid:return ConnectionTestResult.success()return ConnectionTestResult.failure(- validation_result.error_message or 'Connection test failed'+ validation_result.error_message or 'Access validation failed')except IntegrationAttributeError as e:@@ -278,8 +278,8 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusexcept IntegrationError as e:return ConnectionTestResult.failure(str(e))except Exception as e:- logger.exception(f'Error in HomeBox connection test: {e}')- return ConnectionTestResult.failure(f'Connection test error: {e}')+ logger.exception(f'Error in HomeBox access validation: {e}')+ return ConnectionTestResult.failure(f'Access validation error: {e}')def _build_hb_attr_type_to_attribute_map(self,diff --git a/src/hi/services/homebox/tests/test_hb_connector.py b/src/hi/services/homebox/tests/test_hb_connector.pyindex b9c23fdf..29b8d643 100644--- a/src/hi/services/homebox/tests/test_hb_connector.py+++ b/src/hi/services/homebox/tests/test_hb_connector.py@@ -13,7 +13,7 @@ from unittest.mock import Mock, patchfrom django.test import TestCasefrom hi.apps.entity.models import Entity-from hi.integrations.external_view_data import (+from hi.integrations.connect.external_view_data import (MinimalViewData,NameValuePair,StructuredViewData,diff --git a/src/hi/services/homebox/tests/test_hb_entity_factory.py b/src/hi/services/homebox/tests/test_hb_entity_factory.pynew file mode 100644index 00000000..63c05da0--- /dev/null+++ b/src/hi/services/homebox/tests/test_hb_entity_factory.py@@ -0,0 +1,101 @@+import logging+from unittest.mock import Mock++from django.test import TestCase++from hi.apps.entity.enums import EntityType+from hi.apps.entity.models import Entity+from hi.services.homebox.connector.hb_entity_factory import HbEntityFactory+from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.shared.hb_models import HbItem+++logging.disable(logging.CRITICAL)+++class TestHbEntityFactory(TestCase):++ def _mock_item(self, item_id='item-1', name='Item 1', description='desc', quantity=1):+ api_dict = {+ 'id': item_id,+ 'name': name,+ 'description': description,+ 'quantity': quantity,+ 'location': {'id': 'loc-1', 'name': 'Garage'},+ 'tags': [{'id': 'lab-1', 'name': 'Tools'}],+ 'fields': [],+ 'attachments': [],+ }++ client = Mock()+ client.download_attachment.return_value = None++ return HbItem(api_dict=api_dict, client=client)++ def test_create_models_for_hb_item_creates_entity(self):+ item = self._mock_item(item_id='item-create', name='Drill')++ entity = HbEntityFactory.create_models_for_hb_item(hb_item=item)++ self.assertIsInstance(entity, Entity)+ self.assertEqual(entity.integration_id, HbMetaData.integration_id)+ self.assertEqual(entity.integration_name, 'item-create')+ self.assertEqual(entity.name, 'Drill')+ self.assertEqual(entity.entity_type, EntityType.OTHER)+ self.assertFalse(entity.allow_internal_attributes)+ self.assertNotIn('description', entity.integration_payload)+ self.assertEqual(entity.integration_payload.get('location', {}).get('name'), 'Garage')+ self.assertEqual(entity.integration_payload.get('tags')[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 = HbEntityFactory.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',+ entity_type_str=str(EntityType.SERVICE),+ can_user_delete=False,+ allow_internal_attributes=True,+ integration_id=HbMetaData.integration_id,+ integration_name='item-update',+ integration_payload={'quantity': 1},+ )++ item = self._mock_item(item_id='item-update', name='New Name', description='new', quantity=3)++ messages = HbEntityFactory.update_models_for_hb_item(entity=entity, hb_item=item)++ self.assertTrue(messages)+ entity.refresh_from_db()+ self.assertEqual(entity.name, 'New Name')+ self.assertEqual(entity.entity_type, EntityType.OTHER)+ self.assertFalse(entity.allow_internal_attributes)+ self.assertNotIn('description', entity.integration_payload)+ self.assertEqual(entity.integration_payload.get('quantity'), 3)diff --git a/src/hi/services/homebox/tests/test_hb_importer.py b/src/hi/services/homebox/tests/test_hb_importer.pyindex 2b4f77d5..082208fe 100644--- a/src/hi/services/homebox/tests/test_hb_importer.py+++ b/src/hi/services/homebox/tests/test_hb_importer.py@@ -4,10 +4,8 @@ from unittest.mock import Mockfrom django.test import TestCasefrom hi.apps.attribute.enums import AttributeValueType-from hi.apps.entity.enums import EntityType-from hi.apps.entity.models import Entity+from hi.services.homebox.connector.hb_entity_factory import HbEntityFactoryfrom hi.services.homebox.importer.hb_importer import HbImporter-from hi.services.homebox.hb_metadata import HbMetaDatafrom hi.services.homebox.shared.hb_models import HbItem@@ -33,77 +31,9 @@ class TestHbImporter(TestCase):return HbItem(api_dict=api_dict, client=client)- def test_create_models_for_hb_item_creates_entity(self):- item = self._mock_item(item_id='item-create', name='Drill')-- entity = HbImporter.create_models_for_hb_item(hb_item=item)-- self.assertIsInstance(entity, Entity)- self.assertEqual(entity.integration_id, HbMetaData.integration_id)- self.assertEqual(entity.integration_name, 'item-create')- self.assertEqual(entity.name, 'Drill')- self.assertEqual(entity.entity_type, EntityType.OTHER)- self.assertFalse(entity.allow_internal_attributes)- self.assertNotIn('description', entity.integration_payload)- self.assertEqual(entity.integration_payload.get('location', {}).get('name'), 'Garage')- self.assertEqual(entity.integration_payload.get('tags')[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 = HbImporter.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',- entity_type_str=str(EntityType.SERVICE),- can_user_delete=False,- allow_internal_attributes=True,- integration_id=HbMetaData.integration_id,- integration_name='item-update',- integration_payload={'quantity': 1},- )-- item = self._mock_item(item_id='item-update', name='New Name', description='new', quantity=3)-- messages = HbImporter.update_models_for_hb_item(entity=entity, hb_item=item)-- self.assertTrue(messages)- entity.refresh_from_db()- self.assertEqual(entity.name, 'New Name')- self.assertEqual(entity.entity_type, EntityType.OTHER)- self.assertFalse(entity.allow_internal_attributes)- self.assertNotIn('description', entity.integration_payload)- self.assertEqual(entity.integration_payload.get('quantity'), 3)-def test_create_and_update_file_attribute_from_attachment(self):item = self._mock_item(item_id='item-file-sync')- entity = HbImporter.create_models_for_hb_item(hb_item=item)+ entity = HbEntityFactory.create_models_for_hb_item(hb_item=item)attachment = {'id': 'att-2',diff --git a/src/hi/services/homebox/tests/test_hb_sync.py b/src/hi/services/homebox/tests/test_hb_sync.pyindex 9e1dc15f..1e19e7d2 100644--- a/src/hi/services/homebox/tests/test_hb_sync.py+++ b/src/hi/services/homebox/tests/test_hb_sync.py@@ -1,14 +1,14 @@import loggingfrom contextlib import ExitStack, nullcontext-from unittest.mock import ANY, Mock, patch+from unittest.mock import Mock, patchfrom django.test import SimpleTestCasefrom hi.apps.entity.models import Entity-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.homebox.hb_metadata import HbMetaData-from hi.services.homebox.importer.hb_sync import HomeBoxSynchronizer+from hi.services.homebox.connector.hb_sync import HomeBoxSynchronizerfrom hi.testing.async_task_utils import AsyncTaskTestCase@@ -31,7 +31,7 @@ class TestHomeBoxSynchronizer(SimpleTestCase):with patch.object(synchronizer, 'hb_manager', return_value=manager), \patch.object(synchronizer, '_sync_helper_entities', return_value=[]) as sync_entities_mock:- result = synchronizer._sync_impl(is_initial_import=True)+ result = synchronizer._sync_impl(is_initial_connect=True)self.assertIsInstance(result, IntegrationSyncResult)self.assertIn('Found 3 current HomeBox items.', result.info_list)@@ -66,13 +66,13 @@ class TestHomeBoxSynchronizer(SimpleTestCase):with ExitStack() as stack:stack.enter_context(patch(- 'hi.services.homebox.importer.hb_sync.transaction.atomic',+ 'hi.services.homebox.connector.hb_sync.transaction.atomic',return_value=nullcontext(),))stack.enter_context(patch(- 'hi.services.homebox.importer.hb_sync.HbConverter.hb_item_to_integration_key',+ 'hi.services.homebox.connector.hb_sync.HbConverter.hb_item_to_integration_key',side_effect=key_from_item,))@@ -99,13 +99,6 @@ class TestHomeBoxSynchronizer(SimpleTestCase):remove_entity_mock = stack.enter_context(patch.object(synchronizer, '_remove_entity'))- # Connect-mode: _sync_helper_entity_attributes is no- # longer called during sync (HomeBox attributes are- # fetched live by the connector). Patch it anyway and- # assert it is NOT called, to pin the new contract.- 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@@ -132,170 +125,10 @@ class TestHomeBoxSynchronizer(SimpleTestCase):result=result,)- # Connect-mode contract: sync no longer creates/updates/- # removes EntityAttribute rows. The attribute-sync helper is- # not invoked by the Connect-mode sync flow.- self.assertEqual(sync_attrs_mock.call_count, 0)-self.assertIn('Found 2 existing HomeBox items.', result.info_list)self.assertTrue(any('Ignoring HomeBox item due to missing/invalid id' in messagefor message in result.error_list))- def test_sync_helper_entity_attributes_create_update_remove_fields_and_attachments(self):- synchronizer = HomeBoxSynchronizer()- result = IntegrationSyncResult(title='HomeBox Import Result')-- entity = Mock(name='entity')- entity.id = 10-- field_existing = {'id': 'field-existing', 'name': 'Field Existing'}- field_new = {'id': 'field-new', 'name': 'Field New'}- attachment_existing = {'id': 'attachment-existing', 'name': 'Attachment Existing'}- attachment_new = {'id': 'attachment-new', 'name': 'Attachment New'}-- field_existing_key = self._key('field:field-existing')- field_new_key = self._key('field:field-new')- attachment_existing_key = self._key('field:attachment-existing')- attachment_new_key = self._key('field:attachment-new')- stale_key = self._key('field:stale-field')- foreign_key = self._key('field:foreign-field')-- existing_field_attr = Mock(name='existing_field_attr')- existing_field_attr.entity_id = entity.id- existing_attachment_attr = Mock(name='existing_attachment_attr')- existing_attachment_attr.entity_id = entity.id- stale_attr = Mock(name='stale_attr')- stale_attr.entity_id = entity.id- stale_attr.name = 'Stale Field'- foreign_attr = Mock(name='foreign_attr')- foreign_attr.entity_id = entity.id + 1-- created_field_attr = Mock(name='created_field_attr')- created_field_attr.name = 'Field New'- created_attachment_attr = Mock(name='created_attachment_attr')- created_attachment_attr.name = 'Attachment New'-- field_key_by_id = {- 'field-existing': field_existing_key,- 'field-new': field_new_key,- }- attachment_key_by_id = {- 'attachment-existing': attachment_existing_key,- 'attachment-new': attachment_new_key,- }-- def field_key_from_field(hb_field):- return field_key_by_id.get(hb_field.get('id'))-- def attachment_key_from_attachment(hb_attachment):- return attachment_key_by_id.get(hb_attachment.get('id'))-- with ExitStack() as stack:- stack.enter_context(- patch(- 'hi.services.homebox.importer.hb_sync.transaction.atomic',- return_value=nullcontext(),- )- )- stack.enter_context(- patch(- 'hi.services.homebox.importer.hb_sync.HbConverter.hb_item_to_attribute_field_list',- return_value=[field_existing, field_new],- )- )- stack.enter_context(- patch(- 'hi.services.homebox.importer.hb_sync.HbConverter.hb_field_to_integration_key',- side_effect=field_key_from_field,- )- )- stack.enter_context(- patch(- 'hi.services.homebox.importer.hb_sync.HbConverter.hb_item_to_attachment_field_list',- return_value=[attachment_existing, attachment_new],- )- )- stack.enter_context(- patch(- 'hi.services.homebox.importer.hb_sync.HbConverter.hb_attachment_to_integration_key',- side_effect=attachment_key_from_attachment,- )- )- stack.enter_context(- patch.object(- synchronizer,- '_get_existing_hb_attributes',- return_value={- field_existing_key: existing_field_attr,- attachment_existing_key: existing_attachment_attr,- stale_key: stale_attr,- foreign_key: foreign_attr,- },- )- )- update_attr_mock = stack.enter_context(- patch.object(synchronizer, '_update_attribute')- )- create_attr_mock = stack.enter_context(- patch.object(- synchronizer,- '_create_attribute',- return_value=created_field_attr,- )- )- update_attachment_mock = stack.enter_context(- patch.object(synchronizer, '_update_attachment_attribute')- )- create_attachment_mock = stack.enter_context(- patch.object(- synchronizer,- '_create_attachment_attribute',- return_value=created_attachment_attr,- )- )-- synchronizer._sync_helper_entity_attributes(- entity=entity,- hb_item=Mock(),- result=result,- )-- update_attr_mock.assert_called_once_with(- attribute=existing_field_attr,- hb_field=field_existing,- order_id=0,- message_list=ANY,- updated_prefix='Field attribute updated',- )- create_attr_mock.assert_called_once_with(- entity=entity,- hb_field=field_new,- order_id=1,- )-- update_attachment_mock.assert_called_once_with(- attribute=existing_attachment_attr,- hb_attachment=attachment_existing,- order_id=2,- message_list=ANY,- updated_prefix='Attachment attribute updated',- )- create_attachment_mock.assert_called_once_with(- entity=entity,- hb_attachment=attachment_new,- order_id=3,- )-- stale_attr.delete.assert_called_once()- foreign_attr.delete.assert_not_called()-- # Per-attribute change detail is no longer surfaced in the- # sync result (counts at the entity level capture the- # operator-relevant signal). The persistence behavior above- # — created/updated/deleted attribute records — remains the- # contract this test pins.- self.assertEqual(result.info_list, [])-class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):"""Phase 2 grouping behavior: HomeBox has no domain notion of@@ -327,7 +160,7 @@ class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):with patch.object(synchronizer, 'hb_manager', return_value=manager), \patch.object(synchronizer, '_sync_helper_entities',return_value=[entity_a, entity_b]):- result = synchronizer._sync_impl(is_initial_import=True)+ result = synchronizer._sync_impl(is_initial_connect=True)self.assertIsNotNone(result.placement_input)self.assertEqual(result.placement_input.groups, [])@@ -351,7 +184,7 @@ class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):with patch.object(synchronizer, 'hb_manager', return_value=manager), \patch.object(synchronizer, '_sync_helper_entities', return_value=[]):- result = synchronizer._sync_impl(is_initial_import=True)+ result = synchronizer._sync_impl(is_initial_connect=True)# No newly-created entities → placement_input is None.self.assertIsNone(result.placement_input)@@ -362,7 +195,7 @@ class TestHomeBoxSynchronizerRebuildIntegrationComponents(SimpleTestCase):Issue #281: the per-integration ``_rebuild_integration_components``override is the only piece each synchronizer contributes to theframework-level reconnect path. This test verifies that- HomeBoxSynchronizer's override dispatches to ``HbConverter`` with+ HomeBoxSynchronizer's override dispatches to ``HbEntityFactory`` withthe existing-entity argument set. Framework-level behavior(find candidates, strip prefix, clear previous identity, updateentity map, info_list note) is covered by tests of@@ -377,7 +210,7 @@ class TestHomeBoxSynchronizerRebuildIntegrationComponents(SimpleTestCase):upstream = Mock(name='hb_item')with patch(- 'hi.services.homebox.importer.hb_sync.HbImporter.create_models_for_hb_item'+ 'hi.services.homebox.connector.hb_sync.HbEntityFactory.create_models_for_hb_item') as mock_converter:synchronizer._rebuild_integration_components(entity=existing_entity,diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.pyindex 8d3a27a0..33413319 100644--- a/src/hi/services/zoneminder/integration.py+++ b/src/hi/services/zoneminder/integration.py@@ -9,10 +9,10 @@ from hi.apps.sense.transient_models import SensorResponsefrom hi.apps.system.enums import HealthStatusTypefrom hi.apps.system.health_status_provider import HealthStatusProvider-from hi.integrations.integration_controller import IntegrationController-from hi.integrations.integration_gateway import IntegrationGateway-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane-from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.integration_controller import IntegrationController+from hi.integrations.connect.integration_gateway import IntegrationGateway+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizerfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import (ConnectionTestResult,@@ -80,21 +80,21 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):error_message=f'Configuration validation failed: {e}')- def test_connection(+ def validate_access(self,integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float],) -> ConnectionTestResult:- """Live connection probe; delegates to ZoneMinderManager."""+ """Live access validation probe; delegates to ZoneMinderManager."""try:zm_manager = ZoneMinderManager()- return zm_manager.test_connection(+ return zm_manager.validate_access(integration_attributes=integration_attributes,timeout_secs=timeout_secs,)except Exception as e:- logger.exception(f'Error in ZoneMinder connection test: {e}')- return ConnectionTestResult.failure(f'Connection test error: {e}')+ logger.exception(f'Error in ZoneMinder access validation: {e}')+ return ConnectionTestResult.failure(f'Access validation error: {e}')def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:"""Return a fresh still frame for the ZoneMinder monitor backingdiff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.pyindex 19385317..51ff7926 100644--- a/src/hi/services/zoneminder/tests/test_zm_sync.py+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py@@ -9,9 +9,9 @@ from hi.apps.entity.models import Entity, EntityAttributefrom hi.apps.event.models import EventDefinitionfrom hi.apps.sense.models import Sensor-from hi.integrations.entity_operations import EntityIntegrationOperations+from hi.integrations.connect.entity_operations import EntityIntegrationOperationsfrom hi.integrations.integration_manager import IntegrationManager-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.zoneminder.zm_sync import ZoneMinderSynchronizer@@ -26,7 +26,7 @@ class TestZoneMinderSynchronizerLockBehavior(TestCase):def setUp(self):self.synchronizer = ZoneMinderSynchronizer()- @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')+ @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')def test_sync_uses_exclusion_lock(self, mock_lock_context):"""Test sync method uses exclusion lock and returns sync results"""# Mock a successful lock context@@ -38,26 +38,26 @@ class TestZoneMinderSynchronizerLockBehavior(TestCase):mock_manager.zm_client = Noneself.synchronizer._zm_manager = mock_manager- result = self.synchronizer.sync(is_initial_import=True)+ result = self.synchronizer.sync(is_initial_connect=True)# Test lock usagemock_lock_context.assert_called_once_with(name='integrations_sync')# Test actual behavior: should return result with error when client disabled- self.assertEqual(result.title, 'Import Result')+ self.assertEqual(result.title, 'Connect Result')self.assertGreater(len(result.error_list), 0)self.assertIn('Sync problem. ZM integration disabled?', result.error_list[0])- @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')+ @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')def test_sync_handles_lock_runtime_error(self, mock_lock_context):"""Test sync method handles RuntimeError from lock context and returns proper error result"""lock_error_msg = "Lock acquisition failed"mock_lock_context.side_effect = RuntimeError(lock_error_msg)- result = self.synchronizer.sync(is_initial_import=True)+ result = self.synchronizer.sync(is_initial_connect=True)# Test error handling behavior- self.assertEqual(result.title, 'Import Result')+ self.assertEqual(result.title, 'Connect Result')self.assertEqual(len(result.error_list), 1)self.assertIn(lock_error_msg, result.error_list[0])@@ -83,9 +83,9 @@ class TestZoneMinderSynchronizerSyncHelper(TestCase):"""Test sync helper handles missing ZM client gracefully"""self.mock_manager.zm_client = None- result = self.synchronizer._sync_impl(is_initial_import=True)+ result = self.synchronizer._sync_impl(is_initial_connect=True)- self.assertEqual(result.title, 'Import Result')+ self.assertEqual(result.title, 'Connect Result')self.assertIn('Sync problem. ZM integration disabled?', result.error_list[0])def test_sync_impl_calls_both_sync_methods(self):@@ -107,14 +107,14 @@ class TestZoneMinderSynchronizerSyncHelper(TestCase):with patch.object(self.synchronizer, '_sync_states', side_effect=mock_sync_states) as mock_sync_states, \patch.object(self.synchronizer, '_sync_monitors', side_effect=mock_sync_monitors) as mock_sync_monitors:- result = self.synchronizer._sync_impl(is_initial_import=True)+ result = self.synchronizer._sync_impl(is_initial_connect=True)# Test coordination: both methods called with same resultmock_sync_states.assert_called_once()mock_sync_monitors.assert_called_once()# Test result aggregation: messages from both operations- self.assertEqual(result.title, 'Import Result')+ self.assertEqual(result.title, 'Connect Result')self.assertIn('States synced successfully', result.info_list)self.assertIn('Monitors synced successfully', result.info_list)@@ -957,7 +957,7 @@ class TestZoneMinderSynchronizerSyncResultGrouping(TestCase):with patch.object(self.synchronizer, '_sync_states'), \patch.object(self.synchronizer, '_sync_monitors',return_value=[entity_a, entity_b]):- result = self.synchronizer._sync_impl(is_initial_import=True)+ result = self.synchronizer._sync_impl(is_initial_connect=True)self.assertIsNotNone(result.placement_input)self.assertEqual(result.placement_input.ungrouped_items, [])@@ -972,7 +972,7 @@ class TestZoneMinderSynchronizerSyncResultGrouping(TestCase):def test_sync_impl_emits_no_placement_input_when_no_monitors_imported(self):with patch.object(self.synchronizer, '_sync_states'), \patch.object(self.synchronizer, '_sync_monitors', return_value=[]):- result = self.synchronizer._sync_impl(is_initial_import=True)+ result = self.synchronizer._sync_impl(is_initial_connect=True)# No newly-created entities → no placement input → placement# modal is not shown.diff --git a/src/hi/services/zoneminder/zm_controller.py b/src/hi/services/zoneminder/zm_controller.pyindex d97421ac..f56fe639 100644--- a/src/hi/services/zoneminder/zm_controller.py+++ b/src/hi/services/zoneminder/zm_controller.py@@ -1,7 +1,7 @@import loggingimport re-from hi.integrations.integration_controller import IntegrationController+from hi.integrations.connect.integration_controller import IntegrationControllerfrom hi.integrations.transient_models import IntegrationDetailsfrom hi.integrations.transient_models import IntegrationControlResultdiff --git a/src/hi/services/zoneminder/zm_manage_view_pane.py b/src/hi/services/zoneminder/zm_manage_view_pane.pyindex fe02fb61..69c1d19d 100644--- a/src/hi/services/zoneminder/zm_manage_view_pane.py+++ b/src/hi/services/zoneminder/zm_manage_view_pane.py@@ -1,7 +1,7 @@from typing import Dict-from hi.integrations.integration_data import IntegrationData-from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.connect.integration_data import IntegrationData+from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPaneclass ZmManageViewPane( IntegrationManageViewPane ):diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex 1826c273..6910407a 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -425,7 +425,7 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthSta"""Schema-only validation. Confirms required attributes are presentand structurally usable. Does NOT touch the network — for live- connection probing, see test_connection().+ access validation, see validate_access()."""try:self._build_zm_attr_type_to_attribute_map(@@ -446,12 +446,12 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStaerror_message=f'Configuration validation failed: {e}')- def test_connection(+ def validate_access(self,integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float]) -> ConnectionTestResult:"""- Live connection probe with bounded timeout. Builds a temporary+ Live access validation with bounded timeout. Builds a temporaryZMApi client against the proposed attributes; the client's ownlogin flow exercises auth and reachability synchronously."""@@ -468,7 +468,7 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStaif validation_result.is_valid:return ConnectionTestResult.success()return ConnectionTestResult.failure(- validation_result.error_message or 'Connection test failed'+ validation_result.error_message or 'Access validation failed')except IntegrationAttributeError as e:@@ -476,8 +476,8 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStaexcept IntegrationError as e:return ConnectionTestResult.failure(str(e))except Exception as e:- logger.exception(f'Error in ZoneMinder connection test: {e}')- return ConnectionTestResult.failure(f'Connection test error: {e}')+ logger.exception(f'Error in ZoneMinder access validation: {e}')+ return ConnectionTestResult.failure(f'Access validation error: {e}')def _build_zm_attr_type_to_attribute_map(self,diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.pyindex 7cb764cc..32d6b395 100644--- a/src/hi/services/zoneminder/zm_sync.py+++ b/src/hi/services/zoneminder/zm_sync.py@@ -17,9 +17,9 @@ from hi.apps.entity.entity_placement import (EntityPlacementGroup,)-from hi.integrations.integration_synchronizer import IntegrationSynchronizer-from hi.integrations.sync_check import IntegrationSyncCheck, SyncDelta-from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta+from hi.integrations.connect.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom .zm_metadata import ZmMetaData@@ -42,8 +42,8 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):'Nodect': 'Nodect',}- def get_description(self, is_initial_import: bool) -> Optional[str]:- if is_initial_import:+ def get_description(self, is_initial_connect: bool) -> Optional[str]:+ if is_initial_connect:return ('Each monitor becomes a camera with motion and'' run-state sensors.'@@ -95,9 +95,9 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):).values_list( 'integration_id', 'integration_name' )}- def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:+ def _sync_impl( self, is_initial_connect: bool ) -> IntegrationSyncResult:result = IntegrationSyncResult(- title = self.get_result_title( is_initial_import = is_initial_import ),+ title = self.get_result_title( is_initial_connect = is_initial_connect ),)if not self.zm_manager().zm_client:diff --git a/src/hi/simulator/services/enums.py b/src/hi/simulator/services/enums.pyindex 7a59643a..8c81cef0 100644--- a/src/hi/simulator/services/enums.py+++ b/src/hi/simulator/services/enums.py@@ -45,7 +45,7 @@ class ServiceFaultMode(LabeledEnum):Fault-injection state for a simulated service. Set per-simulator fromthe simulator UI; consumed by ServiceFaultInjectionMiddleware toshort-circuit API responses so the main app's integration- test_connection probe paths can be exercised without standing up real+ validate_access probe paths can be exercised without standing up realmisbehaving servers."""diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.pyindex 0ab258f9..b4d3d83e 100644--- a/src/hi/simulator/services/hass/api/views.py+++ b/src/hi/simulator/services/hass/api/views.py@@ -20,7 +20,7 @@ class PingView( View ):Mirrors the real Home Assistant API root endpoint, which returns asmall JSON envelope confirming the API is running. Used by`HassClient.ping()` as a lightweight reachability + content-type- probe so test_connection can fail quickly when the configured base+ probe so validate_access can fail quickly when the configured baseURL points at the wrong place."""diff --git a/src/hi/simulator/services/middleware.py b/src/hi/simulator/services/middleware.pyindex 44dcf232..7119f987 100644--- a/src/hi/simulator/services/middleware.py+++ b/src/hi/simulator/services/middleware.py@@ -15,7 +15,7 @@ class ServiceFaultInjectionMiddleware:"""Intercepts requests under /services/<short_name>/<...> and applies thetarget simulator's current fault mode. Lets manual end-to-end testing- of the main app's integration test_connection probe failure paths+ of the main app's integration validate_access probe failure pathsproceed without standing up real misbehaving servers.Each service can define its own URL layout, so this matcher does NOT