Home Information - Your home, your data, organized.
Python
Integration Health, Status & Error Notifications (#279) (#285)
Tony Ce27b427def2d
diff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.pyindex d9ef46ec..eb9d7f96 100644--- a/src/hi/apps/alert/alert_manager.py+++ b/src/hi/apps/alert/alert_manager.py@@ -82,10 +82,34 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):self._alert_queue.acknowledge_alert( alert_id = alert_id )return- async def add_alarm( self, alarm : Alarm ):+ async def add_alarm_async( self, alarm : Alarm ):notification_manager = await self.notification_manager_async()if not notification_manager:return+ self._add_alarm_impl(+ alarm = alarm,+ notification_manager = notification_manager,+ )+ return++ def add_alarm( self, alarm : Alarm ):+ """+ Synchronous peer of add_alarm_async. Both AlertQueue.add_alarm+ and NotificationManager.add_notification_item are sync+ thread-safe; the async wrapper exists only for compatibility+ with async callers. Use this from sync code (e.g.,+ HealthStatusProvider transition dispatch).+ """+ notification_manager = self.notification_manager()+ if not notification_manager:+ return+ self._add_alarm_impl(+ alarm = alarm,+ notification_manager = notification_manager,+ )+ return++ def _add_alarm_impl( self, alarm : Alarm, notification_manager ):logging.debug( f'Adding Alarm: {alarm}' )security_state = self.security_manager().security_statetry:@@ -96,8 +120,8 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):)except ValueError as ve:logging.info( str(ve) )- except Exception as e:- logger.exception( 'Problem adding alarm to alert queue.', e )+ except Exception:+ logger.exception( 'Problem adding alarm to alert queue.' )returnasync def do_periodic_maintenance(self) -> AlertMaintenanceResult:diff --git a/src/hi/apps/alert/enums.py b/src/hi/apps/alert/enums.pyindex 0c157c53..03961f47 100644--- a/src/hi/apps/alert/enums.py+++ b/src/hi/apps/alert/enums.py@@ -2,10 +2,11 @@ from hi.apps.common.enums import LabeledEnumclass AlarmSource( LabeledEnum ):-- EVENT = ( 'Event' , '' )- WEATHER = ( 'Weather' , '' )- CONSOLE = ( 'Console' , '' )++ EVENT = ( 'Event' , '' )+ WEATHER = ( 'Weather' , '' )+ CONSOLE = ( 'Console' , '' )+ HEALTH_STATUS = ( 'Health Status' , '' )class AlarmLevel( LabeledEnum ):diff --git a/src/hi/apps/alert/monitors.py b/src/hi/apps/alert/monitors.pyindex 1abb188c..15e84488 100644--- a/src/hi/apps/alert/monitors.py+++ b/src/hi/apps/alert/monitors.py@@ -4,6 +4,7 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.system.provider_info import ProviderInfofrom .alert_mixins import AlertMixin+from .enums import AlarmLevellogger = logging.getLogger(__name__)@@ -31,6 +32,12 @@ class AlertMonitor( PeriodicMonitor, AlertMixin ):expected_heartbeat_interval_secs = cls.ALERT_POLLING_INTERVAL_SECS,)+ def alarm_ceiling(self):+ # Alert queue maintenance failures cause stale/uncleaned alerts+ # but don't lose insertions — alarms still reach the user.+ # WARNING is appropriate.+ return AlarmLevel.WARNING+async def do_work(self):if self.TRACE:logger.debug( 'Checking for alert maintenance work.' )diff --git a/src/hi/apps/alert/tests/test_alert_manager_delegation.py b/src/hi/apps/alert/tests/test_alert_manager_delegation.pyindex 85c7ce75..6199471c 100644--- a/src/hi/apps/alert/tests/test_alert_manager_delegation.py+++ b/src/hi/apps/alert/tests/test_alert_manager_delegation.py@@ -111,7 +111,7 @@ class TestAlertManagerDelegation(BaseTestCase):mock_helper_class.return_value = mock_helper# Add alarm to create an alert- self.run_async_test(self.alert_manager.add_alarm(motion_alarm))+ self.run_async_test(self.alert_manager.add_alarm_async(motion_alarm))# Get alert status data (this should trigger delegation to TransientViewManager)self.alert_manager.get_alert_status_data(@@ -254,13 +254,13 @@ class TestAlertManagerDelegation(BaseTestCase):)# Add old alarm first- self.run_async_test(self.alert_manager.add_alarm(old_alarm))+ self.run_async_test(self.alert_manager.add_alarm_async(old_alarm))# Verify no suggestion exists yetself.assertFalse(self.transient_manager.has_suggestion())# Add new alarm- self.run_async_test(self.alert_manager.add_alarm(new_alarm))+ self.run_async_test(self.alert_manager.add_alarm_async(new_alarm))# Mock settings to enable auto-view for this testwith patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:diff --git a/src/hi/apps/audio/audio_signal.py b/src/hi/apps/audio/audio_signal.pyindex 7ccecf5f..393a97a8 100644--- a/src/hi/apps/audio/audio_signal.py+++ b/src/hi/apps/audio/audio_signal.py@@ -64,15 +64,19 @@ class AudioSignal(LabeledEnum):return cls.WEATHER_WARNINGelif alarm_level == AlarmLevel.CRITICAL:return cls.WEATHER_CRITICAL-- # All other alerts get event signals- else:- if alarm_level == AlarmLevel.INFO:- return cls.EVENT_INFO- elif alarm_level == AlarmLevel.WARNING:- return cls.EVENT_WARNING- elif alarm_level == AlarmLevel.CRITICAL:- return cls.EVENT_CRITICAL-++ # Everything else (EVENT, HEALTH_STATUS, and any future system-+ # level alarm sources) routes to the EVENT signals. EVENT is+ # treated here as the generic "system event" bucket — health+ # transitions are system events about the system's own ability+ # to function, which fits this same audio surface without+ # adding three more operator-tunable settings.+ if alarm_level == AlarmLevel.INFO:+ return cls.EVENT_INFO+ elif alarm_level == AlarmLevel.WARNING:+ return cls.EVENT_WARNING+ elif alarm_level == AlarmLevel.CRITICAL:+ return cls.EVENT_CRITICAL+return Nonediff --git a/src/hi/apps/audio/tests/test_audio_signal.py b/src/hi/apps/audio/tests/test_audio_signal.pyindex 49ca872b..349d3730 100644--- a/src/hi/apps/audio/tests/test_audio_signal.py+++ b/src/hi/apps/audio/tests/test_audio_signal.py@@ -107,6 +107,27 @@ class TestAudioSignal(BaseTestCase):self.assertEqual(AudioSignal.CONSOLE_INFO.label, 'ConsoleInfo')return+ def test_health_status_alarms_route_to_event_signals(self):+ """HEALTH_STATUS alarms reuse the EVENT signals — EVENT is+ treated as the generic 'system event' audio bucket. Health+ transitions are system events about the system's own ability+ to function, which fits this same surface without adding new+ operator-tunable settings."""+ info_signal = AudioSignal.from_alarm_attributes(+ AlarmLevel.INFO, AlarmSource.HEALTH_STATUS, 'health_status.x.recovered'+ )+ self.assertEqual(info_signal, AudioSignal.EVENT_INFO)++ warning_signal = AudioSignal.from_alarm_attributes(+ AlarmLevel.WARNING, AlarmSource.HEALTH_STATUS, 'health_status.x.error'+ )+ self.assertEqual(warning_signal, AudioSignal.EVENT_WARNING)++ critical_signal = AudioSignal.from_alarm_attributes(+ AlarmLevel.CRITICAL, AlarmSource.HEALTH_STATUS, 'health_status.x.error'+ )+ self.assertEqual(critical_signal, AudioSignal.EVENT_CRITICAL)+def test_invalid_alarm_level_returns_none(self):"""Test that invalid alarm levels return None gracefully."""signal = AudioSignal.from_alarm_attributes(AlarmLevel.NONE, AlarmSource.EVENT, None)diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.pyindex 5f2fb01f..9bf4bbba 100644--- a/src/hi/apps/event/event_manager.py+++ b/src/hi/apps/event/event_manager.py@@ -173,7 +173,7 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):if alarm_action.security_level != current_security_level:continuealarm = event.to_alarm( alarm_action = alarm_action )- await alert_manager.add_alarm( alarm )+ await alert_manager.add_alarm_async( alarm )continuecontrol_actions = await sync_to_async(list)(event.event_definition.control_actions.all())diff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.pyindex e21a93e6..841eec39 100644--- a/src/hi/apps/event/tests/test_event_manager.py+++ b/src/hi/apps/event/tests/test_event_manager.py@@ -535,8 +535,8 @@ class TestEventManagerEventActions(AsyncEventManagerTestCase):await self.manager._do_new_event_action([event])# Examine the results - should have called alert manager with correct alarm- mock_alert_manager.add_alarm.assert_called_once()- alarm_call_args = mock_alert_manager.add_alarm.call_args[0][0]+ mock_alert_manager.add_alarm_async.assert_called_once()+ alarm_call_args = mock_alert_manager.add_alarm_async.call_args[0][0]self.assertEqual(alarm_call_args.title, 'Test Event')self.assertEqual(alarm_call_args.alarm_level, AlarmLevel.CRITICAL)@@ -578,7 +578,7 @@ class TestEventManagerEventActions(AsyncEventManagerTestCase):await self.manager._do_new_event_action([event])# Examine the results - should NOT have called alert manager- mock_alert_manager.add_alarm.assert_not_called()+ mock_alert_manager.add_alarm_async.assert_not_called()self.run_async(async_test_logic())returndiff --git a/src/hi/apps/monitor/periodic_monitor.py b/src/hi/apps/monitor/periodic_monitor.pyindex ec5cbe75..826bd554 100644--- a/src/hi/apps/monitor/periodic_monitor.py+++ b/src/hi/apps/monitor/periodic_monitor.py@@ -105,8 +105,28 @@ class PeriodicMonitor( HealthStatusProvider ):except Exception as e:query_duration = (datetimeproxy.now() - query_start_time).total_seconds()- self._logger.exception( f"Query {self._query_counter} failed"- f" after {query_duration:.2f}s: {e}" )+ # Most monitor failures are recurring upstream-connectivity+ # issues (server down, fault-injection, transient network+ # errors). Logging a full traceback every cycle is noise.+ # Emit a single-line summary at ERROR level and keep the+ # traceback available at DEBUG for when an operator is+ # actively investigating.+ error_message = f"{type(e).__name__}: {e}"+ self._logger.error(+ f"Query {self._query_counter} failed after"+ f" {query_duration:.2f}s: {error_message}"+ )+ self._logger.debug(+ f"Traceback for query {self._query_counter} failure:",+ exc_info=True,+ )+ # Update this monitor's own health status. Without this, the+ # monitor's HealthStatus remains at its prior value (typically+ # HEALTHY) even while every cycle is failing — which both+ # misleads the System Info surface that reads it and+ # suppresses the HealthStatusProvider transition-dispatch+ # path that fires alarms on HEALTHY -> ERROR transitions.+ self.record_error( error_message )# Don't re-raise - the monitor loop in start() will continue despite failuresreturndiff --git a/src/hi/apps/notify/monitors.py b/src/hi/apps/notify/monitors.pyindex d00e74b5..520cc8f3 100644--- a/src/hi/apps/notify/monitors.py+++ b/src/hi/apps/notify/monitors.py@@ -1,5 +1,6 @@import logging+from hi.apps.alert.enums import AlarmLevelfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.system.provider_info import ProviderInfo@@ -29,6 +30,12 @@ class NotificationMonitor( PeriodicMonitor, NotificationMixin ):expected_heartbeat_interval_secs = cls.NOTIFICATION_POLLING_INTERVAL_SECS,)+ def alarm_ceiling(self):+ # Email/push delivery failures matter — but the in-app alert+ # queue is independent of notification delivery, so the alarm+ # still reaches the user. WARNING is appropriate.+ return AlarmLevel.WARNING+async def do_work(self):logger.debug( 'Checking for notification maintenance work.' )notification_manager = await self.notification_manager_async()diff --git a/src/hi/apps/security/monitors.py b/src/hi/apps/security/monitors.pyindex f64a79a7..b44a91f9 100644--- a/src/hi/apps/security/monitors.py+++ b/src/hi/apps/security/monitors.py@@ -1,6 +1,7 @@import loggingimport hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.alert.enums import AlarmLevelfrom hi.apps.console.console_helper import ConsoleSettingsHelperfrom hi.apps.config.settings_mixins import SettingsMixinfrom hi.apps.monitor.periodic_monitor import PeriodicMonitor@@ -35,6 +36,13 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):expected_heartbeat_interval_secs = cls.SECURITY_POLLING_INTERVAL_SECS,)+ def alarm_ceiling(self):+ # The security monitor drives automatic DAY/NIGHT transitions.+ # If it fails, the home can be left in the wrong security mode,+ # which mis-gates alarm and notification delivery for ALL other+ # subsystems — treat health failures here as serious.+ return AlarmLevel.CRITICAL+async def do_work(self):try:message = await self._check_security_state()diff --git a/src/hi/apps/system/aggregate_health_provider.py b/src/hi/apps/system/aggregate_health_provider.pyindex df6824b9..a48a5e5f 100644--- a/src/hi/apps/system/aggregate_health_provider.py+++ b/src/hi/apps/system/aggregate_health_provider.py@@ -39,40 +39,61 @@ class AggregateHealthProvider( HealthStatusProvider ):returnsuper()._ensure_health_status_provider_setup()self._api_health_status_providers = [] # Track API health status providers+ self._subordinate_health_status_providers = [] # Track subordinate HealthStatusProvider sourcesreturn@propertydef health_status(self) -> AggregateHealthStatus:- """Get aggregated health status (thread-safe, always fresh)."""+ """Get aggregated health status (thread-safe, always fresh).++ Subordinate registration must form a DAG. If a subordinate is+ itself an AggregateHealthProvider whose subordinate set+ transitively contains this aggregator, the cyclic refresh+ below would recurse — and because each level reads its+ subordinates outside its own lock, a cycle would manifest as+ infinite recursion rather than deadlock. Today all subordinate+ registrations are leaves (monitors → managers); preserve that+ invariant when adding new subordinate types.+ """self._ensure_health_status_provider_setup()+ # Snapshot the registered source lists under our lock, then+ # release before pulling each source's status. Reading another+ # provider's health_status may acquire that provider's lock; if+ # we held our own lock during those reads, a transitive+ # subordinate-of-subordinate aggregator could deadlock against+ # an unrelated lock-acquisition order. Snapshot-and-release+ # avoids the lock-ordering question entirely.with self._health_lock:- # Always refresh from API owners before returning- self._refresh_aggregated_health()- return copy.deepcopy(self._health_status)- return+ api_providers = list( self._api_health_status_providers )+ subordinate_providers = list( self._subordinate_health_status_providers )++ api_snapshots = [+ (p.get_api_provider_info(), p.api_health_status)+ for p in api_providers+ ]+ subordinate_snapshots = [+ (p.get_provider_info(), p.health_status)+ for p in subordinate_providers+ ]- def refresh_aggregated_health(self) -> None:- self._ensure_health_status_provider_setup()with self._health_lock:- self._refresh_aggregated_health()-- def _refresh_aggregated_health(self) -> None:- """Refresh API status map from all tracked API health status providers.+ self._health_status.api_status_map.clear()+ for provider_info, api_health_status in api_snapshots:+ self._health_status.api_status_map[provider_info] = api_health_status- Note: The aggregated health status is computed dynamically via the status property,- so this method only needs to update the API status map.- """- # Clear current sources- self._health_status.api_status_map.clear()+ self._health_status.subordinate_status_map.clear()+ for provider_info, subordinate_health_status in subordinate_snapshots:+ self._health_status.subordinate_status_map[provider_info] = (+ subordinate_health_status+ )- # Collect current health from all providers- for provider in self._api_health_status_providers:- provider_info = provider.get_api_provider_info()- api_health_status = provider.api_health_status- self._health_status.api_status_map[provider_info] = api_health_status+ return copy.deepcopy(self._health_status)- # Status is now computed dynamically via the status property in AggregateHealthStatus- # No need to manually update it here+ def refresh_aggregated_health(self) -> None:+ # Public refresh — preserved for any external callers, though+ # health_status now refreshes on every read. Implemented in+ # terms of health_status to share the lock-ordering discipline.+ _ = self.health_statusreturndef _get_aggregation_rule(self) -> HealthAggregationRule:@@ -82,14 +103,19 @@ class AggregateHealthProvider( HealthStatusProvider ):def add_api_health_status_provider(self,api_health_status_provider : ApiHealthStatusProvider ) -> None:- """Add an API health status provider to be tracked and aggregated."""+ """Add an API health status provider to be tracked and aggregated.++ Registration changes are picked up on the next health_status+ read; no eager refresh inside the lock (which would force us+ to read other providers' health_status while holding our own+ lock — see health_status() for the lock-ordering rationale).+ """self._ensure_health_status_provider_setup()with self._health_lock:if api_health_status_provider not in self._api_health_status_providers:self._api_health_status_providers.append( api_health_status_provider )- self._refresh_aggregated_health()return-+def add_api_health_status_provider_multi(self,api_health_status_provider_sequence : Sequence[ ApiHealthStatusProvider ]@@ -101,9 +127,8 @@ class AggregateHealthProvider( HealthStatusProvider ):if api_health_status_provider not in self._api_health_status_providers:self._api_health_status_providers.append(api_health_status_provider)continue- self._refresh_aggregated_health()return-+def remove_api_health_status_provider(self,api_health_status_provider : ApiHealthStatusProvider@@ -113,5 +138,38 @@ class AggregateHealthProvider( HealthStatusProvider ):with self._health_lock:if api_health_status_provider in self._api_health_status_providers:self._api_health_status_providers.remove(api_health_status_provider)- self._refresh_aggregated_health()+ return++ def add_subordinate_health_status_provider(+ self,+ subordinate : HealthStatusProvider ) -> None:+ """+ Register a subordinate HealthStatusProvider whose status+ contributes to this aggregator's overall status. The aggregator+ pulls the subordinate's current status on each read of+ self.health_status — mirroring how add_api_health_status_provider+ treats its providers.++ Use this for non-API sources that should not alias the parent's+ own _base_status: e.g., a polling monitor that watches the same+ subsystem the manager configures. A successful manager reload+ setting _base_status=HEALTHY must not silently overwrite a+ monitor still reporting ERROR — separate slots prevent that.++ Subordinate registration must form a DAG; see health_status().+ """+ self._ensure_health_status_provider_setup()+ with self._health_lock:+ if subordinate not in self._subordinate_health_status_providers:+ self._subordinate_health_status_providers.append( subordinate )+ return++ def remove_subordinate_health_status_provider(+ self,+ subordinate : HealthStatusProvider ) -> None:+ """Remove a subordinate HealthStatusProvider from tracking."""+ self._ensure_health_status_provider_setup()+ with self._health_lock:+ if subordinate in self._subordinate_health_status_providers:+ self._subordinate_health_status_providers.remove( subordinate )returndiff --git a/src/hi/apps/system/aggregate_health_status.py b/src/hi/apps/system/aggregate_health_status.pyindex 2046f0b3..d18351ad 100644--- a/src/hi/apps/system/aggregate_health_status.py+++ b/src/hi/apps/system/aggregate_health_status.py@@ -10,27 +10,46 @@ from .enums import HealthStatusType, ApiHealthStatusType, HealthAggregationRule@dataclassclass AggregateHealthStatus( HealthStatus ):"""- Extends HealthStatus to add API source tracking and aggregation.- The status property returns the aggregated health status combined with base status.+ Extends HealthStatus to add aggregation across multiple status+ sources. The `status` property returns the worst-of:+ - This provider's own base status (set via record_* on itself).+ - The API source aggregate (api_status_map, with aggregation_rule).+ - Each registered subordinate provider's current status+ (subordinate_status_map, populated on read by the+ AggregateHealthProvider).++ Per-source slots exist because a single status field would alias.+ A successful reload setting _base_status=HEALTHY must not silently+ overwrite a separate subordinate (e.g., a polling monitor) that is+ still reporting ERROR."""# Current aggregated API health data- api_status_map : Dict[ProviderInfo, ApiHealthStatus] = field(default_factory=dict)- aggregation_rule : HealthAggregationRule = HealthAggregationRule.ALL_SOURCES_HEALTHY+ api_status_map : Dict[ProviderInfo, ApiHealthStatus] = field(default_factory=dict)++ # Snapshot of subordinate HealthStatusProvider statuses, populated+ # on read of the parent AggregateHealthProvider. Mirrors+ # api_status_map's shape: keyed by ProviderInfo, valued by the+ # subordinate's full HealthStatus so the modal / detail views can+ # render last_message, heartbeat, error_count, etc.+ subordinate_status_map : Dict[ProviderInfo, HealthStatus] = field(default_factory=dict)++ aggregation_rule : HealthAggregationRule = HealthAggregationRule.ALL_SOURCES_HEALTHY# Store the base status separately (for provider's own health issues)- _base_status : HealthStatusType = field(default=HealthStatusType.HEALTHY, init=False)+ _base_status : HealthStatusType = field(default=HealthStatusType.HEALTHY, init=False)@propertydef status(self) -> HealthStatusType:"""Override status to return the combined health status.- Returns the worst of base status and aggregated API status.+ Returns the worst of base status, aggregated API status, and+ every registered subordinate's status."""- api_health = self.aggregate_health()+ candidates = [ self._base_status, self.aggregate_health() ]+ candidates.extend( hs.status for hs in self.subordinate_status_map.values() )- # Return worst of base status and aggregated API status using priority# Lower priority number = worse health- return min([ self._base_status, api_health ], key=lambda s: s.priority )+ return min( candidates, key=lambda s: s.priority )@status.setterdef status(self, value: HealthStatusType) -> None:diff --git a/src/hi/apps/system/health_status.py b/src/hi/apps/system/health_status.pyindex 43ce9915..30403c8f 100644--- a/src/hi/apps/system/health_status.py+++ b/src/hi/apps/system/health_status.py@@ -161,7 +161,7 @@ class HealthStatus:elif self.status.is_critical:return "border-error"elif self.status.is_error:- return "bordder-error"+ return "border-error"else: # UNKNOWNreturn "border-unknown"diff --git a/src/hi/apps/system/health_status_alarm_mapper.py b/src/hi/apps/system/health_status_alarm_mapper.pynew file mode 100644index 00000000..beb774a4--- /dev/null+++ b/src/hi/apps/system/health_status_alarm_mapper.py@@ -0,0 +1,181 @@+"""+Map HealthStatusProvider state transitions to system alarms.++Stateless policy concentrator. Inputs: a HealthStatusTransition plus the+provider's declared maximum allowed alarm level. Output: an Optional[Alarm]+that the caller (HealthStatusProvider._dispatch_transition_alarm) hands to+AlertManager.++Design echoes WeatherAlertAlarmMapper:+- Single create_alarm() entry point; helper methods are pure.+- Alarms apply at SecurityLevel.OFF (universal — health affects everyone).+- Distinct alarm_type strings for error vs recovery so the alert queue+ treats them as separate alerts the user can see and acknowledge+ independently.++Per-provider seriousness is expressed as a maximum alarm level (the+"ceiling"), declared by the provider via HealthStatusProvider.alarm_ceiling.+The mapper picks a "natural" alarm level for the transition class+(ERROR=CRITICAL, WARNING=WARNING, recovery=INFO) and clamps to the+provider's ceiling. This lets each provider declare relative importance+(e.g., HASS/ZM ceiling=CRITICAL, HomeBox ceiling=INFO) without owning the+full mapping policy.++Transitions involving UNKNOWN or DISABLED on either side are+suppressed entirely (no alarm fires). UNKNOWN is initialization noise+with no settled baseline; DISABLED is operator-initiated and the+operator already knows.+"""+from typing import List, Optional+import logging++import hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.alert.alarm import Alarm+from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKey++from .enums import HealthStatusType+from .health_status_transition import HealthStatusTransition++logger = logging.getLogger(__name__)+++class HealthStatusAlarmMapper:++ # Single shared lifetime for both error and recovery alarms. They+ # MUST match: if recovery expired before the error it's resolving,+ # the user would be left looking at a bare error alert from the+ # moment the recovery disappeared until the error finally expired —+ # incorrectly suggesting the integration is still broken.+ ALARM_LIFETIME_SECS = 30 * 60++ # Natural alarm level for each transition class, BEFORE the+ # per-provider ceiling is applied. DISABLED is intentionally+ # omitted — see _ALARM_SUPPRESSED_STATES.+ NATURAL_LEVEL_FOR_NEW_STATUS = {+ HealthStatusType.ERROR : AlarmLevel.CRITICAL,+ HealthStatusType.WARNING : AlarmLevel.WARNING,+ }+ RECOVERY_NATURAL_LEVEL = AlarmLevel.INFO++ # States whose presence on EITHER side of a transition disqualifies+ # the transition from alarming:+ # UNKNOWN - initialization edge; no settled baseline to compare+ # against.+ # DISABLED - operator-initiated; entering it is the operator's+ # explicit action and exiting it is the operator's+ # explicit re-enable. The operator already knows; an+ # alarm would be a redundant confirmation.+ _ALARM_SUPPRESSED_STATES = frozenset({+ HealthStatusType.UNKNOWN,+ HealthStatusType.DISABLED,+ })++ def should_create_alarm( self, transition : HealthStatusTransition ) -> bool:+ if ( transition.previous_status in self._ALARM_SUPPRESSED_STATES+ or transition.current_status in self._ALARM_SUPPRESSED_STATES ):+ return False++ # Recovery: HEALTHY from a non-HEALTHY state.+ if transition.is_recovery:+ return True++ # Forward transitions into states that warrant an alarm.+ if transition.current_status in self.NATURAL_LEVEL_FOR_NEW_STATUS:+ return True++ return False++ def get_alarm_level( self,+ transition : HealthStatusTransition,+ max_level : AlarmLevel ) -> Optional[ AlarmLevel ]:+ if not self.should_create_alarm( transition ):+ return None++ if transition.is_recovery:+ natural = self.RECOVERY_NATURAL_LEVEL+ else:+ natural = self.NATURAL_LEVEL_FOR_NEW_STATUS.get( transition.current_status )+ if natural is None:+ return None++ # Clamp to the provider's declared ceiling.+ if natural.priority > max_level.priority:+ return max_level+ return natural++ def get_alarm_lifetime_secs( self, transition : HealthStatusTransition ) -> int:+ return self.ALARM_LIFETIME_SECS++ def get_alarm_type( self, transition : HealthStatusTransition ) -> str:+ # Distinct types so error and recovery produce separate alerts+ # the user can see and acknowledge independently. Includes the+ # provider id so signatures group sensibly when multiple+ # providers are unhealthy at once.+ provider_id = transition.provider_info.provider_id+ if transition.is_recovery:+ return f'health_status.{provider_id}.recovered'+ return f'health_status.{provider_id}.error'++ def get_alarm_title( self, transition : HealthStatusTransition ) -> str:+ provider_name = transition.provider_info.provider_name+ if transition.is_recovery:+ return f'{provider_name} recovered'+ return f'{provider_name} unhealthy'++ def create_sensor_responses( self,+ transition : HealthStatusTransition ) -> List[ SensorResponse ]:+ provider_info = transition.provider_info+ detail_attrs = {+ 'Provider' : provider_info.provider_name,+ 'Status' : transition.current_status.label,+ 'Previous Status' : transition.previous_status.label,+ 'Error Count' : str( transition.error_count ),+ 'Last Update' : transition.timestamp.strftime( '%Y-%m-%d %H:%M:%S' ),+ }+ if transition.last_message:+ message = transition.last_message+ if len( message ) > 300:+ message = message[ :300 ] + '...'+ detail_attrs[ 'Message' ] = message++ # Synthetic integration_key — health-status alarms don't have a+ # backing sensor record, but downstream rendering treats this+ # field as the canonical pointer to the alarm's source.+ integration_key = IntegrationKey(+ integration_id = 'health_status',+ integration_name = provider_info.provider_id,+ )+ return [+ SensorResponse(+ integration_key = integration_key,+ value = transition.current_status.name,+ timestamp = transition.timestamp,+ sensor = None,+ detail_attrs = detail_attrs,+ source_image_url = None,+ has_video_stream = False,+ ),+ ]++ def create_alarm( self,+ transition : HealthStatusTransition,+ max_level : AlarmLevel ) -> Optional[ Alarm ]:+ alarm_level = self.get_alarm_level( transition = transition, max_level = max_level )+ if alarm_level is None:+ return None++ alarm = Alarm(+ alarm_source = AlarmSource.HEALTH_STATUS,+ alarm_type = self.get_alarm_type( transition = transition ),+ alarm_level = alarm_level,+ title = self.get_alarm_title( transition = transition ),+ sensor_response_list = self.create_sensor_responses( transition = transition ),+ security_level = SecurityLevel.OFF,+ alarm_lifetime_secs = self.get_alarm_lifetime_secs( transition = transition ),+ timestamp = datetimeproxy.now(),+ )+ logger.info( f'Created health-status alarm: {alarm.signature} - {alarm.title}' )+ return alarmdiff --git a/src/hi/apps/system/health_status_provider.py b/src/hi/apps/system/health_status_provider.pyindex 9b2e7ce1..7eede19a 100644--- a/src/hi/apps/system/health_status_provider.py+++ b/src/hi/apps/system/health_status_provider.py@@ -2,14 +2,18 @@ from abc import ABC, abstractmethodimport copyimport loggingimport threading-from typing import Optional+from typing import Optional, TYPE_CHECKINGimport hi.apps.common.datetimeproxy as datetimeproxyfrom .enums import HealthStatusTypefrom .health_status import HealthStatus+from .health_status_transition import HealthStatusTransitionfrom .provider_info import ProviderInfo+if TYPE_CHECKING:+ from hi.apps.alert.enums import AlarmLevel+logger = logging.getLogger(__name__)@@ -76,11 +80,37 @@ class HealthStatusProvider(ABC):logger.debug("Health heartbeat updated")return+ def alarm_ceiling( self ) -> Optional['AlarmLevel']:+ """+ Maximum alarm level this provider is permitted to fire on+ state transitions. Return None to opt out of alarm dispatch+ entirely (the default — most providers update local health+ only). Override and return an AlarmLevel to participate; the+ HealthStatusAlarmMapper will compute a "natural" level for the+ transition (ERROR=CRITICAL, WARNING=WARNING, recovery=INFO)+ and clamp it down to this ceiling so different providers can+ express their relative importance without each owning the+ full mapping policy. Transitions involving UNKNOWN or DISABLED+ on either side are suppressed entirely.++ Subclass guidance:+ - User-facing managers (whose state transitions reflect+ user-initiated actions like Configure/Sync) should leave+ this at None — those paths give immediate inline feedback+ and don't need redundant alarms.+ - Background periodic monitors that publish health for+ dependencies the user cannot otherwise see should override+ this. The ceiling expresses "how serious is it when this+ dependency degrades silently in the background".+ """+ return None+def update_health_status( self,status : HealthStatusType,last_message : Optional[str] = None) -> None:self._ensure_health_status_provider_setup()with self._health_lock:+ previous_status = self._health_status.statusself._health_status.status = statusself._health_status.last_update = datetimeproxy.now()self._health_status.last_message = last_message@@ -91,8 +121,70 @@ class HealthStatusProvider(ABC):# Reset error count on successful statusself._health_status.error_count = 0+ current_error_count = self._health_status.error_count+ current_update_time = self._health_status.last_update+logger.debug( f'Health status updated to {status.label}:'f' {last_message or "No error"}')++ if previous_status != status:+ try:+ self._dispatch_transition_alarm(+ previous_status = previous_status,+ current_status = status,+ last_message = last_message,+ error_count = current_error_count,+ timestamp = current_update_time,+ )+ except Exception:+ # Framework-level safety net: a misbehaving alarm path+ # (or a subclass override that forgets its own+ # try/except) must NEVER break health bookkeeping for+ # the caller of update_health_status.+ logger.exception( 'Failed to dispatch health-status transition alarm.' )+ return++ def _dispatch_transition_alarm( self,+ previous_status : HealthStatusType,+ current_status : HealthStatusType,+ last_message : Optional[str],+ error_count : int,+ timestamp ) -> None:+ """+ Map a state transition to an alarm and queue it via AlertManager+ when the provider is opted in (alarm_ceiling returns+ non-None). The framework calls into the alert subsystem+ directly — the dependency direction (apps/system -> apps/alert)+ is acceptable since alert is a more general-purpose facility.++ Caller (update_health_status) wraps invocations in a safety+ net, so subclass overrides do not need to defend against their+ own exceptions to preserve health bookkeeping.+ """+ max_level = self.alarm_ceiling()+ if max_level is None:+ return++ # Imported lazily to avoid module-load-time edges in apps that+ # do not depend on the alert subsystem at import time.+ from hi.apps.alert.alert_manager import AlertManager+ from .health_status_alarm_mapper import HealthStatusAlarmMapper++ transition = HealthStatusTransition(+ provider_info = self.get_provider_info(),+ previous_status = previous_status,+ current_status = current_status,+ last_message = last_message,+ error_count = error_count,+ timestamp = timestamp,+ )+ alarm = HealthStatusAlarmMapper().create_alarm(+ transition = transition,+ max_level = max_level,+ )+ if alarm is None:+ return+ AlertManager().add_alarm( alarm = alarm )returndiff --git a/src/hi/apps/system/health_status_transition.py b/src/hi/apps/system/health_status_transition.pynew file mode 100644index 00000000..d990a348--- /dev/null+++ b/src/hi/apps/system/health_status_transition.py@@ -0,0 +1,34 @@+from dataclasses import dataclass+from datetime import datetime+from typing import Optional++from .enums import HealthStatusType+from .provider_info import ProviderInfo+++@dataclass+class HealthStatusTransition:+ """+ Materialization of a single observed change in a HealthStatusProvider's+ status. Built and dispatched by HealthStatusProvider.update_health_status+ when (and only when) the new status differs from the prior one.++ Consumers (e.g., HealthStatusAlarmMapper) use this to decide whether to+ emit alarms / alerts. The transient is intentionally narrow — no+ references to alert plumbing — so apps/system stays alert-free.+ """++ provider_info : ProviderInfo+ previous_status : HealthStatusType+ current_status : HealthStatusType+ last_message : Optional[ str ]+ error_count : int+ timestamp : datetime++ @property+ def is_recovery(self) -> bool:+ """Transition into HEALTHY from a previously-non-HEALTHY state."""+ return bool(+ self.current_status == HealthStatusType.HEALTHY+ and self.previous_status != HealthStatusType.HEALTHY+ )diff --git a/src/hi/apps/system/monitors.py b/src/hi/apps/system/monitors.pyindex b25e934f..a407e6cf 100644--- a/src/hi/apps/system/monitors.py+++ b/src/hi/apps/system/monitors.py@@ -1,6 +1,7 @@from asgiref.sync import sync_to_asyncimport logging+from hi.apps.alert.enums import AlarmLevelfrom hi.apps.common.history_table_manager import CleanupResultTypefrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.system.history_cleanup.manager import HistoryCleanupManager@@ -37,6 +38,12 @@ class SystemMonitor( PeriodicMonitor ):expected_heartbeat_interval_secs = cls.SYSTEM_MAINTENANCE_INTERVAL_SECS,)+ def alarm_ceiling(self):+ # History cleanup is bookkeeping. Failures cause table growth+ # over time but do not lose user-facing data. INFO-level+ # visibility is sufficient.+ return AlarmLevel.INFO+async def do_work(self):logger.debug('Running system maintenance tasks')try:diff --git a/src/hi/apps/system/templates/system/panes/health_status_badge.html b/src/hi/apps/system/templates/system/panes/health_status_badge.htmlnew file mode 100644index 00000000..fd0e87ee--- /dev/null+++ b/src/hi/apps/system/templates/system/panes/health_status_badge.html@@ -0,0 +1,27 @@+{% load icons %}+{% comment %}+Expanded health-status badge — button-style with state label.++Parameters:+ health_status : HealthStatus instance (required).++Renders all five HealthStatusType values with a state-appropriate icon+and the canonical status.label as the displayed text.+{% endcomment %}+{% if health_status %}+{% with status=health_status.status %}+<span class="btn btn-sm hi-health-badge hi-health-badge-{{ status.name|lower }}">+ {% if status.is_healthy %}+ {% icon "check-circle" size="md" css_class="mr-1" %}{{ status.label }}+ {% elif status.is_critical %}+ {% icon "warning" size="md" css_class="mr-1" %}{{ status.label }}+ {% elif status.is_warning %}+ {% icon "warning" size="md" css_class="mr-1" %}{{ status.label }}+ {% elif status.is_info %}+ {% icon "info-circle" size="md" css_class="mr-1" %}{{ status.label }}+ {% else %}+ {% icon "question-circle" size="md" css_class="mr-1" %}{{ status.label }}+ {% endif %}+</span>+{% endwith %}+{% endif %}diff --git a/src/hi/apps/system/templates/system/panes/health_status_details.html b/src/hi/apps/system/templates/system/panes/health_status_details.htmlindex bbf80b6e..f1fec39c 100644--- a/src/hi/apps/system/templates/system/panes/health_status_details.html+++ b/src/hi/apps/system/templates/system/panes/health_status_details.html@@ -101,6 +101,23 @@</div>{% endif %}+ {% if health_status.subordinate_status_map %}+ <!-- Subordinate Providers Section -->+ <div class="row mt-4">+ <div class="col-12">+ <h6 class="mb-3">+ {% icon "tasks" size="sm" css_class="mr-2" %}+ Components+ </h6>++ {% for subordinate_health_status in health_status.subordinate_status_map.values %}+ <hr />+ {% include "system/panes/subordinate_health_status_details.html" with subordinate_health_status=subordinate_health_status %}+ {% endfor %}+ </div>+ </div>+ {% endif %}+{% if health_status_provider.get_provider_info.description %}<div class="row"><div class="col-12">diff --git a/src/hi/apps/system/templates/system/panes/subordinate_health_status_details.html b/src/hi/apps/system/templates/system/panes/subordinate_health_status_details.htmlnew file mode 100644index 00000000..9b8646a7--- /dev/null+++ b/src/hi/apps/system/templates/system/panes/subordinate_health_status_details.html@@ -0,0 +1,63 @@+{% load icons %}+{% load tz %}+{% load humanize %}+{% comment %}+Per-subordinate health-status detail block — used inside the+health-status modal when an AggregateHealthProvider has registered+subordinate HealthStatusProviders. Mirrors api_health_status_details.html+in shape but renders only the fields HealthStatus carries (no API+metrics).++Parameters:+ subordinate_health_status : HealthStatus instance (required).+{% endcomment %}+{% timezone USER_TIMEZONE %}++<div class="{{ subordinate_health_status.border_color_class }} mb-4">+ <div class="d-flex justify-content-between align-items-center mb-2">+ <h5 class="mb-0">{{ subordinate_health_status.provider_name }}</h5>+ <span class="badge {{ subordinate_health_status.status_badge_class }}">+ {% icon subordinate_health_status.status_icon size="sm" css_class="mr-1" %}{{ subordinate_health_status.status.label }}+ </span>+ </div>++ {% if subordinate_health_status.last_message %}+ <div class="row">+ <div class="col-sm-3"><strong>Last Message:</strong></div>+ <div class="col-sm-9">+ <div class="{{ subordinate_health_status.status_alert_class }} p-2">+ {{ subordinate_health_status.last_message }}+ </div>+ </div>+ </div>+ {% endif %}++ {% if subordinate_health_status.heartbeat %}+ <div class="row mt-2">+ <div class="col-sm-3"><strong>Heartbeat:</strong></div>+ <div class="col-sm-9">+ <span class="heartbeat-indicator {{ subordinate_health_status.heartbeat_css_class }}"></span>+ <span class="{{ subordinate_health_status.heartbeat_text_class }}">{{ subordinate_health_status.heartbeat_status_text }}</span>+ <span class="text-muted ml-2">+ ({{ subordinate_health_status.heartbeat|localtime|naturaltime }})+ </span>+ </div>+ </div>+ {% endif %}++ <div class="row mt-2">+ <div class="col-sm-3"><strong>Last Update:</strong></div>+ <div class="col-sm-9">+ {{ subordinate_health_status.last_update|localtime|naturaltime }}+ <span class="text-muted">({{ subordinate_health_status.last_update|localtime|date:"M j, Y H:i:s" }})</span>+ </div>+ </div>++ {% if subordinate_health_status.error_count > 1 %}+ <div class="row mt-2">+ <div class="col-sm-3"><strong>Error Count:</strong></div>+ <div class="col-sm-9">{{ subordinate_health_status.error_count }}</div>+ </div>+ {% endif %}+</div>+{% endtimezone %}diff --git a/src/hi/apps/system/tests/test_aggregate_health_status.py b/src/hi/apps/system/tests/test_aggregate_health_status.pyindex 52dfc1c0..871127bd 100644--- a/src/hi/apps/system/tests/test_aggregate_health_status.py+++ b/src/hi/apps/system/tests/test_aggregate_health_status.py@@ -6,6 +6,7 @@ from unittest.mock import MagicMockfrom hi.apps.system.aggregate_health_status import AggregateHealthStatusfrom hi.apps.system.api_health_status import ApiHealthStatus+from hi.apps.system.health_status import HealthStatusfrom hi.apps.system.provider_info import ProviderInfofrom hi.apps.system.enums import (HealthStatusType,@@ -14,6 +15,16 @@ from hi.apps.system.enums import ()+def _sub_health_status(provider_info: ProviderInfo, status: HealthStatusType) -> HealthStatus:+ return HealthStatus(+ provider_id=provider_info.provider_id,+ provider_name=provider_info.provider_name,+ status=status,+ last_update=MagicMock(),+ last_message=None,+ )++class TestAggregateHealthStatus(unittest.TestCase):"""Test cases for AggregateHealthStatus aggregation logic."""@@ -223,6 +234,72 @@ class TestAggregateHealthStatus(unittest.TestCase):result = self.base_status.statusself.assertEqual(result, HealthStatusType.ERROR, "API FAILING should override base HEALTHY")+ def test_subordinate_status_factors_into_overall(self):+ """A registered subordinate's status must contribute to the+ worst-of computation in the overall status property."""+ sub_provider = ProviderInfo(+ provider_id='sub.monitor',+ provider_name='Sub Monitor',+ description='',+ )+ # Base healthy; subordinate healthy → overall healthy.+ self.base_status._base_status = HealthStatusType.HEALTHY+ self.base_status.subordinate_status_map[sub_provider] = _sub_health_status(+ sub_provider, HealthStatusType.HEALTHY)+ self.assertEqual(self.base_status.status, HealthStatusType.HEALTHY)++ # Subordinate flips to ERROR → overall ERROR even though base+ # is HEALTHY. This is the aliasing case the slot was added to+ # solve: a healthy reload must not mask a failing monitor.+ self.base_status.subordinate_status_map[sub_provider] = _sub_health_status(+ sub_provider, HealthStatusType.ERROR)+ self.assertEqual(self.base_status.status, HealthStatusType.ERROR)++ def test_subordinate_error_persists_across_base_healthy(self):+ """Setting _base_status to HEALTHY must not clear a subordinate's+ ERROR — separate slots are the whole point."""+ sub_provider = ProviderInfo(+ provider_id='sub.monitor',+ provider_name='Sub Monitor',+ description='',+ )+ self.base_status._base_status = HealthStatusType.WARNING+ self.base_status.subordinate_status_map[sub_provider] = _sub_health_status(+ sub_provider, HealthStatusType.ERROR)+ self.assertEqual(self.base_status.status, HealthStatusType.ERROR)++ # Simulate a successful manager reload setting base to HEALTHY.+ self.base_status._base_status = HealthStatusType.HEALTHY+ # Subordinate still ERROR → overall still ERROR.+ self.assertEqual(self.base_status.status, HealthStatusType.ERROR)++ # Only when subordinate also recovers does overall go HEALTHY.+ self.base_status.subordinate_status_map[sub_provider] = _sub_health_status(+ sub_provider, HealthStatusType.HEALTHY)+ self.assertEqual(self.base_status.status, HealthStatusType.HEALTHY)++ def test_subordinate_combines_with_api_sources(self):+ """Worst-of must span base + API aggregate + subordinates."""+ # Healthy API source.+ api_pi, api_health = self._create_api_status('one', ApiHealthStatusType.HEALTHY)+ self.base_status.api_status_map[api_pi] = api_health+ self.base_status._base_status = HealthStatusType.HEALTHY++ # Subordinate WARNING — overall must reflect WARNING.+ sub_pi = ProviderInfo(+ provider_id='sub.monitor',+ provider_name='Sub Monitor',+ description='',+ )+ self.base_status.subordinate_status_map[sub_pi] = _sub_health_status(+ sub_pi, HealthStatusType.WARNING)+ self.assertEqual(self.base_status.status, HealthStatusType.WARNING)++ # API source flips to FAILING → ERROR. ERROR is worse than WARNING.+ _, failing = self._create_api_status('one', ApiHealthStatusType.FAILING)+ self.base_status.api_status_map[api_pi] = failing+ self.assertEqual(self.base_status.status, HealthStatusType.ERROR)+def test_disabled_sources_excluded(self):"""Test comprehensive scenarios where DISABLED sources are properly excluded."""test_cases = [diff --git a/src/hi/apps/system/tests/test_aggregate_subordinate_provider.py b/src/hi/apps/system/tests/test_aggregate_subordinate_provider.pynew file mode 100644index 00000000..5379a0c4--- /dev/null+++ b/src/hi/apps/system/tests/test_aggregate_subordinate_provider.py@@ -0,0 +1,99 @@+"""+Tests for the subordinate-HealthStatusProvider registration path on+AggregateHealthProvider. The aggregator pulls the subordinate's status+on each read of self.health_status — so a successful base-status update+on the aggregator cannot mask a subordinate that is still reporting a+worse status.+"""+import logging++from django.test import SimpleTestCase++from hi.apps.system.aggregate_health_provider import AggregateHealthProvider+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.health_status_provider import HealthStatusProvider+from hi.apps.system.provider_info import ProviderInfo++logging.disable(logging.CRITICAL)+++class _Aggregator(AggregateHealthProvider):+ @classmethod+ def get_provider_info(cls):+ return ProviderInfo(+ provider_id='test.aggregator',+ provider_name='Test Aggregator',+ description='',+ )+++class _Subordinate(HealthStatusProvider):+ def __init__(self, provider_id):+ self._test_provider_id = provider_id+ super().__init__()++ def get_provider_info(self):+ return ProviderInfo(+ provider_id=self._test_provider_id,+ provider_name=self._test_provider_id,+ description='',+ )+++class AggregateSubordinateProviderTest(SimpleTestCase):++ def test_subordinate_status_pulled_on_each_health_read(self):+ agg = _Aggregator()+ sub = _Subordinate('test.sub')++ # Establish a healthy baseline on the aggregator.+ agg.update_health_status(HealthStatusType.HEALTHY, 'Reloaded')+ self.assertEqual(agg.health_status.status, HealthStatusType.HEALTHY)++ # Register the subordinate. UNKNOWN doesn't drag the overall+ # status down (it represents "no data," not "bad"), so aggregator+ # remains HEALTHY.+ agg.add_subordinate_health_status_provider(sub)+ self.assertEqual(agg.health_status.status, HealthStatusType.HEALTHY)++ # Subordinate moves to HEALTHY → aggregator still HEALTHY.+ sub.update_health_status(HealthStatusType.HEALTHY, 'init')+ self.assertEqual(agg.health_status.status, HealthStatusType.HEALTHY)++ # Subordinate flips to ERROR.+ sub.update_health_status(HealthStatusType.ERROR, 'broken')+ self.assertEqual(agg.health_status.status, HealthStatusType.ERROR)++ # Aggregator records its OWN healthy state again (e.g.,+ # successful reload). Subordinate is still ERROR; aggregator+ # must still report ERROR. This is the aliasing case the new+ # slot was added to solve.+ agg.update_health_status(HealthStatusType.HEALTHY, 'Reloaded again')+ self.assertEqual(agg.health_status.status, HealthStatusType.ERROR)++ # Only when the subordinate also recovers does the aggregator+ # go HEALTHY.+ sub.update_health_status(HealthStatusType.HEALTHY, 'recovered')+ self.assertEqual(agg.health_status.status, HealthStatusType.HEALTHY)++ def test_remove_subordinate_stops_contribution(self):+ agg = _Aggregator()+ sub = _Subordinate('test.sub')+ agg.update_health_status(HealthStatusType.HEALTHY, 'init')++ agg.add_subordinate_health_status_provider(sub)+ sub.update_health_status(HealthStatusType.ERROR, 'broken')+ self.assertEqual(agg.health_status.status, HealthStatusType.ERROR)++ agg.remove_subordinate_health_status_provider(sub)+ # Aggregator returns to its own base status — subordinate no+ # longer counted.+ self.assertEqual(agg.health_status.status, HealthStatusType.HEALTHY)++ def test_double_registration_is_idempotent(self):+ agg = _Aggregator()+ sub = _Subordinate('test.sub')++ agg.add_subordinate_health_status_provider(sub)+ agg.add_subordinate_health_status_provider(sub)+ self.assertEqual(len(agg._subordinate_health_status_providers), 1)diff --git a/src/hi/apps/system/tests/test_health_status_alarm_mapper.py b/src/hi/apps/system/tests/test_health_status_alarm_mapper.pynew file mode 100644index 00000000..b4038d82--- /dev/null+++ b/src/hi/apps/system/tests/test_health_status_alarm_mapper.py@@ -0,0 +1,200 @@+"""+Unit tests for HealthStatusAlarmMapper. Pure-policy tests — no Django DB,+no AlertManager interaction.+"""+import logging+from datetime import datetime++from django.test import SimpleTestCase++from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.security.enums import SecurityLevel+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.health_status_alarm_mapper import HealthStatusAlarmMapper+from hi.apps.system.health_status_transition import HealthStatusTransition+from hi.apps.system.provider_info import ProviderInfo++logging.disable(logging.CRITICAL)+++def _provider() -> ProviderInfo:+ return ProviderInfo(+ provider_id='test.provider',+ provider_name='Test Provider',+ description='',+ )+++def _transition( prev: HealthStatusType, curr: HealthStatusType ) -> HealthStatusTransition:+ return HealthStatusTransition(+ provider_info=_provider(),+ previous_status=prev,+ current_status=curr,+ last_message='upstream unreachable',+ error_count=1,+ timestamp=datetime(2026, 4, 28, 12, 0, 0),+ )+++class HealthStatusAlarmMapperTest(SimpleTestCase):++ def setUp(self):+ self.mapper = HealthStatusAlarmMapper()++ # --- should_create_alarm gating ---++ def test_unknown_on_either_side_suppresses_alarm(self):+ # Initialization edge: no settled baseline.+ for prev, curr in [+ (HealthStatusType.UNKNOWN, HealthStatusType.ERROR),+ (HealthStatusType.UNKNOWN, HealthStatusType.HEALTHY),+ (HealthStatusType.UNKNOWN, HealthStatusType.WARNING),+ ]:+ t = _transition(prev, curr)+ self.assertFalse(+ self.mapper.should_create_alarm(t),+ f'{prev} -> {curr} should be suppressed',+ )++ def test_disabled_on_either_side_suppresses_alarm(self):+ # Operator-initiated edge: entering or leaving DISABLED is an+ # explicit user action; the operator already knows.+ for prev, curr in [+ (HealthStatusType.HEALTHY, HealthStatusType.DISABLED),+ (HealthStatusType.ERROR, HealthStatusType.DISABLED),+ (HealthStatusType.DISABLED, HealthStatusType.HEALTHY),+ (HealthStatusType.DISABLED, HealthStatusType.ERROR),+ ]:+ t = _transition(prev, curr)+ self.assertFalse(+ self.mapper.should_create_alarm(t),+ f'{prev} -> {curr} should be suppressed',+ )++ def test_warning_target_alarms(self):+ # WARNING in monitor context means a real probe failure+ # (categorized at warning rather than error) — alarm-worthy.+ t = _transition(HealthStatusType.HEALTHY, HealthStatusType.WARNING)+ self.assertTrue(self.mapper.should_create_alarm(t))++ def test_healthy_to_error_alarms(self):+ t = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)+ self.assertTrue(self.mapper.should_create_alarm(t))++ def test_error_to_healthy_recovery_alarms(self):+ t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)+ self.assertTrue(self.mapper.should_create_alarm(t))++ def test_warning_to_healthy_recovery_alarms(self):+ t = _transition(HealthStatusType.WARNING, HealthStatusType.HEALTHY)+ self.assertTrue(self.mapper.should_create_alarm(t))++ # --- get_alarm_level: natural levels and ceiling clamp ---++ def test_error_natural_level_is_critical(self):+ t = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)+ self.assertEqual(+ self.mapper.get_alarm_level(t, max_level=AlarmLevel.CRITICAL),+ AlarmLevel.CRITICAL,+ )++ def test_warning_natural_level_is_warning(self):+ t = _transition(HealthStatusType.HEALTHY, HealthStatusType.WARNING)+ self.assertEqual(+ self.mapper.get_alarm_level(t, max_level=AlarmLevel.CRITICAL),+ AlarmLevel.WARNING,+ )++ def test_recovery_natural_level_is_info(self):+ t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)+ self.assertEqual(+ self.mapper.get_alarm_level(t, max_level=AlarmLevel.CRITICAL),+ AlarmLevel.INFO,+ )++ def test_error_clamped_down_when_provider_caps_at_info(self):+ t = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)+ self.assertEqual(+ self.mapper.get_alarm_level(t, max_level=AlarmLevel.INFO),+ AlarmLevel.INFO,+ )++ def test_error_clamped_down_when_provider_caps_at_warning(self):+ t = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)+ self.assertEqual(+ self.mapper.get_alarm_level(t, max_level=AlarmLevel.WARNING),+ AlarmLevel.WARNING,+ )++ def test_suppressed_edge_returns_no_level(self):+ for prev, curr in [+ (HealthStatusType.UNKNOWN, HealthStatusType.ERROR),+ (HealthStatusType.HEALTHY, HealthStatusType.DISABLED),+ (HealthStatusType.DISABLED, HealthStatusType.HEALTHY),+ ]:+ t = _transition(prev, curr)+ self.assertIsNone(+ self.mapper.get_alarm_level(t, max_level=AlarmLevel.CRITICAL),+ f'{prev} -> {curr} should produce no alarm level',+ )++ # --- alarm types: signature stability ---++ def test_error_and_recovery_have_distinct_types(self):+ t_err = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)+ t_rec = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)+ self.assertNotEqual(+ self.mapper.get_alarm_type(t_err),+ self.mapper.get_alarm_type(t_rec),+ )+ self.assertIn('error', self.mapper.get_alarm_type(t_err))+ self.assertIn('recovered', self.mapper.get_alarm_type(t_rec))+ # Provider id is part of the type so different providers don't+ # collapse into the same alarm.+ self.assertIn('test.provider', self.mapper.get_alarm_type(t_err))++ # --- create_alarm end-to-end ---++ def test_create_alarm_full_shape_for_error(self):+ t = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)+ alarm = self.mapper.create_alarm(t, max_level=AlarmLevel.CRITICAL)+ self.assertIsNotNone(alarm)+ self.assertEqual(alarm.alarm_source, AlarmSource.HEALTH_STATUS)+ self.assertEqual(alarm.alarm_level, AlarmLevel.CRITICAL)+ self.assertEqual(alarm.security_level, SecurityLevel.OFF)+ self.assertIn('Test Provider', alarm.title)+ self.assertEqual(len(alarm.sensor_response_list), 1)+ sr = alarm.sensor_response_list[0]+ self.assertEqual(sr.detail_attrs['Status'], HealthStatusType.ERROR.label)+ self.assertEqual(sr.detail_attrs['Message'], 'upstream unreachable')++ def test_create_alarm_full_shape_for_recovery(self):+ t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)+ alarm = self.mapper.create_alarm(t, max_level=AlarmLevel.CRITICAL)+ self.assertIsNotNone(alarm)+ self.assertEqual(alarm.alarm_level, AlarmLevel.INFO)+ self.assertIn('recovered', alarm.title.lower())++ def test_create_alarm_returns_none_for_suppressed_edges(self):+ for prev, curr in [+ (HealthStatusType.UNKNOWN, HealthStatusType.ERROR),+ (HealthStatusType.HEALTHY, HealthStatusType.DISABLED),+ (HealthStatusType.DISABLED, HealthStatusType.HEALTHY),+ ]:+ t = _transition(prev, curr)+ self.assertIsNone(+ self.mapper.create_alarm(t, max_level=AlarmLevel.CRITICAL),+ f'{prev} -> {curr} should produce no alarm',+ )++ def test_error_and_recovery_share_lifetime(self):+ # Recovery must not expire before the error it's resolving —+ # otherwise the user sees a bare error alert with no recovery+ # context for the rest of the error's lifetime, suggesting the+ # integration is still broken.+ t_err = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)+ t_rec = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)+ self.assertEqual(+ self.mapper.get_alarm_lifetime_secs(t_err),+ self.mapper.get_alarm_lifetime_secs(t_rec),+ )diff --git a/src/hi/apps/system/tests/test_health_status_provider_transitions.py b/src/hi/apps/system/tests/test_health_status_provider_transitions.pynew file mode 100644index 00000000..d0273e99--- /dev/null+++ b/src/hi/apps/system/tests/test_health_status_provider_transitions.py@@ -0,0 +1,94 @@+"""+Tests for the transition-dispatch behavior added to HealthStatusProvider.++We don't go through AlertManager — we patch _dispatch_transition_alarm to+record invocations and verify it's only called on real transitions and+only with the right inputs.+"""+import logging+from unittest.mock import patch++from django.test import SimpleTestCase++from hi.apps.alert.enums import AlarmLevel+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.health_status_provider import HealthStatusProvider+from hi.apps.system.provider_info import ProviderInfo++logging.disable(logging.CRITICAL)+++class _OptedOutProvider(HealthStatusProvider):+ @classmethod+ def get_provider_info(cls):+ return ProviderInfo(+ provider_id='test.opted_out',+ provider_name='Opted Out',+ description='',+ )+++class _OptedInProvider(HealthStatusProvider):+ @classmethod+ def get_provider_info(cls):+ return ProviderInfo(+ provider_id='test.opted_in',+ provider_name='Opted In',+ description='',+ )++ def alarm_ceiling(self):+ return AlarmLevel.CRITICAL+++class HealthStatusProviderTransitionDispatchTest(SimpleTestCase):++ def test_no_dispatch_on_no_op_status_set(self):+ """Setting the same status repeatedly must not fire transitions."""+ provider = _OptedInProvider()+ # Force a known starting status (UNKNOWN by default).+ provider.update_health_status(HealthStatusType.HEALTHY, 'init')++ with patch.object(_OptedInProvider, '_dispatch_transition_alarm') as mock_dispatch:+ provider.update_health_status(HealthStatusType.HEALTHY, 'still healthy')+ mock_dispatch.assert_not_called()++ def test_dispatch_on_real_transition(self):+ provider = _OptedInProvider()+ provider.update_health_status(HealthStatusType.HEALTHY, 'init')++ with patch.object(_OptedInProvider, '_dispatch_transition_alarm') as mock_dispatch:+ provider.update_health_status(HealthStatusType.ERROR, 'broken')+ mock_dispatch.assert_called_once()+ kwargs = mock_dispatch.call_args.kwargs+ self.assertEqual(kwargs['previous_status'], HealthStatusType.HEALTHY)+ self.assertEqual(kwargs['current_status'], HealthStatusType.ERROR)+ self.assertEqual(kwargs['last_message'], 'broken')++ def test_opted_out_provider_skips_alarm_path(self):+ """alarm_ceiling() returning None must short-circuit dispatch."""+ provider = _OptedOutProvider()+ provider.update_health_status(HealthStatusType.HEALTHY, 'init')++ with patch('hi.apps.alert.alert_manager.AlertManager') as mock_alert_manager:+ provider.update_health_status(HealthStatusType.ERROR, 'broken')+ # AlertManager must never be touched for opted-out providers.+ mock_alert_manager.assert_not_called()++ def test_dispatch_failure_does_not_break_health_update(self):+ """A misbehaving alarm path must not break health bookkeeping."""+ provider = _OptedInProvider()+ provider.update_health_status(HealthStatusType.HEALTHY, 'init')++ with patch.object(+ _OptedInProvider, '_dispatch_transition_alarm',+ side_effect=RuntimeError('alarm path exploded'),+ ):+ # Health bookkeeping must succeed regardless of alarm-path failure.+ try:+ provider.update_health_status(HealthStatusType.ERROR, 'broken')+ except RuntimeError:+ self.fail('update_health_status leaked an alarm-path exception')++ # Status was updated despite the alarm exception.+ self.assertEqual(provider.health_status.status, HealthStatusType.ERROR)diff --git a/src/hi/apps/weather/monitors.py b/src/hi/apps/weather/monitors.pyindex 2dc1019e..e32e9620 100644--- a/src/hi/apps/weather/monitors.py+++ b/src/hi/apps/weather/monitors.py@@ -2,6 +2,7 @@ import asyncioimport loggingimport hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.alert.enums import AlarmLevelfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.alert.alert_mixins import AlertMixin@@ -61,6 +62,15 @@ class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):expected_heartbeat_interval_secs = cls.WEATHER_POLLING_INTERVAL_SECS,)+ def alarm_ceiling(self):+ # Cap at INFO for two reasons:+ # 1. Weather staleness is informational — the user is not+ # typically depending on a 150-second freshness window.+ # 2. The monitor records WARNING during its 30-second startup-+ # safety window. Capping at INFO prevents that startup+ # transition from firing alarms on every server restart.+ return AlarmLevel.INFO+async def do_work(self):# To help guard against hitting API rate limits, hold off ondiff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.pyindex 460d8ee7..b342065f 100644--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py@@ -197,10 +197,10 @@ class TestWeatherAlertIntegration(AsyncTaskTestCase):self.run_async(test_update())# Verify alert manager was called to add alarms- self.assertEqual(mock_alert_manager.add_alarm.call_count, 2) # Only 2 should create alarms+ self.assertEqual(mock_alert_manager.add_alarm_async.call_count, 2) # Only 2 should create alarms# Verify the alarms that were created- call_args_list = mock_alert_manager.add_alarm.call_args_list+ call_args_list = mock_alert_manager.add_alarm_async.call_args_listalarm1 = call_args_list[0][0][0] # First alarmalarm2 = call_args_list[1][0][0] # Second alarmdiff --git a/src/hi/apps/weather/weather_manager.py b/src/hi/apps/weather/weather_manager.pyindex 2b5361f2..9f1addcf 100644--- a/src/hi/apps/weather/weather_manager.py+++ b/src/hi/apps/weather/weather_manager.py@@ -275,7 +275,7 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):alert_manager = await self.alert_manager_async()if alert_manager:for alarm in alarms:- await alert_manager.add_alarm(alarm)+ await alert_manager.add_alarm_async(alarm)logger.info(f'Added weather alarm to system: {alarm.signature}')else:logger.warning('Alert manager not available, weather alarms not created')diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex f2ed8db7..5b3e6c51 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -10,28 +10,29 @@ from .integration_controller import IntegrationControllerfrom .integration_manage_view_pane import IntegrationManageViewPanefrom .models import IntegrationAttributefrom .transient_models import (+ ConnectionTestResult,IntegrationMetaData,IntegrationValidationResult,)class IntegrationGateway:- """+ """Each integration needs to provide an Integration Manager that implements these methods."""def get_metadata(self) -> IntegrationMetaData:raise NotImplementedError('Subclasses must override this method')-+def get_manage_view_pane(self) -> IntegrationManageViewPane:raise NotImplementedError('Subclasses must override this method')-+def get_monitor(self) -> PeriodicMonitor:raise NotImplementedError('Subclasses must override this method')-+def get_controller(self) -> IntegrationController:raise NotImplementedError('Subclasses must override this method')-+def notify_settings_changed(self):"""This method is called when Integration or IntegrationAttribute models@@ -39,14 +40,33 @@ class IntegrationGateway:configuration and notify any dependent components."""raise NotImplementedError('Subclasses must override this method')-+def get_health_status_provider(self) -> HealthStatusProvider:raise NotImplementedError('Subclasses must override this method')-+def validate_configuration(self,integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:+ """+ Schema-only validation of the proposed configuration. Must NOT+ perform network operations. Returns success if the attribute set+ is structurally usable; returns an error otherwise. For live+ connection probing, see test_connection().+ """+ raise NotImplementedError('Subclasses must override this method')++ def test_connection(+ 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).+ """raise NotImplementedError('Subclasses must override this method')def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:diff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.pyindex 9bdf5978..b8fe2605 100644--- a/src/hi/integrations/integration_manager.py+++ b/src/hi/integrations/integration_manager.py@@ -20,6 +20,7 @@ from hi.apps.system.health_status_provider import HealthStatusProviderfrom .entity_operations import EntityIntegrationOperationsfrom .enums import IntegrationAttributeType, IntegrationDisableMode+from .exceptions import IntegrationConnectionErrorfrom .integration_data import IntegrationDatafrom .integration_gateway import IntegrationGatewayfrom .transient_models import IntegrationKey@@ -34,6 +35,13 @@ 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+ # validation or before relaunching monitors. Kept short for interactive+ # save-time UX; can be promoted to a user-tunable setting later if+ # demand emerges.+ HEALTH_CHECK_TIMEOUT_SECS = 5+def __new__(cls):return super().__new__(cls)@@ -444,10 +452,48 @@ class IntegrationManager( Singleton ):failed launch can be retried by invoking resume again._launch_integration_monitor_task is idempotent when the monitor isalready running.++ Probes upstream connectivity via the gateway's test_connection+ before relaunching, so we fail fast (with a meaningful error to+ the caller) rather than spinning up monitors that will immediately+ error against an unreachable service. Raises+ IntegrationConnectionError on probe failure.++ The probe runs OUTSIDE the data lock — we don't want to hold the+ lock for ~5 seconds while a network probe is in flight, since+ that would block all other lifecycle operations on every+ integration. The trade-off is a TOCTOU window between the+ outside-lock is_enabled check and the inside-lock state write:+ another caller could disable_integration() during the probe.+ We close that window by re-checking is_enabled inside the lock+ and aborting if the integration was disabled while we probed."""if not integration_data.integration.is_enabled:return++ integration_attributes = list(+ integration_data.integration.attributes.all()+ )+ test_result = integration_data.integration_gateway.test_connection(+ 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.'+ )+with self._data_lock:+ # Re-check is_enabled inside the lock to close the TOCTOU+ # window opened by running the probe lock-free above. If+ # another caller disabled the integration while we were+ # probing, abandon the resume — surfacing the cause to the+ # caller so the UI can communicate why nothing happened.+ integration_data.integration.refresh_from_db()+ if not integration_data.integration.is_enabled:+ raise IntegrationConnectionError(+ 'Integration was disabled while resume was probing upstream.'+ )with transaction.atomic():integration_data.integration.is_paused = Falseintegration_data.integration.save()diff --git a/src/hi/integrations/templates/integrations/pages/integration_manage.html b/src/hi/integrations/templates/integrations/pages/integration_manage.htmlindex ad8ad2e7..20b9a864 100644--- a/src/hi/integrations/templates/integrations/pages/integration_manage.html+++ b/src/hi/integrations/templates/integrations/pages/integration_manage.html@@ -24,11 +24,7 @@{{ integration_data.label }}</span>{% with health_status=integration_data.integration_gateway.get_health_status_provider.health_status %}- {% if health_status.is_error %}- <span class="text-danger">- {% icon "warning" size="lg" css_class="mr-1" %}- </span>- {% endif %}+ {% include "integrations/panes/integration_status_indicator.html" with health_status=health_status is_paused=integration_data.integration.is_paused %}{% endwith %}</div></a>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 88703c0b..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@@ -19,16 +19,7 @@class="btn btn-link p-0 d-flex align-items-center text-decoration-none"data-async="modal"title="View health status details">- <!-- Health status badge -->- <button class="btn btn-sm {% if health_status.is_healthy %}btn-outline-primary{% elif health_status.is_critical %}btn-danger{% else %}btn-warning{% endif %}">- {% if health_status.is_healthy %}- {% icon "check-circle" size="mdm" css_class="mr-1" %}Healthy- {% elif health_status.is_critical %}- {% icon "warning" size="md" css_class="mr-1" %}Error- {% else %}- {% icon "info-circle" size="md" css_class="mr-1" %}Warning- {% endif %}- </button>+ {% include "system/panes/health_status_badge.html" with health_status=health_status %}</a></div>{% endif %}diff --git a/src/hi/integrations/templates/integrations/panes/integration_status_indicator.html b/src/hi/integrations/templates/integrations/panes/integration_status_indicator.htmlnew file mode 100644index 00000000..5120fe09--- /dev/null+++ b/src/hi/integrations/templates/integrations/panes/integration_status_indicator.html@@ -0,0 +1,46 @@+{% load icons %}+{% comment %}+Compact integration-status indicator — small icon + tooltip, no label.+Composes HealthStatus and the integration's is_paused flag into a+single attention-grabbing glyph for the sidebar nav-tab.++Parameters:+ health_status : HealthStatus instance (required).+ is_paused : bool — integration's is_paused flag (required).++Visual priority (worst-of):+ ERROR > WARNING > paused+HEALTHY-and-not-paused renders nothing — sidebar should be visually+clean when there is nothing to draw the operator's attention to.++DISABLED is intentionally not handled — disabled integrations are+excluded from the sidebar tab list upstream.++UNKNOWN is intentionally not handled — initialization edge, transient.+{% endcomment %}+{% if health_status %}+{% with status=health_status.status %}+{% if status.is_critical %}+ <span class="hi-integration-indicator hi-integration-indicator-error"+ role="img"+ aria-label="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}"+ title="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}">+ {% icon "warning" size="md" %}+ </span>+{% elif status.is_warning %}+ <span class="hi-integration-indicator hi-integration-indicator-warning"+ role="img"+ aria-label="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}"+ title="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}">+ {% icon "warning" size="sm" %}+ </span>+{% elif is_paused %}+ <span class="hi-integration-indicator hi-integration-indicator-paused"+ role="img"+ aria-label="Paused — background monitor is suspended"+ title="Paused — background monitor is suspended">+ {% icon "pause" size="sm" %}+ </span>+{% endif %}+{% endwith %}+{% endif %}diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.pyindex 808ff618..f2cfdd61 100644--- a/src/hi/integrations/tests/test_integration_manager.py+++ b/src/hi/integrations/tests/test_integration_manager.py@@ -11,11 +11,16 @@ from django.test import TestCasefrom hi.apps.attribute.enums import AttributeType, AttributeValueTypefrom hi.apps.entity.models import Entity, EntityAttribute+from hi.integrations.exceptions import IntegrationConnectionErrorfrom hi.integrations.integration_manager import IntegrationManagerfrom hi.integrations.integration_data import IntegrationDatafrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.models import Integration, IntegrationAttribute-from hi.integrations.transient_models import IntegrationMetaData, IntegrationKey+from hi.integrations.transient_models import (+ ConnectionTestResult,+ IntegrationMetaData,+ IntegrationKey,+)from hi.integrations.enums import IntegrationAttributeType, IntegrationDisableModelogging.disable(logging.CRITICAL)@@ -29,11 +34,18 @@ class MockIntegrationAttributeType(IntegrationAttributeType):class MockIntegrationGateway(IntegrationGateway):"""Mock integration gateway for testing."""-- def __init__(self, integration_id='test_integration', label='Test Integration'):++ def __init__(self, integration_id='test_integration', label='Test Integration',+ connection_test_result=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.+ self.connection_test_result = (+ connection_test_result if connection_test_result is not None+ else ConnectionTestResult.success()+ )+def get_metadata(self):return IntegrationMetaData(integration_id=self.integration_id,@@ -41,16 +53,19 @@ class MockIntegrationGateway(IntegrationGateway):attribute_type=MockIntegrationAttributeType,allow_entity_deletion=True)-+def get_manage_view_pane(self):return Mock()-+def get_monitor(self):return Mock()-+def get_controller(self):return Mock()+ def test_connection(self, integration_attributes, timeout_secs):+ return self.connection_test_result+class IntegrationManagerTestCase(TestCase):"""Test cases for IntegrationManager singleton behavior and core functionality."""@@ -809,6 +824,106 @@ class IntegrationManagerTestCase(TestCase):mock_launch.assert_called_once_with(integration_data=data)+ def test_resume_integration_short_circuits_when_connection_test_fails(self):+ """Resume must not relaunch monitors when the connection probe fails.++ Without this short-circuit a paused integration could be resumed+ against an unreachable upstream and silently fail in the background.+ """+ manager = IntegrationManager()+ manager.reset_for_testing()++ integration = Integration.objects.create(+ integration_id='resume_probe_fail',+ is_enabled=True,+ is_paused=True,+ )+ gateway = MockIntegrationGateway(+ 'resume_probe_fail',+ connection_test_result=ConnectionTestResult.failure(+ 'Cannot reach upstream'+ ),+ )+ data = IntegrationData(integration_gateway=gateway, integration=integration)++ with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:+ with self.assertRaises(IntegrationConnectionError) as context:+ manager.resume_integration(data)++ self.assertIn('Cannot reach upstream', str(context.exception))+ mock_launch.assert_not_called()++ # is_paused state must NOT have been flipped to False.+ integration.refresh_from_db()+ 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."""+ manager = IntegrationManager()+ manager.reset_for_testing()++ integration = Integration.objects.create(+ integration_id='resume_timeout_test',+ is_enabled=True,+ is_paused=True,+ )+ gateway = MockIntegrationGateway('resume_timeout_test')+ data = IntegrationData(integration_gateway=gateway, integration=integration)++ with patch.object(gateway, 'test_connection',+ return_value=ConnectionTestResult.success()) as mock_probe:+ with patch.object(manager, '_launch_integration_monitor_task'):+ manager.resume_integration(data)++ mock_probe.assert_called_once()+ kwargs = mock_probe.call_args.kwargs+ self.assertEqual(kwargs['timeout_secs'],+ IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS)++ def test_resume_integration_aborts_when_disabled_during_probe(self):+ """+ TOCTOU close-out: if another caller disables the integration+ while resume_integration is running its lock-free probe, the+ post-probe state mutation must be abandoned (no monitor launch,+ is_paused not flipped) and the caller must be told why.+ """+ manager = IntegrationManager()+ manager.reset_for_testing()++ integration = Integration.objects.create(+ integration_id='resume_toctou_test',+ is_enabled=True,+ is_paused=True,+ )+ gateway = MockIntegrationGateway('resume_toctou_test')+ 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+ # 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.+ def disable_during_probe(*args, **kwargs):+ integration.is_enabled = False+ integration.save()+ return ConnectionTestResult.success()++ with patch.object(gateway, 'test_connection',+ side_effect=disable_during_probe):+ with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:+ with self.assertRaises(IntegrationConnectionError) as context:+ manager.resume_integration(data)++ self.assertIn('disabled while resume was probing',+ str(context.exception))+ mock_launch.assert_not_called()++ # is_paused must NOT have been flipped — disable_integration is+ # responsible for the disabled-state cleanup, not us.+ integration.refresh_from_db()+ self.assertTrue(integration.is_paused)+ self.assertFalse(integration.is_enabled)+def test_data_lock_thread_safety_during_attribute_creation(self):"""Test thread safety of attribute creation operations."""diff --git a/src/hi/integrations/tests/test_view_mixins.py b/src/hi/integrations/tests/test_view_mixins.pynew file mode 100644index 00000000..bc2f01e3--- /dev/null+++ b/src/hi/integrations/tests/test_view_mixins.py@@ -0,0 +1,152 @@+"""+Tests for IntegrationViewMixin.validate_attributes_extra_helper, the+two-stage save-time validation entry point.++Stage 1: gateway.validate_configuration (schema-only, fast, offline)+Stage 2: gateway.test_connection (live probe, bounded timeout)++Both stages must surface their failure inline as a non-form error so the+user sees the cause without a silent save followed by a delayed background+error.+"""++import logging+from unittest.mock import Mock++from django.test import SimpleTestCase++from hi.apps.system.enums import HealthStatusType+from hi.integrations.integration_manager import IntegrationManager+from hi.integrations.transient_models import (+ ConnectionTestResult,+ IntegrationValidationResult,+)+from hi.integrations.view_mixins import IntegrationViewMixin++logging.disable(logging.CRITICAL)+++def _build_formset(form_data_list):+ """+ Build a fake formset that the helper can iterate. Each entry in+ form_data_list maps to a single 'form' with cleaned_data.+ """+ formset = Mock()+ formset._non_form_errors = []+ forms = []+ for cleaned_data in form_data_list:+ form = Mock()+ form.cleaned_data = cleaned_data+ form.instance = Mock()+ form.instance.value = ''+ forms.append(form)+ formset.__iter__ = lambda self: iter(forms)+ return formset+++def _build_attr_item_context(gateway):+ integration_data = Mock()+ integration_data.integration_gateway = gateway+ attr_item_context = Mock()+ attr_item_context.integration_data = integration_data+ return attr_item_context+++class ValidateAttributesExtraHelperTest(SimpleTestCase):++ def setUp(self):+ self.mixin = IntegrationViewMixin()++ def test_success_path_runs_both_stages(self):+ """Both stages succeed → no errors appended to the formset."""+ gateway = Mock()+ gateway.validate_configuration.return_value = (+ IntegrationValidationResult.success()+ )+ gateway.test_connection.return_value = ConnectionTestResult.success()++ formset = _build_formset([{'value': 'token'}])+ ctx = _build_attr_item_context(gateway)++ self.mixin.validate_attributes_extra_helper(+ attr_item_context=ctx,+ regular_attributes_formset=formset,+ error_title='Test',+ )++ 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+ self.assertEqual(kwargs['timeout_secs'],+ IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS)++ def test_schema_failure_short_circuits_before_connection_probe(self):+ """Stage 1 failure must skip Stage 2 entirely (no network)."""+ gateway = Mock()+ gateway.validate_configuration.return_value = (+ IntegrationValidationResult.error(+ status=HealthStatusType.ERROR,+ error_message='Missing API URL',+ )+ )++ formset = _build_formset([{'value': ''}])+ ctx = _build_attr_item_context(gateway)++ self.mixin.validate_attributes_extra_helper(+ attr_item_context=ctx,+ regular_attributes_formset=formset,+ error_title='Test',+ )++ gateway.test_connection.assert_not_called()+ self.assertEqual(len(formset._non_form_errors), 1)+ self.assertIn('Missing API URL', formset._non_form_errors[0])++ def test_connection_failure_after_schema_success_appends_error(self):+ """Stage 1 passes, Stage 2 fails → its message surfaces inline."""+ gateway = Mock()+ gateway.validate_configuration.return_value = (+ IntegrationValidationResult.success()+ )+ gateway.test_connection.return_value = ConnectionTestResult.failure(+ 'Cannot connect to upstream'+ )++ formset = _build_formset([{'value': 'token'}])+ ctx = _build_attr_item_context(gateway)++ self.mixin.validate_attributes_extra_helper(+ attr_item_context=ctx,+ regular_attributes_formset=formset,+ error_title='Test',+ )++ gateway.test_connection.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+ contracts to convert internal exceptions into result objects+ (IntegrationValidationResult.error / ConnectionTestResult.failure).+ If a gateway impl is buggy and throws anyway, the helper does NOT+ coerce that exception into a form-level error — it lets the+ exception propagate so the bug surfaces through Django's error+ pipeline rather than being silently masked as a connection+ failure.+ """+ gateway = Mock()+ gateway.validate_configuration.side_effect = RuntimeError('boom')++ formset = _build_formset([{'value': 'token'}])+ ctx = _build_attr_item_context(gateway)++ with self.assertRaises(RuntimeError):+ self.mixin.validate_attributes_extra_helper(+ attr_item_context=ctx,+ regular_attributes_formset=formset,+ error_title='Test',+ )diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.pyindex eb371d9e..db48325d 100644--- a/src/hi/integrations/transient_models.py+++ b/src/hi/integrations/transient_models.py@@ -103,6 +103,29 @@ class IntegrationRemovalSummary:return self.user_data_count > 0+@dataclass+class ConnectionTestResult:+ """+ Result from a live integration connection probe.++ Distinct from IntegrationValidationResult, which represents schema-level+ validation outcomes. ConnectionTestResult specifically reports whether+ a network probe against the proposed configuration succeeded within a+ bounded timeout.+ """++ is_success : bool+ message : Optional[str] = None++ @classmethod+ def success(cls, message: Optional[str] = None) -> 'ConnectionTestResult':+ return cls(is_success=True, message=message)++ @classmethod+ def failure(cls, message: str) -> 'ConnectionTestResult':+ return cls(is_success=False, message=message)++@dataclassclass IntegrationValidationResult:"""Result from integration configuration validation."""diff --git a/src/hi/integrations/view_mixins.py b/src/hi/integrations/view_mixins.pyindex 1b7572b8..20e6bdc8 100644--- a/src/hi/integrations/view_mixins.py+++ b/src/hi/integrations/view_mixins.py@@ -23,35 +23,61 @@ class IntegrationViewMixin:attr_item_context,regular_attributes_formset,error_title ):- """Validate API connectivity before enabling integration."""- # Get the integration data from the context+ """+ 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+ unreachable upstream / bad credentials so the user sees the+ specific reason inline rather than experiencing a silent+ save followed by a delayed background error.++ Both gateway methods are required by their contracts to never+ throw — they convert any internal exception into the appropriate+ result type (IntegrationValidationResult.error /+ ConnectionTestResult.failure) carrying a human-readable message.+ We deliberately do NOT wrap their invocations in a broad try/+ except here: doing so would coerce the gateway's specific+ failure message into a generic catch-all string, and would also+ hide genuine programming bugs (which should surface through+ Django's error pipeline rather than be silently translated into+ a form-level error).+ """integration_data = attr_item_context.integration_data-- try:- # Get current attribute values from the formset- integration_attributes = []- for form in regular_attributes_formset:- if form.cleaned_data and not form.cleaned_data.get('DELETE', False):- # Create a temporary attribute-like object with the form data- attr_instance = form.instance- attr_instance.value = form.cleaned_data.get('value', '')- integration_attributes.append(attr_instance)-- validation_result = integration_data.integration_gateway.validate_configuration(- integration_attributes+ gateway = integration_data.integration_gateway++ # Get current attribute values from the formset+ integration_attributes = []+ for form in regular_attributes_formset:+ if form.cleaned_data and not form.cleaned_data.get('DELETE', False):+ # Create a temporary attribute-like object with the form data+ attr_instance = form.instance+ attr_instance.value = form.cleaned_data.get('value', '')+ integration_attributes.append(attr_instance)++ # Stage 1: schema-only validation.+ validation_result = gateway.validate_configuration(+ integration_attributes+ )+ if not validation_result.is_valid:+ error_message = validation_result.error_message or 'Configuration is invalid'+ regular_attributes_formset._non_form_errors.append(+ f'{error_title}: {error_message}')+ return- if not validation_result.is_valid:- error_message = validation_result.error_message or 'API validation failed'- regular_attributes_formset._non_form_errors.append(- f'{error_title}: {error_message}'- )-- except Exception as e:- error_message = f'API validation error: {e}'+ # Stage 2: live connection probe with bounded timeout.+ test_result = gateway.test_connection(+ 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'regular_attributes_formset._non_form_errors.append(f'{error_title}: {error_message}')+ returndiff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.pyindex d1b65b1c..7eaf290e 100644--- a/src/hi/integrations/views.py+++ b/src/hi/integrations/views.py@@ -16,6 +16,7 @@ from hi.apps.config.views import ConfigPageViewfrom .entity_operations import EntityIntegrationOperationsfrom .enums import IntegrationDisableMode+from .exceptions import IntegrationConnectionErrorfrom .integration_attribute_edit_context import IntegrationAttributeItemEditContextfrom .integration_manager import IntegrationManagerfrom .models import IntegrationAttribute@@ -219,7 +220,12 @@ class IntegrationResumeView( View, IntegrationViewMixin ):if not integration_data.integration.is_enabled:raise BadRequest( f'{integration_data.label} integration is not configured' )- IntegrationManager().resume_integration( integration_data = integration_data )+ try:+ IntegrationManager().resume_integration( integration_data = integration_data )+ except IntegrationConnectionError as e:+ raise BadRequest(+ f'{integration_data.label} could not resume: {e}'+ )redirect_url = reverse( 'integrations_manage',kwargs = { 'integration_id': integration_id } )diff --git a/src/hi/services/hass/hass_client.py b/src/hi/services/hass/hass_client.pyindex 28e22d42..15f7103e 100644--- a/src/hi/services/hass/hass_client.py+++ b/src/hi/services/hass/hass_client.py@@ -1,7 +1,7 @@import jsonimport loggingfrom requests import get, post-from typing import Dict, List+from typing import Dict, List, Optionalfrom .hass_converter import HassConverterfrom .hass_models import HassState@@ -12,37 +12,87 @@ logger = logging.getLogger(__name__)class HassClient:# Docs: https://developers.home-assistant.io/docs/api/rest/-+API_BASE_URL = 'api_base_url'API_TOKEN = 'api_token'+ DEFAULT_TIMEOUT = 25.0+TRACE = False # For debugging- def __init__( self, api_options : Dict[ str, str ] ):+ def __init__( self, api_options : Dict[ str, str ], timeout_secs : Optional[float] = None ):self._api_base_url = api_options.get( self.API_BASE_URL )assert self._api_base_url is not Noneif self._api_base_url[-1] == '/':self._api_base_url = self._api_base_url[0:-1]-+token = api_options.get( self.API_TOKEN )assert token is not None-+self._headers = {'Authorization': f'Bearer {token}','content-type':'application/json',}++ # Per-instance timeout. Defaults to DEFAULT_TIMEOUT; the+ # connection-test path passes a tighter bound for save-time+ # interactive validation.+ self._timeout_secs = timeout_secs if timeout_secs is not None else self.DEFAULT_TIMEOUTreturndef states(self) -> List[ HassState ]:url = f'{self._api_base_url}/api/states'- response = get( url, headers = self._headers, timeout = 25.0 )- data = json.loads(response.text)+ response = get( url, headers = self._headers, timeout = self._timeout_secs )+ if response.status_code not in (200, 201):+ raise ValueError(+ f'HASS states fetch failed: {response.status_code} {response.text}'+ )+ content_type = response.headers.get('content-type', '')+ if 'json' not in content_type.lower():+ raise ValueError(+ f'HASS API URL may be incorrect. Expected JSON response but '+ f'received {content_type or "unknown content type"}. '+ f'Ensure the URL points at the HASS API root.'+ )+ try:+ data = json.loads(response.text)+ except json.JSONDecodeError as e:+ raise ValueError(+ f'HASS states response was not valid JSON: {e}'+ ) from eif self.TRACE:logger.debug( f'HAss Response = {response.text}' )return [ HassConverter.create_hass_state(x) for x in data ]+ def ping(self) -> None:+ """+ Lightweight reachability probe. Hits the HASS root API endpoint+ which authenticates the bearer token and confirms the service is+ responding without fetching the full states payload.++ Also validates that the response body is JSON-shaped. A 200 with+ an HTML body means we are talking to something that is not the+ HASS API (misconfigured proxy, captive portal, wrong base URL),+ and we want test_connection to fail at save time rather than+ letting the runtime sync path JSONDecodeError later.+ """+ url = f'{self._api_base_url}/api/'+ response = get( url, headers = self._headers, timeout = self._timeout_secs )+ if response.status_code not in (200, 201):+ raise ValueError(+ f'HASS ping failed: {response.status_code} {response.text}'+ )+ content_type = response.headers.get('content-type', '')+ if 'json' not in content_type.lower():+ raise ValueError(+ f'HASS API URL may be incorrect. Expected JSON response but '+ f'received {content_type or "unknown content type"}. '+ f'Ensure the URL points at the HASS API root.'+ )+ return+def set_state( self, entity_id: str, state: str, attributes: dict = None ) -> dict:url = f'{self._api_base_url}/api/states/{entity_id}'@@ -51,10 +101,20 @@ class HassClient:}if attributes:data["attributes"] = attributes- response = post( url, json = data, headers = self._headers, timeout = 25.0 )+ response = post( url, json = data, headers = self._headers, timeout = self._timeout_secs )if response.status_code != 200:raise ValueError( f"Failed to set state: {response.status_code} {response.text}" )-++ # Guard against the wrong-base-URL / misconfigured-proxy case+ # where the upstream returns 200 with non-JSON. Without this,+ # response.json() would raise an opaque JSONDecodeError.+ content_type = response.headers.get('content-type', '')+ if 'json' not in content_type.lower():+ raise ValueError(+ f'HASS API URL may be incorrect. Expected JSON response but '+ f'received {content_type or "unknown content type"}. '+ f'Ensure the URL points at the HASS API root.'+ )return response.json()def call_service( self, domain: str, service: str, hass_state_id: str, service_data: dict = None ):@@ -77,10 +137,22 @@ class HassClient:if service_data:data.update(service_data)- response = post( url, json = data, headers = self._headers, timeout = 25.0 )+ response = post( url, json = data, headers = self._headers, timeout = self._timeout_secs )if response.status_code not in [200, 201]:raise ValueError( f"Failed to call service: {response.status_code} {response.text}" )-++ # Guard against the wrong-base-URL / misconfigured-proxy case+ # where the upstream returns a 2xx with non-JSON. Callers that+ # parse the response (e.g., HassController) would otherwise hit+ # an opaque JSONDecodeError downstream.+ content_type = response.headers.get('content-type', '') if response.headers else ''+ if 'json' not in content_type.lower():+ raise ValueError(+ f'HASS API URL may be incorrect. Expected JSON response but '+ f'received {content_type or "unknown content type"}. '+ f'Ensure the URL points at the HASS API root.'+ )+logger.debug( f'HAss call_service: {domain}.{service} for {hass_state_id}, response={response.status_code}' )return responsediff --git a/src/hi/services/hass/hass_client_factory.py b/src/hi/services/hass/hass_client_factory.pyindex f0824b03..8523355b 100644--- a/src/hi/services/hass/hass_client_factory.py+++ b/src/hi/services/hass/hass_client_factory.py@@ -1,7 +1,7 @@"""Factory for creating and testing Home Assistant API clients."""import logging-from typing import Dict+from typing import Dict, Optionalfrom hi.apps.system.enums import HealthStatusType@@ -21,7 +21,8 @@ class HassClientFactory:def create_client(self,- hass_attr_type_to_attribute: Dict[HassAttributeType, IntegrationAttribute]) -> HassClient:+ hass_attr_type_to_attribute: Dict[HassAttributeType, IntegrationAttribute],+ timeout_secs: Optional[float] = None) -> HassClient:"""Create a HassClient from integration attributes.@@ -65,7 +66,7 @@ class HassClientFactory:api_options[options_key] = hass_attr.valuelogger.debug(f'Home Assistant client options: {api_options}')- return HassClient(api_options=api_options)+ return HassClient(api_options=api_options, timeout_secs=timeout_secs)def test_client(self, client: HassClient) -> IntegrationValidationResult:"""@@ -78,16 +79,11 @@ class HassClientFactory:IntegrationValidationResult indicating success or failure with details"""try:- # Test basic API connectivity- states = client.states()- if states is not None:- # Successful API call- return IntegrationValidationResult.success()- else:- return IntegrationValidationResult.error(- status=HealthStatusType.ERROR,- error_message='Failed to fetch states from Home Assistant API'- )+ # Lightweight reachability probe — confirms the bearer token+ # is valid and the server is responding without fetching the+ # full states payload.+ client.ping()+ return IntegrationValidationResult.success()except Exception as e:error_msg = str(e).lower()diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.pyindex 0e1c244a..71061853 100644--- a/src/hi/services/hass/hass_manager.py+++ b/src/hi/services/hass/hass_manager.py@@ -1,6 +1,6 @@import loggingfrom asgiref.sync import sync_to_async-from typing import Dict, List+from typing import Dict, List, Optionalfrom hi.apps.common.singleton_manager import SingletonManagerfrom hi.apps.common.utils import str_to_bool@@ -15,6 +15,7 @@ from hi.integrations.exceptions import (IntegrationDisabledError,)from hi.integrations.transient_models import (+ ConnectionTestResult,IntegrationKey,IntegrationValidationResult,)@@ -186,28 +187,6 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProthread_sensitive=True)(verbose=verbose)- def test_connection(self) -> bool:- """Test the connection to HASS API and update health status."""- try:- if not self.hass_client:- self.record_error("HASS client not configured")- return False-- # Try to fetch states to test connection- states = self.fetch_hass_states_from_api(verbose=False)- if states is not None:- self.record_healthy('OK')- return True- else:- self.record_error("Failed to fetch states from HASS API")- return False-- except Exception as e:- error_msg = f'Connection test failed: {e}'- logger.debug(error_msg)- self.record_error( f"Connection error: {error_msg}" )- return False-def test_client_with_attributes(self,hass_attr_type_to_attribute: Dict[HassAttributeType, IntegrationAttribute]@@ -242,30 +221,61 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProself,integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:"""- Validate HASS configuration using provided attributes.-- Args:- integration_attributes: List of IntegrationAttribute objects-- Returns:- IntegrationValidationResult with validation results+ Schema-only validation. Confirms required attributes are present+ and structurally usable. Does NOT touch the network — for live+ connection probing, see test_connection()."""try:- # Build attribute mapping without enforcing requirements (for validation testing)- hass_attr_type_to_attribute = self._build_hass_attr_type_to_attribute_map(+ self._build_hass_attr_type_to_attribute_map(integration_attributes=integration_attributes,- enforce_requirements=False+ enforce_requirements=True,)+ return IntegrationValidationResult.success()- # Use existing test method- return self.test_client_with_attributes(hass_attr_type_to_attribute)-+ except IntegrationAttributeError as e:+ return IntegrationValidationResult.error(+ status=HealthStatusType.ERROR,+ error_message=str(e),+ )except Exception as e:logger.exception(f'Error in HASS configuration validation: {e}')return IntegrationValidationResult.error(status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')++ def test_connection(+ self,+ integration_attributes: List[IntegrationAttribute],+ timeout_secs: Optional[float]) -> ConnectionTestResult:+ """+ Live connection probe with bounded timeout. Builds a temporary+ HassClient against the proposed attributes and exercises the+ lightweight `/api/` ping endpoint.+ """+ try:+ hass_attr_type_to_attribute = self._build_hass_attr_type_to_attribute_map(+ integration_attributes=integration_attributes,+ enforce_requirements=True,+ )+ temp_client = self._client_factory.create_client(+ hass_attr_type_to_attribute=hass_attr_type_to_attribute,+ timeout_secs=timeout_secs,+ )+ validation_result = self._client_factory.test_client(temp_client)+ if validation_result.is_valid:+ return ConnectionTestResult.success()+ return ConnectionTestResult.failure(+ validation_result.error_message or 'Connection test failed'+ )++ except IntegrationAttributeError as e:+ return ConnectionTestResult.failure(str(e))+ except 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}')def _build_hass_attr_type_to_attribute_map(self,diff --git a/src/hi/services/hass/integration.py b/src/hi/services/hass/integration.pyindex 8188d1b9..da733623 100644--- a/src/hi/services/hass/integration.py+++ b/src/hi/services/hass/integration.py@@ -1,5 +1,5 @@import logging-from typing import List+from typing import List, Optionalfrom hi.apps.system.enums import HealthStatusTypefrom hi.apps.system.health_status_provider import HealthStatusProvider@@ -8,7 +8,11 @@ from hi.integrations.integration_controller import IntegrationControllerfrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manage_view_pane import IntegrationManageViewPanefrom hi.integrations.models import IntegrationAttribute-from hi.integrations.transient_models import IntegrationMetaData, IntegrationValidationResult+from hi.integrations.transient_models import (+ ConnectionTestResult,+ IntegrationMetaData,+ IntegrationValidationResult,+)from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom .hass_controller import HassController@@ -52,10 +56,7 @@ class HassGateway( IntegrationGateway ):def validate_configuration(self, integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:- """Validate HASS integration configuration by testing API connectivity.-- Delegates to HassManager for configuration validation.- """+ """Schema-only validation; delegates to HassManager."""try:hass_manager = HassManager()return hass_manager.validate_configuration(integration_attributes)@@ -65,3 +66,19 @@ class HassGateway( IntegrationGateway ):status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')++ def test_connection(+ self,+ integration_attributes: List[IntegrationAttribute],+ timeout_secs: Optional[float],+ ) -> ConnectionTestResult:+ """Live connection probe; delegates to HassManager."""+ try:+ hass_manager = HassManager()+ return hass_manager.test_connection(+ 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}')diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.pyindex 2e27dc01..37672b59 100644--- a/src/hi/services/hass/monitors.py+++ b/src/hi/services/hass/monitors.py@@ -1,6 +1,7 @@import loggingimport hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.alert.enums import AlarmLevelfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.sensor_response_manager import SensorResponseMixinfrom hi.apps.sense.transient_models import SensorResponse@@ -29,12 +30,22 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):def get_api_timeout(self) -> float:return self.HASS_API_TIMEOUT_SECS+ def alarm_ceiling(self):+ # HA outage in the background masks security and home-automation+ # state changes. Treat health failures here as serious.+ return AlarmLevel.CRITICAL+async def _initialize(self):hass_manager = await self.hass_manager_async()if not hass_manager:return_ = await self.sensor_response_manager_async() # Allows async use of self.sensor_response_manager()hass_manager.register_change_listener( self.refresh )+ # Register this monitor as a subordinate health source on the+ # manager so the manager's aggregated health reflects monitor+ # outcomes. The manager pulls our current status on each read of+ # its health_status; we never push.+ hass_manager.add_subordinate_health_status_provider( self )self._was_initialized = Truereturn@@ -100,6 +111,7 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):message = f'Processed {len(id_to_hass_state_map)} Home Assistant states.'self.record_healthy( message )- hass_manager.record_healthy( message )+ # Manager picks up our status via add_subordinate_health_status_provider+ # registration; no explicit push needed here.returndiff --git a/src/hi/services/hass/tests/test_hass_client.py b/src/hi/services/hass/tests/test_hass_client.pyindex dfd59010..8934b513 100644--- a/src/hi/services/hass/tests/test_hass_client.py+++ b/src/hi/services/hass/tests/test_hass_client.py@@ -91,6 +91,8 @@ class TestHassClientStatesMethod(TestCase):"""Test states() returns empty list when HASS returns no entities"""with patch('hi.services.hass.hass_client.get') as mock_get:mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = '[]'mock_get.return_value = mock_response@@ -108,11 +110,13 @@ class TestHassClientStatesMethod(TestCase):with patch('hi.services.hass.hass_client.get') as mock_get:mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = json.dumps(real_hass_data)mock_get.return_value = mock_response-+result = self.client.states()-+# Verify data transformation qualityself.assertEqual(len(result), len(real_hass_data))self.assertIsInstance(result, list)@@ -136,18 +140,47 @@ class TestHassClientStatesMethod(TestCase):with self.assertRaises(ConnectionError):self.client.states()- def test_states_propagates_json_decode_errors(self):- """Test states() properly propagates JSON parsing errors with context"""+ def test_states_raises_value_error_on_malformed_json(self):+ """A 200 with content-type=json but a malformed body must surface+ as a ValueError so the monitor can record a meaningful error+ instead of an opaque JSONDecodeError traceback."""with patch('hi.services.hass.hass_client.get') as mock_get:mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = 'invalid json {"incomplete"'mock_get.return_value = mock_response-- with self.assertRaises(json.JSONDecodeError) as context:++ with self.assertRaises(ValueError) as context:self.client.states()-- # Verify the error provides useful information for debugging- self.assertIn('Expecting', str(context.exception))++ self.assertIn('not valid JSON', str(context.exception))++ def test_states_raises_value_error_on_non_2xx(self):+ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.status_code = 500+ mock_response.text = 'Internal Server Error'+ mock_get.return_value = mock_response++ with self.assertRaises(ValueError) as context:+ self.client.states()+ self.assertIn('500', str(context.exception))++ def test_states_raises_value_error_on_non_json_content_type(self):+ """Mirrors ping() — a 200 with HTML body means we are not talking+ to the HASS API; surface that as a clear error instead of letting+ json.loads raise."""+ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'text/html'}+ mock_response.text = '<html><body>not the API</body></html>'+ mock_get.return_value = mock_response++ with self.assertRaises(ValueError) as context:+ self.client.states()+ self.assertIn('URL may be incorrect', str(context.exception))def test_states_handles_single_entity_response(self):"""Test states() correctly processes single entity response"""@@ -162,11 +195,13 @@ class TestHassClientStatesMethod(TestCase):with patch('hi.services.hass.hass_client.get') as mock_get:mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = json.dumps([single_entity])mock_get.return_value = mock_response-+result = self.client.states()-+self.assertEqual(len(result), 1)state = result[0]self.assertEqual(state.entity_id, 'sensor.temperature')@@ -192,6 +227,8 @@ class TestHassClientStatesMethod(TestCase):with patch('hi.services.hass.hass_client.get') as mock_get:mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = json.dumps([sample_entity])mock_get.return_value = mock_response@@ -230,9 +267,10 @@ class TestHassClientSetStateMethod(TestCase):mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.json.return_value = expected_response_datamock_post.return_value = mock_response-+result = self.client.set_state('light.living_room', 'on')# Test the actual return value, not the mock call@@ -259,9 +297,10 @@ class TestHassClientSetStateMethod(TestCase):mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.json.return_value = expected_responsemock_post.return_value = mock_response-+result = self.client.set_state('light.living_room', 'on', input_attributes)# Test that attributes are preserved in the response@@ -319,12 +358,14 @@ class TestHassClientSetStateMethod(TestCase):@patch('hi.services.hass.hass_client.post')def test_set_state_json_response_parsing_error(self, mock_post):"""Test set_state handles JSON response parsing errors"""- # Mock response with invalid JSON+ # Mock response with invalid JSON. Content-type advertises JSON+ # so the upstream-mismatch guard passes and json() is reached.mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.json.side_effect = json.JSONDecodeError("Invalid JSON", "", 0)mock_post.return_value = mock_response-+with self.assertRaises(json.JSONDecodeError):self.client.set_state('light.living_room', 'on')@@ -363,6 +404,7 @@ class TestHassClientCallServiceMethod(TestCase):"""Test call_service properly merges entity_id with additional service data"""mock_response = Mock()mock_response.status_code = 201 # Test that 201 is also accepted+ mock_response.headers = {'content-type': 'application/json'}mock_post.return_value = mock_responseservice_data = {'brightness': 255, 'color_temp': 300}@@ -428,15 +470,17 @@ class TestHassClientCallServiceMethod(TestCase):# Test 200 responsemock_response_200 = Mock()mock_response_200.status_code = 200+ mock_response_200.headers = {'content-type': 'application/json'}mock_post.return_value = mock_response_200-+result1 = self.client.call_service('light', 'turn_on', 'light.living_room')self.assertEqual(result1, mock_response_200)self.assertEqual(result1.status_code, 200)-+# Test 201 responsemock_response_201 = Mock()mock_response_201.status_code = 201+ mock_response_201.headers = {'content-type': 'application/json'}mock_post.return_value = mock_response_201result2 = self.client.call_service('light', 'turn_off', 'light.living_room')@@ -452,6 +496,7 @@ class TestHassClientCallServiceMethod(TestCase):"""Test call_service works correctly when service_data is None or empty"""mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_post.return_value = mock_response# Test with None service_data@@ -476,6 +521,7 @@ class TestHassClientCallServiceMethod(TestCase):"""Test call_service builds correct URLs for different domain/service combinations"""mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_post.return_value = mock_response# Test URL construction for different service types@@ -505,6 +551,78 @@ class TestHassClientCallServiceMethod(TestCase):self.assertEqual(second_data['entity_id'], 'climate.thermostat')+class TestHassClientPingAndTimeout(TestCase):+ """ping() probe and timeout_secs threading behavior."""++ def setUp(self):+ self.api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456',+ }++ def test_default_timeout_used_when_not_specified(self):+ client = HassClient(self.api_options)+ self.assertEqual(client._timeout_secs, HassClient.DEFAULT_TIMEOUT)++ def test_explicit_timeout_overrides_default(self):+ client = HassClient(self.api_options, timeout_secs=2)+ self.assertEqual(client._timeout_secs, 2)++ @patch('hi.services.hass.hass_client.get')+ def test_ping_calls_root_api_endpoint_with_configured_timeout(self, mock_get):+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}+ mock_get.return_value = mock_response++ client = HassClient(self.api_options, timeout_secs=4)+ client.ping()++ mock_get.assert_called_once()+ call_url = mock_get.call_args[0][0]+ self.assertEqual(call_url, 'https://test.homeassistant.io:8123/api/')+ # Verify the configured timeout was passed to the underlying request+ # (no wall-clock waiting — just inspect the kwargs).+ self.assertEqual(mock_get.call_args[1]['timeout'], 4)++ @patch('hi.services.hass.hass_client.get')+ def test_ping_accepts_200_and_201(self, mock_get):+ client = HassClient(self.api_options)+ for status_code in (200, 201):+ mock_response = Mock()+ mock_response.status_code = status_code+ mock_response.headers = {'content-type': 'application/json'}+ mock_get.return_value = mock_response+ # Should not raise+ client.ping()++ @patch('hi.services.hass.hass_client.get')+ def test_ping_raises_on_non_2xx(self, mock_get):+ mock_response = Mock()+ mock_response.status_code = 401+ mock_response.text = 'Unauthorized'+ mock_get.return_value = mock_response++ client = HassClient(self.api_options)+ with self.assertRaises(ValueError) as context:+ client.ping()+ self.assertIn('401', str(context.exception))++ @patch('hi.services.hass.hass_client.get')+ def test_ping_raises_on_non_json_content_type(self, mock_get):+ """A 200 with HTML body must fail — the URL is not the API root."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'text/html'}+ mock_response.text = '<html><body>not the API</body></html>'+ mock_get.return_value = mock_response++ client = HassClient(self.api_options)+ with self.assertRaises(ValueError) as context:+ client.ping()+ self.assertIn('URL may be incorrect', str(context.exception))++class TestHassClientConstants(TestCase):"""Test HassClient constants and class attributes"""@@ -565,6 +683,8 @@ class TestHassClientEdgeCases(TestCase):# Mock an API call to verify the URL construction works correctlywith patch('hi.services.hass.hass_client.get') as mock_get:mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = '[]'mock_get.return_value = mock_response@@ -579,11 +699,13 @@ class TestHassClientEdgeCases(TestCase):def test_states_empty_response(self, mock_get):"""Test states method with empty response"""mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = '[]'mock_get.return_value = mock_response-+result = self.client.states()-+self.assertEqual(result, [])@patch('hi.services.hass.hass_client.post')@@ -591,6 +713,7 @@ class TestHassClientEdgeCases(TestCase):"""Test set_state with empty attributes dictionary"""mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.json.return_value = {}mock_post.return_value = mock_response@@ -607,6 +730,7 @@ class TestHassClientEdgeCases(TestCase):"""Test call_service with empty service data dictionary"""mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_post.return_value = mock_response# Empty dict should not add extra data to payload@@ -641,6 +765,8 @@ class TestHassClientWithRealData(TestCase):"""Test states() method processes real HASS data through entire pipeline"""# Use real HASS data without mocking the convertermock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = json.dumps(self.real_hass_states_data)mock_get.return_value = mock_response@@ -730,6 +856,7 @@ class TestHassClientWithRealData(TestCase):# Mock successful responsemock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.json.return_value = {'state': 'on'}mock_post.return_value = mock_response@@ -764,6 +891,7 @@ class TestHassClientWithRealData(TestCase):# Mock successful responsemock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_post.return_value = mock_response# Test realistic service calls based on our entity types@@ -795,6 +923,7 @@ class TestHassClientWithRealData(TestCase):"""Test call_service() with realistic service data for camera entities"""mock_response = Mock()mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_post.return_value = mock_response# Test camera-specific service calls with additional data@@ -868,6 +997,8 @@ class TestHassClientWithRealData(TestCase):self.assertGreater(len(complex_entities), 0, "Should have entities with complex attributes")mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}mock_response.text = json.dumps(complex_entities)mock_get.return_value = mock_responsediff --git a/src/hi/services/hass/tests/test_hass_client_factory.py b/src/hi/services/hass/tests/test_hass_client_factory.pyindex 198ebd8d..ce6073c4 100644--- a/src/hi/services/hass/tests/test_hass_client_factory.py+++ b/src/hi/services/hass/tests/test_hass_client_factory.py@@ -96,60 +96,109 @@ class TestHassClientFactory(TestCase):@patch('hi.services.hass.hass_client.get')def test_test_client_success(self, mock_get):- """Test successful client connectivity testing."""- # Arrange+ """test_client succeeds when the ping endpoint returns 200 with a JSON body."""mock_response = Mock()- mock_response.text = '[{"entity_id": "sensor.test", "state": "on"}]'+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}+ mock_response.text = '{"message": "API running."}'mock_get.return_value = mock_responseattributes = self._create_test_attributes()client = self.factory.create_client(attributes)- # Actresult = self.factory.test_client(client)- # Assert - Test actual behaviorself.assertIsInstance(result, IntegrationValidationResult)self.assertTrue(result.is_valid)self.assertEqual(result.status, HealthStatusType.HEALTHY)self.assertIsNone(result.error_message)- # Verify the client was actually tested+ # Probe should hit the lightweight /api/ root, not /api/states.mock_get.assert_called_once()+ call_url = mock_get.call_args[0][0]+ self.assertTrue(call_url.endswith('/api/'))++ @patch('hi.services.hass.hass_client.get')+ def test_test_client_ping_200_with_html_body_fails(self, mock_get):+ """test_client fails when ping returns 200 but the body is not JSON.++ Guards against the 'wrong base URL / misconfigured proxy' case+ where an upstream returns a friendly 200 HTML page. We want+ test_connection to surface this at save time rather than letting+ the runtime sync path JSONDecodeError later.+ """+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'text/html'}+ mock_response.text = '<html><body>not the API</body></html>'+ mock_get.return_value = mock_response++ attributes = self._create_test_attributes()+ client = self.factory.create_client(attributes)++ result = self.factory.test_client(client)++ self.assertFalse(result.is_valid)+ self.assertIn('URL may be incorrect', result.error_message)++ @patch('hi.services.hass.hass_client.get')+ def test_test_client_ping_non_2xx_status_fails(self, mock_get):+ """test_client fails when the ping endpoint returns a non-2xx status."""+ mock_response = Mock()+ mock_response.status_code = 500+ mock_response.text = 'Internal Server Error'+ mock_get.return_value = mock_response++ attributes = self._create_test_attributes()+ client = self.factory.create_client(attributes)++ result = self.factory.test_client(client)++ self.assertFalse(result.is_valid)+ # Status-code text doesn't match the auth/connect heuristics, so it+ # falls through to the WARNING bucket.+ self.assertEqual(result.status, HealthStatusType.WARNING)+ self.assertIn('500', result.error_message)@patch('hi.services.hass.hass_client.get')def test_test_client_connection_failure(self, mock_get):- """Test client testing with connection failure."""- # Arrange+ """test_client surfaces a connection error from the underlying request."""mock_get.side_effect = ConnectionError("Connection refused")attributes = self._create_test_attributes()client = self.factory.create_client(attributes)- # Actresult = self.factory.test_client(client)- # Assert - Test error handling behavior- self.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Cannot connect to Home Assistant', result.error_message)@patch('hi.services.hass.hass_client.get')def test_test_client_authentication_failure(self, mock_get):- """Test client testing with authentication failure."""- # Arrange+ """test_client categorizes auth errors distinctly from connect errors."""mock_get.side_effect = Exception("401 Unauthorized - Invalid token")attributes = self._create_test_attributes()client = self.factory.create_client(attributes)- # Actresult = self.factory.test_client(client)- # Assert - Test error categorization- self.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Authentication failed', result.error_message)-++ def test_create_client_threads_timeout_to_client(self):+ """create_client passes timeout_secs through to the HassClient."""+ attributes = self._create_test_attributes()++ client = self.factory.create_client(attributes, timeout_secs=3)+ self.assertEqual(client._timeout_secs, 3)++ def test_create_client_uses_default_timeout_when_unset(self):+ """create_client falls back to HassClient.DEFAULT_TIMEOUT when not provided."""+ attributes = self._create_test_attributes()++ client = self.factory.create_client(attributes)+ self.assertEqual(client._timeout_secs, HassClient.DEFAULT_TIMEOUT)+diff --git a/src/hi/services/homebox/hb_client.py b/src/hi/services/homebox/hb_client.pyindex f6b03add..4294414c 100644--- a/src/hi/services/homebox/hb_client.py+++ b/src/hi/services/homebox/hb_client.py@@ -11,11 +11,11 @@ class HbClient:API_URL = 'apiurl'API_USER = 'user'API_PASSWORD = 'password'-+DEFAULT_TIMEOUT = 25.0API_VERSION = 'v1'- def __init__(self, api_options: Dict[str, str]):+ def __init__(self, api_options: Dict[str, str], timeout_secs: Optional[float] = None):self._api_url = api_options.get(self.API_URL)assert self._api_url is not Noneif self._api_url.endswith('/'):@@ -26,8 +26,21 @@ class HbClient:self._password = api_options.get(self.API_PASSWORD)assert self._password is not None+ # Per-instance timeout. Defaults to DEFAULT_TIMEOUT when not+ # specified; the connection-test path passes a tighter bound for+ # interactive save-time validation.+ self._timeout_secs = timeout_secs if timeout_secs is not None else self.DEFAULT_TIMEOUT+self._session = Session()- self._login()++ # Login is deferred to first request rather than performed in+ # __init__. This keeps client construction free of network I/O+ # so that transient upstream problems do not leave the manager+ # with a permanently-null client. _make_request lazily logs in+ # on first use and re-logs in on a 401, so both the periodic+ # monitor and operator-initiated sync naturally self-heal once+ # the upstream recovers.+ self._authenticated = Falsedef _login(self):url = f"{self._api_url}/{self.API_VERSION}/users/login"@@ -37,7 +50,7 @@ class HbClient:'stayLoggedIn': True}try:- response = self._session.post(url, json=data, timeout=self.DEFAULT_TIMEOUT)+ response = self._session.post(url, json=data, timeout=self._timeout_secs)except Exception as e:raise ConnectionError(f'Cannot connect to HomeBox at {self._api_url}. '@@ -60,14 +73,24 @@ class HbClient:else:logger.warning("HomeBox login succeeded but response did not contain a token.")+ self._authenticated = True+def _make_request(self, method: str, url: str, **kwargs) -> Union[dict, Response]:"""Helper to make requests with simple re-authentication."""-- kwargs.setdefault('timeout', self.DEFAULT_TIMEOUT)-++ kwargs.setdefault('timeout', self._timeout_secs)++ # Lazy first login. Failures (connection refused, NON_JSON+ # upstream, etc.) propagate to the caller, who will retry on the+ # next monitor cycle / sync attempt — naturally self-healing+ # once the upstream comes back.+ if not self._authenticated and self._user:+ self._login()+response = self._session.request(method, url, **kwargs)-+if response.status_code == 401 and self._user:+ self._authenticated = Falseself._login()response = self._session.request(method, url, **kwargs)@@ -83,10 +106,23 @@ class HbClient:Fetches just the items summary list (one API call). Does not fetchper-item details. Suitable for lightweight reachability /health-check probes where only the count or IDs are needed.++ The items endpoint is always JSON in HomeBox; if we got back a+ raw Response (because _make_request fell through to the+ binary-attachment path on a non-JSON content type), the+ configured API URL is pointing at the wrong place. Surface that+ as a clear ValueError instead of letting downstream callers+ iterate the response as bytes."""url_list = f"{self._api_url}/{self.API_VERSION}/items"data = self._make_request('GET', url_list)- return data.get('items', []) if isinstance(data, dict) else data+ if not isinstance(data, dict):+ raise ValueError(+ f'HomeBox API URL may be incorrect. Expected JSON response '+ f'from {url_list} but did not receive one. Ensure the URL '+ f'points at the HomeBox API root (e.g., http://host:port/api).'+ )+ return data.get('items', [])def get_items(self) -> List[HbItem]:"""diff --git a/src/hi/services/homebox/hb_client_factory.py b/src/hi/services/homebox/hb_client_factory.pyindex a947af02..ef7572a3 100644--- a/src/hi/services/homebox/hb_client_factory.py+++ b/src/hi/services/homebox/hb_client_factory.py@@ -1,7 +1,7 @@"""Factory for creating and testing HomeBox API clients."""import logging-from typing import Dict+from typing import Dict, Optionalfrom hi.apps.system.enums import HealthStatusTypefrom hi.integrations.exceptions import IntegrationAttributeError@@ -20,7 +20,8 @@ class HbClientFactory:def create_client(self,- hb_attr_type_to_attribute: Dict[HbAttributeType, IntegrationAttribute]) -> HbClient:+ hb_attr_type_to_attribute: Dict[HbAttributeType, IntegrationAttribute],+ timeout_secs: Optional[float] = None) -> HbClient:"""Create a HbClient client from integration attributes.@@ -64,7 +65,7 @@ class HbClientFactory:options_key = attr_to_api_option_key[hb_attr_type]api_options[options_key] = hb_attr.value- return HbClient(api_options=api_options)+ return HbClient(api_options=api_options, timeout_secs=timeout_secs)def test_client(self, client: HbClient) -> IntegrationValidationResult:"""@@ -77,8 +78,9 @@ class HbClientFactory:IntegrationValidationResult indicating success or failure with details"""try:- # Test basic API connectivity by fetching items- items = client.get_items()+ # Lightweight probe: items summary (one API call, no per-item+ # detail fetches). Sufficient to verify auth + reachability.+ items = client.get_items_summary()if items is not None:# Successful API callreturn IntegrationValidationResult.success()diff --git a/src/hi/services/homebox/hb_manager.py b/src/hi/services/homebox/hb_manager.pyindex 3477887f..9315faf3 100644--- a/src/hi/services/homebox/hb_manager.py+++ b/src/hi/services/homebox/hb_manager.py@@ -1,6 +1,6 @@import loggingfrom asgiref.sync import sync_to_async-from typing import Dict, List+from typing import Dict, List, Optionalfrom hi.apps.common.singleton_manager import SingletonManagerfrom hi.apps.system.aggregate_health_provider import AggregateHealthProvider@@ -14,6 +14,7 @@ from hi.integrations.exceptions import (IntegrationDisabledError,)from hi.integrations.transient_models import (+ ConnectionTestResult,IntegrationKey,IntegrationValidationResult,)@@ -146,8 +147,11 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatuslogger.debug( 'Getting current HomeBox items.' )if not self.hb_client:- logger.warning('HomeBox client not available - cannot fetch items')- return []+ raise IntegrationError(+ 'HomeBox client is not available. The most recent reload '+ 'failed to construct a client (typically a connection or '+ 'configuration problem with the upstream HomeBox API).'+ )with self.api_call_context( 'hb_items' ):return self.hb_client.get_items()@@ -161,12 +165,18 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusdef fetch_hb_items_summary_from_api( self ) -> list:"""Lightweight one-call probe used by the monitor's reachability- heartbeat. Returns the items summary list (no per-item detail- fetches) or an empty list if the client is unavailable.+ heartbeat. Raises IntegrationError when the client is+ unavailable so the monitor's heartbeat correctly reflects the+ broken state — silently returning [] would let the monitor+ report 'API reachable' against a non-existent client and+ overwrite the manager's true WARNING/ERROR health."""if not self.hb_client:- logger.warning('HomeBox client not available - cannot fetch items summary')- return []+ raise IntegrationError(+ 'HomeBox client is not available. The most recent reload '+ 'failed to construct a client (typically a connection or '+ 'configuration problem with the upstream HomeBox API).'+ )with self.api_call_context( 'hb_items_summary' ):return self.hb_client.get_items_summary()@@ -177,26 +187,6 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusthread_sensitive = True,)()- def test_connection(self) -> bool:- try:- if not self.hb_client:- self.record_error('HomeBox client not configured')- return False-- items = self.fetch_hb_items_from_api(verbose=False)- if items is not None:- self.record_healthy('OK')- return True-- self.record_error('Failed to fetch items from HomeBox API')- return False-- except Exception as e:- error_msg = f'Connection test failed: {e}'- logger.debug(error_msg)- self.record_error( f'Connection error: {error_msg}' )- return False-def test_client_with_attributes(self,hb_attr_type_to_attribute: Dict[HbAttributeType, IntegrationAttribute]@@ -219,13 +209,23 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusdef validate_configuration(self,integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:+ """+ Schema-only validation. Confirms required attributes are present+ and structurally usable. Does NOT touch the network — for live+ connection probing, see test_connection().+ """try:- hb_attr_type_to_attribute = self._build_hb_attr_type_to_attribute_map(+ self._build_hb_attr_type_to_attribute_map(integration_attributes = integration_attributes,- enforce_requirements = False,+ enforce_requirements = True,)- return self.test_client_with_attributes(hb_attr_type_to_attribute)+ return IntegrationValidationResult.success()+ except IntegrationAttributeError as e:+ return IntegrationValidationResult.error(+ status=HealthStatusType.ERROR,+ error_message=str(e),+ )except Exception as e:logger.exception(f'Error in HomeBox configuration validation: {e}')return IntegrationValidationResult.error(@@ -233,6 +233,39 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatuserror_message=f'Configuration validation failed: {e}')+ def test_connection(+ self,+ integration_attributes: List[IntegrationAttribute],+ timeout_secs: Optional[float]) -> ConnectionTestResult:+ """+ Live connection probe with bounded timeout. Builds a temporary+ HbClient against the proposed attributes and exercises the+ lightweight items-summary endpoint.+ """+ try:+ hb_attr_type_to_attribute = self._build_hb_attr_type_to_attribute_map(+ integration_attributes = integration_attributes,+ enforce_requirements = True,+ )+ temp_client = self._client_factory.create_client(+ hb_attr_type_to_attribute = hb_attr_type_to_attribute,+ timeout_secs = timeout_secs,+ )+ validation_result = self._client_factory.test_client(temp_client)+ if validation_result.is_valid:+ return ConnectionTestResult.success()+ return ConnectionTestResult.failure(+ validation_result.error_message or 'Connection test failed'+ )++ except IntegrationAttributeError as e:+ return ConnectionTestResult.failure(str(e))+ except 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}')+def _build_hb_attr_type_to_attribute_map(self,integration_attributes: List[IntegrationAttribute],diff --git a/src/hi/services/homebox/hb_sync.py b/src/hi/services/homebox/hb_sync.pyindex da94176d..b9cf5da3 100644--- a/src/hi/services/homebox/hb_sync.py+++ b/src/hi/services/homebox/hb_sync.py@@ -44,11 +44,24 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):result = ProcessingResult( title = 'HomeBox Import Result' )if not hb_manager.hb_client:- logger.debug( 'HomeBox client not created. HomeBox integration disabled?' )- result.error_list.append( 'Sync problem. HomeBox integration disabled?' )+ health_status = hb_manager.health_status+ reason = health_status.last_message or 'HomeBox integration is disabled or not configured.'+ logger.debug( f'HomeBox client not available: {reason}' )+ result.error_list.append( f'Cannot sync HomeBox: {reason}' )+ return result++ try:+ item_list = hb_manager.fetch_hb_items_from_api()+ except Exception as e:+ # Runtime API call hit a transient upstream problem (login+ # failure, NON_JSON response, etc.). Surface the underlying+ # message rather than propagating a 500. The HbClient's+ # lazy-login path will retry on the next sync attempt,+ # naturally recovering once the upstream is healthy.+ logger.exception( 'HomeBox sync failed during fetch.' )+ result.error_list.append( f'Cannot sync HomeBox: {e}' )return result- item_list = hb_manager.fetch_hb_items_from_api()result.message_list.append( f'Found {len(item_list)} current HomeBox items.' )self._sync_helper_entities( item_list = item_list, result = result )diff --git a/src/hi/services/homebox/integration.py b/src/hi/services/homebox/integration.pyindex 27d32d84..cef77961 100644--- a/src/hi/services/homebox/integration.py+++ b/src/hi/services/homebox/integration.py@@ -1,5 +1,5 @@import logging-from typing import List+from typing import List, Optionalfrom hi.apps.system.enums import HealthStatusTypefrom hi.apps.system.health_status_provider import HealthStatusProvider@@ -8,7 +8,11 @@ from hi.integrations.integration_controller import IntegrationControllerfrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manage_view_pane import IntegrationManageViewPanefrom hi.integrations.models import IntegrationAttribute-from hi.integrations.transient_models import IntegrationMetaData, IntegrationValidationResult+from hi.integrations.transient_models import (+ ConnectionTestResult,+ IntegrationMetaData,+ IntegrationValidationResult,+)from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom .hb_controller import HomeBoxController@@ -52,10 +56,7 @@ class HomeBoxGateway(IntegrationGateway):self,integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:- """Validate HomeBox integration configuration by testing API connectivity.-- Delegates to HomeBoxManager for configuration validation.- """+ """Schema-only validation; delegates to HomeBoxManager."""try:hb_manager = HomeBoxManager()return hb_manager.validate_configuration(integration_attributes)@@ -65,3 +66,19 @@ class HomeBoxGateway(IntegrationGateway):status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')++ def test_connection(+ self,+ integration_attributes: List[IntegrationAttribute],+ timeout_secs: Optional[float],+ ) -> ConnectionTestResult:+ """Live connection probe; delegates to HomeBoxManager."""+ try:+ hb_manager = HomeBoxManager()+ return hb_manager.test_connection(+ 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}')diff --git a/src/hi/services/homebox/monitors.py b/src/hi/services/homebox/monitors.pyindex 5f7dc095..8e634b69 100644--- a/src/hi/services/homebox/monitors.py+++ b/src/hi/services/homebox/monitors.py@@ -1,5 +1,6 @@import logging+from hi.apps.alert.enums import AlarmLevelfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.system.provider_info import ProviderInfo@@ -31,11 +32,20 @@ class HomeBoxMonitor( PeriodicMonitor, HomeBoxMixin ):def get_api_timeout(self) -> float:return self.HOMEBOX_API_TIMEOUT_SECS+ def alarm_ceiling(self):+ # HomeBox tracks inventory data — degraded availability is+ # informational, not safety-critical, so cap at INFO.+ return AlarmLevel.INFO+async def _initialize(self):hb_manager = await self.hb_manager_async()if not hb_manager:returnhb_manager.register_change_listener( self.refresh )+ # See HassMonitor._initialize for the rationale behind subordinate+ # registration: aggregated manager health pulls monitor status on+ # demand, so a healthy reload cannot mask a failing monitor.+ hb_manager.add_subordinate_health_status_provider( self )self._was_initialized = Truereturn@@ -67,11 +77,21 @@ class HomeBoxMonitor( PeriodicMonitor, HomeBoxMixin ):self.record_error( 'No manager found.' )return- item_count = await self._check_api_reachable( hb_manager )+ try:+ item_count = await self._check_api_reachable( hb_manager )+ except Exception as e:+ # The probe failed (client unavailable, upstream unreachable,+ # bad response, etc.). Manager picks up our status via+ # add_subordinate_health_status_provider registration — its+ # aggregated health will reflect this WARNING the next time+ # it is read.+ message = f'HomeBox API probe failed: {e}'+ logger.warning( message )+ self.record_warning( message )+ returnmessage = f'HomeBox API reachable. items={item_count}'self.record_healthy( message )- hb_manager.record_healthy( message )returnasync def _check_api_reachable(self, hb_manager) -> int:diff --git a/src/hi/services/homebox/tests/test_hb_client.py b/src/hi/services/homebox/tests/test_hb_client.pyindex 24d44189..ee7d5e63 100644--- a/src/hi/services/homebox/tests/test_hb_client.py+++ b/src/hi/services/homebox/tests/test_hb_client.py@@ -33,7 +33,11 @@ class TestHbClient(SimpleTestCase):return response- def test_init_strips_trailing_slash_and_logs_in_when_credentials_exist(self):+ def test_init_strips_trailing_slash_and_defers_login(self):+ """Client construction must not perform network I/O. _login is+ deferred to first request so a transient upstream problem at+ construction time does not leave the manager with a permanently+ null client."""with patch.object(HbClient, '_login') as mock_login:client = HbClient(api_options={HbClient.API_URL: 'https://homebox.local/',@@ -42,7 +46,30 @@ class TestHbClient(SimpleTestCase):})self.assertEqual(client._api_url, 'https://homebox.local')- mock_login.assert_called_once()+ mock_login.assert_not_called()+ self.assertFalse(client._authenticated)++ def test_make_request_lazy_logs_in_on_first_use(self):+ """First _make_request call performs the deferred login."""+ with patch.object(HbClient, '_login') as mock_login:+ client = HbClient(api_options={+ HbClient.API_URL: 'https://homebox.local',+ HbClient.API_USER: 'user',+ HbClient.API_PASSWORD: 'pass',+ })++ success = self._response(status_code=200, json_data={'items': []})+ client._session.request = Mock(return_value=success)++ # Simulate _login marking the client as authenticated.+ def fake_login():+ client._authenticated = True+ mock_login.side_effect = fake_login++ result = client._make_request('GET', 'https://homebox.local/v1/items')++ mock_login.assert_called_once()+ self.assertEqual(result, {'items': []})def test_make_request_retries_after_unauthorized(self):with patch.object(HbClient, '_login') as mock_login:@@ -51,7 +78,9 @@ class TestHbClient(SimpleTestCase):HbClient.API_USER: 'user',HbClient.API_PASSWORD: 'pass',})- mock_login.reset_mock()+ # Pretend a prior request already authenticated us so we are+ # exercising only the 401 -> re-login -> retry path here.+ client._authenticated = Trueunauthorized = self._response(status_code=401, json_data={'detail': 'Unauthorized'})success = self._response(status_code=200, json_data={'items': []})@@ -65,8 +94,10 @@ class TestHbClient(SimpleTestCase):mock_login.assert_called_once()def test_make_request_returns_response_for_non_json_content(self):- with patch.object(HbClient, '_login'):- client = HbClient(api_options=self._api_options())+ client = HbClient(api_options=self._api_options())+ # Already-authenticated path so we exercise only the binary+ # attachment-download branch without triggering a lazy login.+ client._authenticated = Truebinary_response = self._response(status_code=200,@@ -80,6 +111,26 @@ class TestHbClient(SimpleTestCase):self.assertIs(result, binary_response)+ def test_get_items_summary_raises_when_response_is_not_json(self):+ """A non-JSON response on the items endpoint means the configured+ API URL is wrong; surface that as a clear ValueError instead of+ passing the raw Response through to get_items where it would+ explode on byte iteration."""+ client = HbClient(api_options=self._api_options())+ client._authenticated = True++ non_json_response = self._response(+ status_code=200,+ json_data=None,+ content_type='text/html',+ content=b'<html><body>not the API</body></html>',+ )+ client._session.request = Mock(return_value=non_json_response)++ with self.assertRaises(ValueError) as context:+ client.get_items_summary()+ self.assertIn('URL may be incorrect', str(context.exception))+def test_get_items_fetches_detail_and_skips_invalid_or_failed_items(self):with patch.object(HbClient, '_login'):client = HbClient(api_options=self._api_options())diff --git a/src/hi/services/homebox/tests/test_hb_client_factory.py b/src/hi/services/homebox/tests/test_hb_client_factory.pyindex 6572090e..212aba3f 100644--- a/src/hi/services/homebox/tests/test_hb_client_factory.py+++ b/src/hi/services/homebox/tests/test_hb_client_factory.py@@ -71,7 +71,8 @@ class TestHbClientFactory(TestCase):RealHbClient.API_USER: 'test_user',RealHbClient.API_PASSWORD: 'test_password',}- mock_client_class.assert_called_once_with(api_options=expected_options)+ mock_client_class.assert_called_once_with(+ api_options=expected_options, timeout_secs=None)def test_create_client_missing_required_attribute(self):"""Test client creation fails with missing required attribute."""@@ -96,9 +97,9 @@ class TestHbClientFactory(TestCase):self.assertIn('api_user', str(context.exception))def test_test_client_success(self):- """Test successful client connectivity testing."""+ """test_client succeeds when the lightweight items-summary probe returns a list."""mock_client = Mock()- mock_client.get_items.return_value = []+ mock_client.get_items_summary.return_value = []result = self.factory.test_client(mock_client)@@ -107,42 +108,56 @@ class TestHbClientFactory(TestCase):self.assertEqual(result.status, HealthStatusType.HEALTHY)self.assertIsNone(result.error_message)- mock_client.get_items.assert_called_once()+ # Probe must use the lightweight summary endpoint, not get_items+ # (which fetches per-item details).+ mock_client.get_items_summary.assert_called_once()+ mock_client.get_items.assert_not_called()def test_test_client_connection_failure(self):- """Test client testing with connection failure."""+ """Connection error from the probe surfaces with the connect category."""mock_client = Mock()- mock_client.get_items.side_effect = ConnectionError('Cannot connect to HomeBox')+ mock_client.get_items_summary.side_effect = ConnectionError('Cannot connect to HomeBox')result = self.factory.test_client(mock_client)- self.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Cannot connect to HomeBox', result.error_message)def test_test_client_authentication_failure(self):- """Test client testing with authentication failure."""+ """Auth error from the probe surfaces with the auth category."""mock_client = Mock()- mock_client.get_items.side_effect = Exception('401 Unauthorized')+ mock_client.get_items_summary.side_effect = Exception('401 Unauthorized')result = self.factory.test_client(mock_client)- self.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Authentication failed', result.error_message)def test_test_client_returns_none_items(self):- """Test client testing when items call returns None."""+ """A None response from the probe is treated as a probe failure."""mock_client = Mock()- mock_client.get_items.return_value = None+ mock_client.get_items_summary.return_value = Noneresult = self.factory.test_client(mock_client)- self.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Failed to fetch items from HomeBox API', result.error_message)- mock_client.get_items.assert_called_once()+ mock_client.get_items_summary.assert_called_once()++ @patch('hi.services.homebox.hb_client_factory.HbClient')+ def test_create_client_threads_timeout_to_client(self, mock_client_class):+ """create_client passes timeout_secs through to the HbClient."""+ from hi.services.homebox.hb_client import HbClient as RealHbClient+ mock_client_class.API_URL = RealHbClient.API_URL+ mock_client_class.API_USER = RealHbClient.API_USER+ mock_client_class.API_PASSWORD = RealHbClient.API_PASSWORD++ attributes = self._create_test_attributes()+ self.factory.create_client(attributes, timeout_secs=2)++ kwargs = mock_client_class.call_args.kwargs+ self.assertEqual(kwargs.get('timeout_secs'), 2)diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.pyindex 065ed10c..a92171f5 100644--- a/src/hi/services/zoneminder/integration.py+++ b/src/hi/services/zoneminder/integration.py@@ -14,6 +14,7 @@ from hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manage_view_pane import IntegrationManageViewPanefrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import (+ ConnectionTestResult,IntegrationMetaData,IntegrationValidationResult,)@@ -63,10 +64,7 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):self,integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:- """Validate ZoneMinder integration configuration by testing API connectivity.-- Delegates to ZoneMinderManager for configuration validation.- """+ """Schema-only validation; delegates to ZoneMinderManager."""try:zm_manager = ZoneMinderManager()return zm_manager.validate_configuration(integration_attributes)@@ -76,6 +74,22 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')++ def test_connection(+ self,+ integration_attributes: List[IntegrationAttribute],+ timeout_secs: Optional[float],+ ) -> ConnectionTestResult:+ """Live connection probe; delegates to ZoneMinderManager."""+ try:+ zm_manager = ZoneMinderManager()+ return zm_manager.test_connection(+ 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}')def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:"""Get entity's primary video stream (typically live)"""diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex 02b0f77e..3d8a2c4c 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -4,6 +4,7 @@ import loggingfrom .pyzm_client.helpers.Monitor import Monitor as ZmMonitorimport hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.alert.enums import AlarmLevelfrom hi.apps.entity.enums import EntityStateValuefrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.sensor_response_manager import SensorResponseMixin@@ -48,15 +49,24 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )def get_api_timeout(self) -> float:return self.ZONEMINDER_API_TIMEOUT_SECS+ def alarm_ceiling(self):+ # ZM outage in the background masks security camera events.+ # Treat health failures here as serious.+ return AlarmLevel.CRITICAL+async def _initialize(self):zm_manager = await self.zm_manager_async() # Allows sync use elsewhere in moduleif not zm_manager:return_ = await self.sensor_response_manager_async() # Allows sync use elsewhere in module-+self._zm_tzname = await zm_manager.get_zm_tzname_async()self._poll_from_datetime = datetimeproxy.now()zm_manager.register_change_listener( self.refresh )+ # See HassMonitor._initialize for the rationale behind subordinate+ # registration: aggregated manager health pulls monitor status on+ # demand, so a healthy reload cannot mask a failing monitor.+ zm_manager.add_subordinate_health_status_provider( self )self._was_initialized = Truereturn@@ -110,8 +120,8 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin ))message = f'Processed {len(sensor_response_map)} ZoneMinder states.'self.record_healthy( message )- if self.zm_manager():- self.zm_manager().record_healthy( message )+ # Manager picks up our status via add_subordinate_health_status_provider+ # registration; no explicit push needed here.returnasync def _process_events(self):diff --git a/src/hi/services/zoneminder/pyzm_client/api.py b/src/hi/services/zoneminder/pyzm_client/api.pyindex 454c975e..a685b4ac 100644--- a/src/hi/services/zoneminder/pyzm_client/api.py+++ b/src/hi/services/zoneminder/pyzm_client/api.py@@ -29,6 +29,9 @@ from .helpers import globals as gclass ZMApi (Base):++ DEFAULT_TIMEOUT = 25.0+def __init__(self, options={}):'''Options is a dict with the following keys:@@ -40,9 +43,16 @@ class ZMApi (Base):- disable_ssl_cert_check - if True will let you use self signed certs- basic_auth_user - basic auth username- basic_auth_password - basic auth password+ - timeout - per-request HTTP timeout in seconds (defaults to DEFAULT_TIMEOUT)Note: you can connect your own customer logging class to the API in which case all modules will use your custom class. Your class will need to implement some methods for this to work. See :class:`pyzm.helpers.Base.SimpleLog` for method details.'''-++ # Explicit None-check rather than `... or DEFAULT_TIMEOUT`: a+ # literal 0 timeout (no-wait probe) would silently revert to+ # the default under truthiness, masking caller intent.+ timeout_value = options.get('timeout')+ self._timeout_secs = timeout_value if timeout_value is not None else self.DEFAULT_TIMEOUT+self.api_url = options.get('apiurl')self.portal_url = options.get('portalurl')if not self.portal_url and self.api_url.endswith('/api'):@@ -181,18 +191,41 @@ class ZMApi (Base):data = {}url = self.api_url + '/host/getVersion.json'- r = self.session.post(url, data=data, timeout=25.0)+ r = self.session.post(url, data=data, timeout=self._timeout_secs)if r.status_code == 401 and self.options.get('token') and self.auth_enabled:g.logger.Debug(1, 'Token auth with refresh failed. Likely revoked, doing u/p login')self.options['token'] = Nonedata = {'user': self.options.get('user'), 'pass': self.options.get('password')}- r = self.session.post(url, data=data, timeout=25.0)+ r = self.session.post(url, data=data, timeout=self._timeout_secs)r.raise_for_status()else:r.raise_for_status()g.logger.Debug(1, r.text)- rj = r.json()++ # Validate that the upstream returned JSON before parsing.+ # A 200 with HTML body means the configured API URL is not+ # actually pointing at the ZoneMinder API root (misconfigured+ # proxy, captive portal, wrong base URL). Surface that as a+ # clear ValueError so the connection-test path reports a+ # meaningful reason instead of a raw JSONDecodeError.+ content_type = r.headers.get('content-type', '') if r.headers else ''+ if 'json' not in content_type.lower():+ self.authenticated = False+ raise ValueError(+ 'ZoneMinder API URL may be incorrect. Expected JSON '+ 'response but received {}. Ensure the URL points at '+ 'the ZoneMinder API root.'.format(+ content_type or 'unknown content type'+ )+ )+ try:+ rj = r.json()+ except ValueError as e:+ self.authenticated = False+ raise ValueError(+ 'ZoneMinder login response was not valid JSON: {}'.format(e)+ ) from eself.api_version = rj.get('apiversion')self.zm_version = rj.get('version')if self.auth_enabled:@@ -259,14 +292,14 @@ class ZMApi (Base):try:g.logger.Debug(3, 'make_request called with url={} payload={} type={} query={}'.format(url, payload, type, query))if type == 'get':- r = self.session.get(url, params=query, timeout=25.0)+ r = self.session.get(url, params=query, timeout=self._timeout_secs)elif type == 'post':- r = self.session.post(url, data=payload, params=query, timeout=25.0)+ r = self.session.post(url, data=payload, params=query, timeout=self._timeout_secs)elif type == 'put':- r = self.session.put(url, data=payload, params=query, timeout=25.0)+ r = self.session.put(url, data=payload, params=query, timeout=self._timeout_secs)elif type == 'delete':- r = self.session.delete(url, data=payload, params=query, timeout=25.0)+ r = self.session.delete(url, data=payload, params=query, timeout=self._timeout_secs)else:g.logger.Error('Unsupported request type:{}'.format(type))raise ValueError('Unsupported request type:{}'.format(type))diff --git a/src/hi/services/zoneminder/tests/test_zm_client_factory.py b/src/hi/services/zoneminder/tests/test_zm_client_factory.pyindex 302414fe..985ffa53 100644--- a/src/hi/services/zoneminder/tests/test_zm_client_factory.py+++ b/src/hi/services/zoneminder/tests/test_zm_client_factory.py@@ -101,75 +101,46 @@ class TestZmClientFactory(TestCase):self.assertIn('Missing ZM API attribute value', str(context.exception))self.assertIn('api_user', str(context.exception))- @patch('hi.services.zoneminder.pyzm_client.api.ZMApi')- def test_test_client_success(self, mock_zmapi_class):- """Test successful client connectivity testing."""- # Arrange+ def test_test_client_success_when_authenticated(self):+ """test_client passes when ZMApi.authenticated is True (login succeeded)."""mock_client = Mock()- mock_states_collection = Mock()- mock_states_collection.list.return_value = [Mock(), Mock()] # Some states- mock_client.states.return_value = mock_states_collection+ mock_client.authenticated = True- # Actresult = self.factory.test_client(mock_client)- # Assert - Test actual behaviorself.assertIsInstance(result, IntegrationValidationResult)self.assertTrue(result.is_valid)self.assertEqual(result.status, HealthStatusType.HEALTHY)self.assertIsNone(result.error_message)- # Verify the client was actually tested- mock_client.states.assert_called_once()- mock_states_collection.list.assert_called_once()-- @patch('hi.services.zoneminder.pyzm_client.api.ZMApi')- def test_test_client_connection_failure(self, mock_zmapi_class):- """Test client testing with connection failure."""- # Arrange+ def test_test_client_failure_when_not_authenticated(self):+ """test_client fails when login attempted but did not authenticate."""mock_client = Mock()- mock_client.states.side_effect = ConnectionError("Cannot connect to ZoneMinder")+ mock_client.authenticated = False- # Actresult = self.factory.test_client(mock_client)- # Assert - Test error handling behavior- self.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)self.assertEqual(result.status, HealthStatusType.ERROR)- self.assertIn('Cannot connect to ZoneMinder', result.error_message)+ self.assertIn('did not authenticate', result.error_message)- @patch('hi.services.zoneminder.pyzm_client.api.ZMApi')- def test_test_client_authentication_failure(self, mock_zmapi_class):- """Test client testing with authentication failure."""- # Arrange- mock_client = Mock()- mock_client.states.side_effect = Exception("401 Unauthorized")+ @patch('hi.services.zoneminder.zm_client_factory.ZMApi')+ def test_create_client_threads_timeout_to_options(self, mock_zmapi_class):+ """create_client passes timeout_secs to ZMApi options['timeout']."""+ attributes = self._create_test_attributes()- # Act- result = self.factory.test_client(mock_client)+ self.factory.create_client(attributes, timeout_secs=2)- # Assert - Test error categorization- self.assertIsInstance(result, IntegrationValidationResult)- self.assertFalse(result.is_valid)- self.assertEqual(result.status, HealthStatusType.ERROR)- self.assertIn('Authentication failed', result.error_message)+ kwargs = mock_zmapi_class.call_args.kwargs+ self.assertEqual(kwargs['options'].get('timeout'), 2)- @patch('hi.services.zoneminder.pyzm_client.api.ZMApi')- def test_test_client_returns_none_states(self, mock_zmapi_class):- """Test client testing when states call returns None."""- # Arrange- mock_client = Mock()- mock_states_collection = Mock()- mock_states_collection.list.return_value = None- mock_client.states.return_value = mock_states_collection+ @patch('hi.services.zoneminder.zm_client_factory.ZMApi')+ def test_create_client_omits_timeout_when_unset(self, mock_zmapi_class):+ """create_client does not set 'timeout' in options when timeout_secs is unset."""+ attributes = self._create_test_attributes()- # Act- result = self.factory.test_client(mock_client)+ self.factory.create_client(attributes)++ kwargs = mock_zmapi_class.call_args.kwargs+ self.assertNotIn('timeout', kwargs['options'])- # Assert- self.assertIsInstance(result, IntegrationValidationResult)- self.assertFalse(result.is_valid)- self.assertEqual(result.status, HealthStatusType.ERROR)- self.assertIn('Failed to fetch states from ZoneMinder API', result.error_message)-diff --git a/src/hi/services/zoneminder/tests/test_zm_manager.py b/src/hi/services/zoneminder/tests/test_zm_manager.pyindex dcc9f764..a09578ee 100644--- a/src/hi/services/zoneminder/tests/test_zm_manager.py+++ b/src/hi/services/zoneminder/tests/test_zm_manager.py@@ -351,7 +351,7 @@ class ZoneMinderManagerReloadTest(TransactionTestCase):# Register a callback to verify it gets calledcallback_called = []-+def test_callback():callback_called.append(True)@@ -362,4 +362,4 @@ class ZoneMinderManagerReloadTest(TransactionTestCase):# Callback should have been calledself.assertEqual(len(callback_called), 1)-+diff --git a/src/hi/services/zoneminder/zm_client_factory.py b/src/hi/services/zoneminder/zm_client_factory.pyindex 124e3bf9..35b0756f 100644--- a/src/hi/services/zoneminder/zm_client_factory.py+++ b/src/hi/services/zoneminder/zm_client_factory.py@@ -1,7 +1,7 @@"""Factory for creating and testing ZoneMinder API clients."""import logging-from typing import Dict+from typing import Dict, Optionalfrom hi.apps.system.enums import HealthStatusTypefrom hi.integrations.exceptions import IntegrationAttributeError@@ -20,12 +20,16 @@ class ZmClientFactory:def create_client(self,- zm_attr_type_to_attribute: Dict[ZmAttributeType, IntegrationAttribute]) -> ZMApi:+ zm_attr_type_to_attribute: Dict[ZmAttributeType, IntegrationAttribute],+ timeout_secs: Optional[float] = None) -> ZMApi:"""Create a ZMApi client from integration attributes.Args:zm_attr_type_to_attribute: Dictionary mapping attribute types to attribute objects+ timeout_secs: Optional per-request HTTP timeout. When set, overrides the+ ZMApi default and is used for the synchronous save-time+ connection probe path.Returns:Configured ZMApi instance@@ -37,6 +41,8 @@ class ZmClientFactory:api_options = {# 'disable_ssl_cert_check': True}+ if timeout_secs is not None:+ api_options['timeout'] = timeout_secsattr_to_api_option_key = {ZmAttributeType.API_URL: 'apiurl',@@ -72,6 +78,12 @@ class ZmClientFactory:"""Test API connectivity for a given client.+ ZMApi performs login during construction, so a successfully+ constructed client has already exercised auth and reachability.+ This method confirms the authenticated flag was set — any failure+ during construction will surface as an exception caught by the+ caller.+Args:client: ZMApi instance to test@@ -79,16 +91,12 @@ class ZmClientFactory:IntegrationValidationResult indicating success or failure with details"""try:- # Test basic API connectivity by fetching states- states = client.states().list()- if states is not None:- # Successful API call+ if getattr(client, 'authenticated', False):return IntegrationValidationResult.success()- else:- return IntegrationValidationResult.error(- status=HealthStatusType.ERROR,- error_message='Failed to fetch states from ZoneMinder API'- )+ return IntegrationValidationResult.error(+ status=HealthStatusType.ERROR,+ error_message='ZoneMinder login did not authenticate'+ )except Exception as e:error_msg = str(e).lower()diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex b114f994..7f8ead01 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -6,7 +6,7 @@ from .pyzm_client.helpers.Event import Event as ZmEventfrom .pyzm_client.helpers.Monitor import Monitor as ZmMonitorfrom .pyzm_client.helpers.State import State as ZmStatefrom .pyzm_client.helpers.globals import logger as pyzm_logger-from typing import Dict, List+from typing import Dict, List, Optionalimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.singleton_manager import SingletonManager@@ -22,6 +22,7 @@ from hi.integrations.exceptions import (IntegrationDisabledError,)from hi.integrations.transient_models import (+ ConnectionTestResult,IntegrationKey,IntegrationValidationResult,)@@ -361,28 +362,6 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStatimestamp = int(time.time())return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event={event_id}&_t={timestamp}'- def test_connection(self) -> bool:- """Test the connection to ZoneMinder API and update health status."""- try:- if not self.zm_client:- self.record_error( "ZoneMinder client not configured")- return False-- # Try to fetch states to test connection- states = self.get_zm_states(force_load=True)- if states:- self.record_healthy('OK')- return True- else:- self.record_error("Failed to fetch states from ZoneMinder API")- return False-- except Exception as e:- error_msg = f'Connection test failed: {e}'- logger.debug(error_msg)- self.record_error(f"Connection error: {error_msg}")- return False-def test_client_with_attributes(self,zm_attr_type_to_attribute: Dict[ZmAttributeType, IntegrationAttribute]@@ -408,20 +387,62 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStadef validate_configuration(self,integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:+ """+ Schema-only validation. Confirms required attributes are present+ and structurally usable. Does NOT touch the network — for live+ connection probing, see test_connection().+ """try:- # Build attribute mapping without enforcing requirements (for validation testing)- zm_attr_type_to_attribute = self._build_zm_attr_type_to_attribute_map(+ self._build_zm_attr_type_to_attribute_map(integration_attributes=integration_attributes,- enforce_requirements=False+ enforce_requirements=True,)- return self.test_client_with_attributes(zm_attr_type_to_attribute)+ return IntegrationValidationResult.success()+ except IntegrationAttributeError as e:+ return IntegrationValidationResult.error(+ status=HealthStatusType.ERROR,+ error_message=str(e),+ )except Exception as e:logger.exception(f'Error in ZoneMinder configuration validation: {e}')return IntegrationValidationResult.error(status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')++ def test_connection(+ self,+ integration_attributes: List[IntegrationAttribute],+ timeout_secs: Optional[float]) -> ConnectionTestResult:+ """+ Live connection probe with bounded timeout. Builds a temporary+ ZMApi client against the proposed attributes; the client's own+ login flow exercises auth and reachability synchronously.+ """+ try:+ zm_attr_type_to_attribute = self._build_zm_attr_type_to_attribute_map(+ integration_attributes=integration_attributes,+ enforce_requirements=True,+ )+ temp_client = self._client_factory.create_client(+ zm_attr_type_to_attribute=zm_attr_type_to_attribute,+ timeout_secs=timeout_secs,+ )+ validation_result = self._client_factory.test_client(temp_client)+ if validation_result.is_valid:+ return ConnectionTestResult.success()+ return ConnectionTestResult.failure(+ validation_result.error_message or 'Connection test failed'+ )++ except IntegrationAttributeError as e:+ return ConnectionTestResult.failure(str(e))+ except 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}')def _build_zm_attr_type_to_attribute_map(self,diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.pyindex 0b684c88..fe4ec700 100644--- a/src/hi/settings/simulator.py+++ b/src/hi/settings/simulator.py@@ -30,6 +30,7 @@ MIDDLEWARE = ['django.middleware.clickjacking.XFrameOptionsMiddleware','hi.simulator.middleware.SimViewMiddleware',+ 'hi.simulator.middleware.SimulatorFaultInjectionMiddleware',]ROOT_URLCONF = 'hi.simulator.urls'diff --git a/src/hi/simulator/enums.py b/src/hi/simulator/enums.pyindex 97bd4fc9..dee4b058 100644--- a/src/hi/simulator/enums.py+++ b/src/hi/simulator/enums.py@@ -40,6 +40,26 @@ class SimStateType(LabeledEnum):return f'simulator/panes/sim_control_{self.name.lower()}.html'+class SimulatorFaultMode(LabeledEnum):+ """+ Fault-injection state for a simulated service. Set per-simulator from+ the simulator UI; consumed by SimulatorFaultInjectionMiddleware to+ short-circuit API responses so the main app's integration+ test_connection probe paths can be exercised without standing up real+ misbehaving servers.+ """++ HEALTHY = ( 'Healthy' , 'Pass requests through normally (default).' )+ AUTH_FAIL = ( 'Auth Fail' , 'Return 401 from every API request.' )+ SERVER_ERROR = ( 'Server Error' , 'Return 500 from every API request.' )+ SLOW = ( 'Slow' , 'Sleep past the integration probe timeout, then pass through.' )+ NON_JSON = ( 'Non-JSON' , 'Return 200 with text/html body (simulates wrong base URL / proxy).' )++ @classmethod+ def default(cls):+ return cls.HEALTHY++class SimEntityType(LabeledEnum):AIR_CONDITIONER = ( 'Air Conditioner', '' )diff --git a/src/hi/simulator/middleware.py b/src/hi/simulator/middleware.pyindex 581656cb..58c3473e 100644--- a/src/hi/simulator/middleware.py+++ b/src/hi/simulator/middleware.py@@ -1,6 +1,13 @@import logging+import os+import re+import time+from django.http import HttpResponse, JsonResponse++from .enums import SimulatorFaultModefrom .sim_view_parameters import SimViewParameters+from .simulator_manager import SimulatorManagerlogger = logging.getLogger(__name__)@@ -10,7 +17,7 @@ class SimViewMiddleware:def __init__(self, get_response):self.get_response = get_responsereturn-+def __call__(self, request):self._set_sim_view_parameters( request )return self.get_response( request )@@ -18,3 +25,78 @@ class SimViewMiddleware:def _set_sim_view_parameters( self, request ):request.sim_view_parameters = SimViewParameters.from_session( request )return+++class SimulatorFaultInjectionMiddleware:+ """+ Intercepts requests under /services/<short_name>/<...> and applies the+ target simulator's current fault mode. Lets manual end-to-end testing+ of the main app's integration test_connection probe failure paths+ proceed without standing up real misbehaving servers.++ Each service can define its own URL layout, so this matcher does NOT+ assume any specific subpath structure (e.g., /api/) — any request+ under a service's mount is subject to fault injection. The fault-mode+ setter lives at a top-level simulator URL (/fault-mode/set/...) and+ therefore never matches this prefix.++ SLOW mode sleeps and then lets the real view run, so the failure that+ surfaces upstream is the integration's read timeout — not a 5xx —+ which is exactly the bucket we want to exercise.+ """++ _SERVICE_PATH_RE = re.compile( r'^/services/(?P<short_name>[^/]+)/' )++ SLOW_FAULT_SECS = float( os.environ.get( 'HI_SIM_SLOW_FAULT_SECS', '10.0' ))++ def __init__(self, get_response):+ self.get_response = get_response+ return++ def __call__(self, request):+ match = self._SERVICE_PATH_RE.match( request.path )+ if not match:+ return self.get_response( request )++ simulator = self._resolve_simulator( match.group('short_name') )+ if simulator is None:+ return self.get_response( request )++ fault_mode = simulator.fault_mode+ if fault_mode == SimulatorFaultMode.HEALTHY:+ return self.get_response( request )++ if fault_mode == SimulatorFaultMode.AUTH_FAIL:+ return JsonResponse(+ { 'message': 'Unauthorized' },+ status = 401,+ )++ if fault_mode == SimulatorFaultMode.SERVER_ERROR:+ return JsonResponse(+ { 'message': 'Internal server error' },+ status = 500,+ )++ if fault_mode == SimulatorFaultMode.SLOW:+ logger.debug( f'Fault injection: sleeping {self.SLOW_FAULT_SECS}s for {request.path}' )+ time.sleep( self.SLOW_FAULT_SECS )+ return self.get_response( request )++ if fault_mode == SimulatorFaultMode.NON_JSON:+ return HttpResponse(+ b'<html><body>simulated non-JSON response</body></html>',+ content_type = 'text/html',+ status = 200,+ )++ return self.get_response( request )++ def _resolve_simulator(self, short_name):+ # No cache — the lookup is cheap (small list, dict comprehension)+ # and avoids staleness if the simulator registry is ever changed+ # at runtime (e.g., test isolation, future dynamic registration).+ for sim_data in SimulatorManager().get_simulator_data_list():+ if sim_data.simulator.url_path_segment == short_name:+ return sim_data.simulator+ return Nonediff --git a/src/hi/simulator/services/hass/api/urls.py b/src/hi/simulator/services/hass/api/urls.pyindex 4ac557ee..dae6b48c 100644--- a/src/hi/simulator/services/hass/api/urls.py+++ b/src/hi/simulator/services/hass/api/urls.py@@ -4,6 +4,10 @@ from . import viewsurlpatterns = [+ re_path( r'^$',+ views.PingView.as_view(),+ name = 'hass_api_ping' ),+re_path( r'^states$',views.AllStatesView.as_view(),name = 'hass_api_states' ),diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.pyindex 833f5c1f..71d90644 100644--- a/src/hi/simulator/services/hass/api/views.py+++ b/src/hi/simulator/services/hass/api/views.py@@ -26,6 +26,19 @@ _SUPPORTED_SERVICES = {}+class PingView( View ):+ """+ Mirrors the real Home Assistant API root endpoint, which returns a+ small 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+ URL points at the wrong place.+ """++ def get(self, request, *args, **kwargs):+ return JsonResponse( { 'message': 'API running.' } )++class AllStatesView( View ):def get(self, request, *args, **kwargs):@@ -34,8 +47,8 @@ class AllStatesView( View ):hass_sim_state_list = hass_simulator.get_hass_sim_state_list()return JsonResponse( [ x.to_api_dict() for x in hass_sim_state_list ], safe = False )- except Exception as e:- logger.exception( 'Problem processing HAss states API request', e )+ except Exception:+ logger.exception( 'Problem processing HAss states API request' )return JsonResponse( list(), safe = False )@@ -132,6 +145,6 @@ class ServiceCallView( View ):except BadRequest:raise- except Exception as e:- logger.exception( 'Problem processing HAss service call', e )+ except Exception:+ logger.exception( 'Problem processing HAss service call' )return JsonResponse( list(), safe = False )diff --git a/src/hi/simulator/services/homebox/api/views.py b/src/hi/simulator/services/homebox/api/views.pyindex 5ce75a10..67b198ab 100644--- a/src/hi/simulator/services/homebox/api/views.py+++ b/src/hi/simulator/services/homebox/api/views.py@@ -55,8 +55,8 @@ class AllItemsView( View ):]return JsonResponse( { 'items': items } )- except Exception as e:- logger.exception( 'Problem processing HomeBox items list', e )+ except Exception:+ logger.exception( 'Problem processing HomeBox items list' )return JsonResponse( { 'items': [] } )diff --git a/src/hi/simulator/services/zoneminder/api/views.py b/src/hi/simulator/services/zoneminder/api/views.pyindex a1acb55a..dacce3c7 100644--- a/src/hi/simulator/services/zoneminder/api/views.py+++ b/src/hi/simulator/services/zoneminder/api/views.py@@ -53,8 +53,8 @@ class MonitorsView( View ):return JsonResponse({'monitors': [ x.to_api_dict() for x in zm_monitor_sim_entity_list ],})- except Exception as e:- logger.exception( 'Problem processing ZM monitors API request', e )+ except Exception:+ logger.exception( 'Problem processing ZM monitors API request' )return JsonResponse({'monitors': [ ],})@@ -100,8 +100,8 @@ class StatesView( View ):return JsonResponse({'states': [ x.to_api_dict() for x in zm_sim_run_state_list ],})- except Exception as e:- logger.exception( 'Problem processing ZM states API request', e )+ except Exception:+ logger.exception( 'Problem processing ZM states API request' )return JsonResponse({'states': [ ],})@@ -165,8 +165,8 @@ class EventsIndexView( View ):'pagination': zm_pagination.to_api_dict(),})- except Exception as e:- logger.exception( 'Problem processing ZM events API request', e )+ except Exception:+ logger.exception( 'Problem processing ZM events API request' )return JsonResponse({'events': [ ],'pagination': ZmPagination( page = 1 ).to_api_dict(),@@ -210,7 +210,7 @@ class EventsIndexView( View ):'operator': operator.strip(),'value_datetime': value_datetime,}- except ValueError as ve:- logger.exception( f'Problem parsing filter date: {value}', ve )+ except ValueError:+ logger.exception( f'Problem parsing filter date: {value}' )continuereturn filtersdiff --git a/src/hi/simulator/services/zoneminder/simulator.py b/src/hi/simulator/services/zoneminder/simulator.pyindex 83af5baf..e47a8d0a 100644--- a/src/hi/simulator/services/zoneminder/simulator.py+++ b/src/hi/simulator/services/zoneminder/simulator.py@@ -40,7 +40,46 @@ class ZoneMinderSimulator( Simulator ):if sim_entity.sim_entity_definition.sim_entity_fields_class == ZmServerSimEntityFields:return ZmSimServer( sim_entity = sim_entity )continue- raise ValueError( 'No ZM server entity has been created.' )++ # Auto-create a default ZoneMinder Service entity. The+ # integration's run-state queries — and therefore any sync —+ # require a server entity; ZmServerSimEntityFields has no+ # operator-configurable fields, so the only sensible operator+ # action would be to click "Add ZoneMinder Service" and accept+ # defaults. Elide that step so a fresh profile is functional out+ # of the box.+ self._auto_create_default_server_entity()+ for sim_entity in self.sim_entities:+ if sim_entity.sim_entity_definition.sim_entity_fields_class == ZmServerSimEntityFields:+ return ZmSimServer( sim_entity = sim_entity )+ continue+ raise ValueError( 'Failed to auto-create ZM server entity.' )++ def _auto_create_default_server_entity( self ):+ # Imported locally to avoid a module-load-time cycle: the+ # SimulatorManager imports the simulator subclasses at startup.+ from hi.simulator.simulator_manager import SimulatorManager++ server_definition = None+ for definition in self.sim_entity_definition_list:+ if definition.sim_entity_fields_class == ZmServerSimEntityFields:+ server_definition = definition+ break+ continue+ if server_definition is None:+ raise ValueError( 'No ZmServerSimEntityFields definition registered.' )++ try:+ SimulatorManager().add_sim_entity(+ simulator = self,+ sim_entity_definition = server_definition,+ sim_entity_fields = ZmServerSimEntityFields(),+ )+ except SimEntityValidationError:+ # Concurrent request already auto-created it. Safe to ignore;+ # the caller's re-scan of self.sim_entities will pick it up.+ pass+ returndef get_zm_sim_run_state_list(self) -> List[ ZmSimRunState ]:diff --git a/src/hi/simulator/simulator.py b/src/hi/simulator/simulator.pyindex 8658dfdd..02c5eb57 100644--- a/src/hi/simulator/simulator.py+++ b/src/hi/simulator/simulator.py@@ -3,6 +3,7 @@ from typing import Dict, Listfrom hi.apps.common.singleton import Singletonfrom .base_models import SimEntityDefinition, SimEntityFields, SimState+from .enums import SimulatorFaultModefrom .sim_entity import SimEntity@@ -53,13 +54,36 @@ class Simulator( Singleton ):"""def __init_singleton__( self ):+ # Set BEFORE initialize() so that a SimProfile switch — which+ # re-invokes initialize() to reload entity instances — does NOT+ # reset the operator-selected fault mode.+ self._fault_mode = SimulatorFaultMode.default()self.initialize()return-+@propertydef id(self) -> str:""" A unique identifier for referencing this simulator implementation. """raise NotImplementedError('Subclasses must override this method.')++ @property+ def url_path_segment(self) -> str:+ """+ The URL segment under which this simulator's routes are mounted by+ src/hi/simulator/urls.py:discover_urls() — derived from the+ services-app directory name (e.g., 'homebox' for the simulator at+ hi.simulator.services.homebox.simulator). Note this can differ+ from `id` (e.g., id='hb' but url_path_segment='homebox').+ """+ return self.__class__.__module__.split('.')[-2]++ @property+ def fault_mode(self) -> SimulatorFaultMode:+ return self._fault_mode++ def set_fault_mode( self, fault_mode : SimulatorFaultMode ):+ self._fault_mode = fault_mode+ return@propertydef label(self) -> str:diff --git a/src/hi/simulator/simulator_manager.py b/src/hi/simulator/simulator_manager.pyindex b8c7fce5..93222515 100644--- a/src/hi/simulator/simulator_manager.py+++ b/src/hi/simulator/simulator_manager.py@@ -178,8 +178,8 @@ class SimulatorManager( Singleton ):)continue- except Exception as e:- logger.exception( f'Problem getting simulator for {module_name}.', e )+ except Exception:+ logger.exception( f'Problem getting simulator for {module_name}.' )continuereturn@@ -233,8 +233,8 @@ class SimulatorManager( Singleton ):)try:simulator_data.simulator.add_sim_entity( sim_entity = sim_entity )- except SimEntityValidationError as ve:- logger.exception( 'Could not add DB simulator entity.', ve )+ except SimEntityValidationError:+ logger.exception( 'Could not add DB simulator entity.' )continuereturndiff --git a/src/hi/simulator/templates/simulator/panes/fault_mode_form.html b/src/hi/simulator/templates/simulator/panes/fault_mode_form.htmlnew file mode 100644index 00000000..550351aa--- /dev/null+++ b/src/hi/simulator/templates/simulator/panes/fault_mode_form.html@@ -0,0 +1,19 @@+<div id="hi-fault-mode-{{ simulator.id }}" class="hi-fault-mode-form-wrap">+ <form action="{% url 'simulator_fault_mode_set' simulator_id=simulator.id %}"+ method="POST" class="form-inline hi-fault-mode-form"+ data-async="#hi-fault-mode-{{ simulator.id }}"+ data-mode="replace">+ {% csrf_token %}+ <label class="mr-2 mb-0" for="fault-mode-{{ simulator.id }}">Fault mode:</label>+ <select id="fault-mode-{{ simulator.id }}" name="fault_mode"+ class="form-control form-control-sm"+ onchange-async="true">+ {% for mode in fault_mode_choices %}+ <option value="{{ mode.name }}"+ {% if simulator.fault_mode == mode %}selected{% endif %}>+ {{ mode.label }}+ </option>+ {% endfor %}+ </select>+ </form>+</div>diff --git a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html b/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.htmlindex 33a3ddcd..0a16bdc4 100644--- a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html+++ b/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html@@ -21,7 +21,7 @@<div id="simulator-{{ simulator.id }}" role="tabpanel"class="tab-pane fade {% if simulator.id == current_simulator.id %}show active{% endif %}"aria-labelledby="hi-simulator-tab-{{ simulator.id }}">- <div>+ <div class="d-flex align-items-center justify-content-between mb-2"><div class="dropdown"><button class="btn btn-secondary btn-control dropdown-toggle" type="button"id="hi-sim-entity-{{ simulator.id }}-menu" data-toggle="dropdown">@@ -42,6 +42,8 @@{% endfor %}</div></div>++ {% include "simulator/panes/fault_mode_form.html" with simulator=simulator fault_mode_choices=fault_mode_choices %}</div>{% for sim_entity in simulator.sim_entities %}diff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.pyindex 5932ce8d..54229f68 100644--- a/src/hi/simulator/urls.py+++ b/src/hi/simulator/urls.py@@ -49,6 +49,10 @@ urlpatterns = [re_path( r'^entity/state/set/(?P<simulator_id>[\w_\-\.\:]+)/(?P<sim_entity_id>\d+)/(?P<sim_state_id>[\w\-]+)$',views.SimStateSetView.as_view(),name = 'simulator_entity_state_set' ),++ re_path( r'^fault-mode/set/(?P<simulator_id>[\w_\-\.\:]+)$',+ views.SetSimulatorFaultModeView.as_view(),+ name = 'simulator_fault_mode_set' ),]@@ -68,8 +72,8 @@ def discover_urls():discovered_url_modules[short_name] = urls_module- except Exception as e:- logger.exception( f'Problem importing URL module: {module_name}', e )+ except Exception:+ logger.exception( f'Problem importing URL module: {module_name}' )passcontinuediff --git a/src/hi/simulator/views.py b/src/hi/simulator/views.pyindex c7dd2805..322c918a 100644--- a/src/hi/simulator/views.py+++ b/src/hi/simulator/views.py@@ -1,3 +1,4 @@+from django.core.exceptions import BadRequestfrom django.http import HttpResponseRedirectfrom django.shortcuts import renderfrom django.urls import reverse@@ -5,6 +6,7 @@ from django.views.generic import Viewimport hi.apps.common.antinode as antinode+from .enums import SimulatorFaultModefrom .exceptions import SimEntityValidationErrorfrom . import formsfrom .models import DbSimEntity@@ -29,6 +31,7 @@ class HomeView( View, SimulatorViewMixin ):'current_sim_profile': current_sim_profile,'simulator_data_list': simulator_data_list,'current_simulator': current_simulator,+ 'fault_mode_choices': list( SimulatorFaultMode ),}return render( request, 'simulator/pages/home.html', context )@@ -266,6 +269,38 @@ class SimEntityDeleteView( View, SimulatorViewMixin ):return antinode.refresh_response()+class SetSimulatorFaultModeView( View, SimulatorViewMixin ):+ """+ Operator-driven control to flip a simulator into a fault-injection+ mode (or back to HEALTHY). Lives at a top-level URL — outside the+ /services/<short_name>/ subtree — so the fault-injection middleware+ never intercepts requests to it. This is the operator's escape hatch+ when a simulator is in any non-HEALTHY mode.++ Returns the fault-mode form HTML fragment so antinode.js can swap it+ in place (data-async + data-mode=replace), avoiding a full page+ reload on each toggle.+ """++ TEMPLATE_NAME = 'simulator/panes/fault_mode_form.html'++ def post( self, request, *args, **kwargs ):+ simulator = self.get_simulator_by_id(+ simulator_id = kwargs.get('simulator_id'),+ )+ fault_mode_name = request.POST.get('fault_mode')+ try:+ fault_mode = SimulatorFaultMode[ fault_mode_name ]+ except (KeyError, TypeError):+ raise BadRequest( f'Invalid fault mode: {fault_mode_name}' )+ simulator.set_fault_mode( fault_mode )+ context = {+ 'simulator': simulator,+ 'fault_mode_choices': list( SimulatorFaultMode ),+ }+ return render( request, self.TEMPLATE_NAME, context )++class SimStateSetView( View, SimulatorViewMixin ):TEMPLATE_NAME = 'simulator/panes/sim_state.html'diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex 9f33bb73..92f7909a 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -1233,6 +1233,56 @@ g[hover] {color: var(--on-error-color);}+/*+ * Health status badge — used by system/panes/health_status_badge.html+ * for the expanded button view. One class per HealthStatusType value.+ */+.hi-health-badge-healthy {+ background-color: var(--success-color);+ color: var(--on-success-color);+ border-color: var(--success-color);+}+.hi-health-badge-warning {+ background-color: var(--warning-color);+ color: var(--on-warning-color);+ border-color: var(--warning-color);+}+.hi-health-badge-error {+ background-color: var(--error-color);+ color: var(--on-error-color);+ border-color: var(--error-color);+}+.hi-health-badge-disabled {+ background-color: var(--muted-color);+ color: var(--on-muted-color, #fff);+ border-color: var(--muted-color);+}+.hi-health-badge-unknown {+ background-color: transparent;+ color: var(--muted-color);+ border-color: var(--muted-color);+}++/*+ * Compact integration-status indicator — used by integrations/panes/+ * integration_status_indicator.html for the sidebar nav-tab. Icon-only,+ * color drawn from semantic CSS variables. paused is informational+ * (muted), warning/error draw attention.+ */+.hi-integration-indicator {+ margin-left: 0.4rem;+ line-height: 1;+}+.hi-integration-indicator-error {+ color: var(--error-color);+}+.hi-integration-indicator-warning {+ color: var(--warning-color);+}+.hi-integration-indicator-paused {+ color: var(--muted-color);+}+.text-success-custom {color: var(--success-color);}