Home Information - Your home, your data, organized.
Python
Pre-release tweaks (2026-05-28) (#379)
Tony C16533d25c26f
diff --git a/src/hi/apps/alert/alarm.py b/src/hi/apps/alert/alarm.pyindex 55f62561..2b4110ec 100644--- a/src/hi/apps/alert/alarm.py+++ b/src/hi/apps/alert/alarm.py@@ -12,14 +12,6 @@ from .enums import AlarmLevel, AlarmSource@dataclassclass Alarm:- # Practical "never expires" lifetime — long enough that the alarm- # persists until the user acknowledges it under any realistic- # scenario, while keeping ``end_datetime`` always a valid datetime- # so consumers do not need a None / special-case branch. Use this- # value (not zero, not None) when constructing an alarm that- # should remain visible until acknowledged.- MAX_LIFETIME_SECS = 365 * 24 * 60 * 60-alarm_source : AlarmSourcealarm_type : stralarm_level : AlarmLevel@@ -46,13 +38,7 @@ class Alarm:# "never expires" intent. Enforce the supported range here so# mistakes show up at construction, not silently as# vanished alarms.- assert (- ( self.alarm_lifetime_secs > 0 )- and ( self.alarm_lifetime_secs <= self.MAX_LIFETIME_SECS )- ), (- f'alarm_lifetime_secs out of range: {self.alarm_lifetime_secs}; '- f'must be in (0, {self.MAX_LIFETIME_SECS}].'- )+ assert self.alarm_lifetime_secs > 0return@propertydiff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.pyindex 462814f7..fd85a3d0 100644--- a/src/hi/apps/alert/alert.py+++ b/src/hi/apps/alert/alert.py@@ -116,22 +116,30 @@ class Alert:def is_matching_alarm( self, alarm : Alarm ) -> bool:return bool( self._first_alarm.signature == alarm.signature )- def upsert_alarm( self, alarm : Alarm ):+ def upsert_alarm( self, alarm : Alarm ) -> bool:+ """Absorb ``alarm`` into this alert. Returns ``True`` if the+ alarm was appended to the occurrence deque (a distinct+ incident under the same signature), ``False`` if it was+ discarded as a ``source_alarm_id`` duplicate of an already-+ tracked incident."""assert alarm.signature == self.first_alarm.signature- # Always refresh expiry from the incoming alarm. A follow-up- # submission with a shorter lifetime correctly shortens the- # Alert's end_datetime (e.g. NWS reducing its ``expires``).- self._end_datetime = datetimeproxy.now() + timedelta( seconds = alarm.alarm_lifetime_secs )+ # Refresh expiry only while unacknowledged. Once acknowledged,+ # the alert stays in the queue as a dedup anchor until its+ # original ``end_datetime`` -- extending the window on every+ # poll would suppress a chronic upstream condition for as long+ # as the source keeps re-reporting it.+ if not self._is_acknowledged:+ self._end_datetime = datetimeproxy.now() + timedelta( seconds = alarm.alarm_lifetime_secs )# If the caller identified this as a specific incident and we# already have that incident in the deque, do not count it- # again — the alarm_count should reflect distinct occurrences,+ # again -- the alarm_count should reflect distinct occurrences,# not how often the source re-reported the same one.if alarm.source_alarm_id is not None:for existing in self._latest_alarms:if existing.source_alarm_id == alarm.source_alarm_id:- return+ return Falseself._latest_alarms.appendleft( alarm )- return+ return Truedef get_latest_alarm(self) -> Alarm:if len(self._latest_alarms) > 0:diff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.pyindex 2fa708e4..3178c98c 100644--- a/src/hi/apps/alert/alert_manager.py+++ b/src/hi/apps/alert/alert_manager.py@@ -133,7 +133,7 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):result.alerts_before_cleanup = len(self._alert_queue)# Perform cleanup and get detailed results- cleanup_result = self._alert_queue.remove_expired_or_acknowledged_alerts()+ cleanup_result = self._alert_queue.remove_expired_alerts()result.expired_alerts_removed = cleanup_result.expired_removedresult.acknowledged_alerts_removed = cleanup_result.acknowledged_removeddiff --git a/src/hi/apps/alert/alert_queue.py b/src/hi/apps/alert/alert_queue.pyindex 63a3b292..132ac9cd 100644--- a/src/hi/apps/alert/alert_queue.py+++ b/src/hi/apps/alert/alert_queue.py@@ -14,7 +14,11 @@ logger = logging.getLogger(__name__)class AlertQueue:- MAX_ALERT_LIST_SIZE = 50+ # Caps the queue's memory of past (acknowledged) alerts. Active+ # (unacknowledged) alerts are never evicted by this cap -- the+ # operator must always see them. When a new alert would push the+ # queue past this size, the oldest acknowledged alert is dropped.+ MAX_ALERT_LIST_SIZE = 200TRACE = False # for debugging@@ -109,18 +113,54 @@ class AlertQueue:for alert in self._alert_list:if not alert.is_matching_alarm( alarm = alarm ):continue- alert.upsert_alarm( alarm = alarm )+ appended = alert.upsert_alarm( alarm = alarm )self._last_changed_datetime = datetimeproxy.now()- logger.debug( f'Added to existing alert: alarm={alarm}, alert={alert}' )+ if appended:+ logger.debug( f'Added alarm to existing alert:'+ f' alarm={alarm}, alert={alert}' )+ else:+ logger.debug( f'Discarded duplicate alarm'+ f' (source_alarm_id already tracked):'+ f' alarm={alarm}, alert={alert}' )return alert-++ # No matching alert. Make room if needed by evicting the+ # oldest acknowledged alert. Unacknowledged alerts are+ # never evicted, so the queue can grow past the cap if all+ # entries are still active -- losing an active alert is+ # worse than briefly exceeding the soft cap.+ if len( self._alert_list ) >= self.MAX_ALERT_LIST_SIZE:+ self._evict_oldest_acknowledged_alert()+new_alert = Alert( first_alarm = alarm )new_alert.queue_insertion_datetime = datetimeproxy.now()self._alert_list.append( new_alert )self._last_changed_datetime = datetimeproxy.now()logger.debug( f'Added new alert: {new_alert}' )return new_alert-++ return++ def _evict_oldest_acknowledged_alert(self):+ # ``add_alarm`` always sets ``queue_insertion_datetime`` before+ # appending, so the field is non-None in practice. Treat a+ # missing value as the epoch so a stray ``None`` doesn't+ # silently freeze the eviction candidate on the first acked+ # entry encountered.+ oldest_index = None+ oldest_insertion_dt = None+ for index, alert in enumerate( self._alert_list ):+ if not alert.is_acknowledged:+ continue+ insertion_dt = alert.queue_insertion_datetime or datetimeproxy.min()+ if ( oldest_insertion_dt is None+ or ( insertion_dt < oldest_insertion_dt )):+ oldest_insertion_dt = insertion_dt+ oldest_index = index+ continue+ if oldest_index is not None:+ evicted = self._alert_list.pop( oldest_index )+ logger.debug( f'Evicted oldest acknowledged alert to make room: {evicted}' )returndef acknowledge_alert( self, alert_id : str ):@@ -135,9 +175,13 @@ class AlertQueue:raise KeyError( f'Alert not found for {alert_id}' )- def remove_expired_or_acknowledged_alerts(self):- """Remove expired and acknowledged alerts and return detailed results."""+ def remove_expired_alerts(self):+ """Remove alerts whose ``end_datetime`` has passed. Acknowledged+ alerts are kept until their natural expiry so they continue to+ suppress duplicate alarms (the queue is the dedup memory)."""expired_removed = 0+ # Informational count of how many expired alerts had been+ # acknowledged. Acknowledgement is not itself a removal trigger.acknowledged_removed = 0with self._active_alerts_lock:@@ -151,24 +195,22 @@ class AlertQueue:for alert in self._alert_list:if alert.end_datetime <= now_datetime:expired_removed += 1- continue- if alert.is_acknowledged:- acknowledged_removed += 1+ if alert.is_acknowledged:+ acknowledged_removed += 1continuenew_list.append( alert )continue-- total_removed = expired_removed + acknowledged_removed- logger.debug( f'Removed "{total_removed}" alerts: {expired_removed}'- f' expired, {acknowledged_removed} acknowledged.' )- if total_removed > 0:++ logger.debug( f'Removed "{expired_removed}" expired alerts'+ f' ({acknowledged_removed} had been acknowledged).' )+ if expired_removed > 0:self._alert_list = new_listself._last_changed_datetime = datetimeproxy.now()return AlertQueueCleanupResult(expired_removed = expired_removed,acknowledged_removed = acknowledged_removed,- total_removed = total_removed+ total_removed = expired_removed,)diff --git a/src/hi/apps/alert/monitors.py b/src/hi/apps/alert/monitors.pyindex 15e84488..1e829ec8 100644--- a/src/hi/apps/alert/monitors.py+++ b/src/hi/apps/alert/monitors.py@@ -17,19 +17,18 @@ class AlertMonitor( PeriodicMonitor, AlertMixin ):TRACE = False # for debuggingdef __init__( self ):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.ALERT_POLLING_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )return+ def get_polling_interval_secs(self) -> int:+ return self.ALERT_POLLING_INTERVAL_SECS+@classmethoddef get_provider_info(cls) -> ProviderInfo:return ProviderInfo(provider_id = cls.MONITOR_ID,provider_name = 'Alert Monitor',description = 'Alert processing and notification management',- expected_heartbeat_interval_secs = cls.ALERT_POLLING_INTERVAL_SECS,)def alarm_ceiling(self):diff --git a/src/hi/apps/alert/templates/alert/modals/alert_details.html b/src/hi/apps/alert/templates/alert/modals/alert_details.htmlindex a9bf433e..44b1719c 100644--- a/src/hi/apps/alert/templates/alert/modals/alert_details.html+++ b/src/hi/apps/alert/templates/alert/modals/alert_details.html@@ -4,6 +4,7 @@{% load video_tags %}{% load icons %}+{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}{% block header_class %}bg-secondary{% endblock %}{% block title_text %}diff --git a/src/hi/apps/alert/tests/test_alert_manager.py b/src/hi/apps/alert/tests/test_alert_manager.pyindex ea4059cd..dcc72118 100644--- a/src/hi/apps/alert/tests/test_alert_manager.py+++ b/src/hi/apps/alert/tests/test_alert_manager.py@@ -109,10 +109,70 @@ class TestAlertManager(BaseTestCase):self.assertIsInstance(manager, Singleton)return+ def test_notification_suppressed_for_absorbed_alarm_into_acked_alert(self):+ """When an alarm is absorbed into an already-acknowledged alert+ with a distinct ``source_alarm_id``, the alert's occurrence+ deque grows -- ``has_single_alarm`` becomes False -- and+ ``add_notification_item`` is NOT invoked. Pins the+ AlertManager-level suppression of re-notification on absorb+ for the new dedup-anchor semantics."""+ manager = AlertManager()+ # Fresh queue per test so prior tests don't bleed in.+ manager._alert_queue._alert_list.clear()++ mock_notification_manager = patch.object(+ manager, 'notification_manager'+ ).start()+ self.addCleanup(patch.stopall)+ mock_security_manager = patch.object(+ manager, 'security_manager'+ ).start()+ mock_security_manager.return_value.security_state.uses_notifications = True++ first_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='absorb_test',+ alarm_level=AlarmLevel.WARNING,+ title='First incident',+ sensor_response_list=[],+ security_level=SecurityLevel.LOW,+ alarm_lifetime_secs=300,+ timestamp=datetimeproxy.now(),+ source_alarm_id='incident-1',+ )+ manager.upsert_alarm(first_alarm)+ first_alert = manager.unacknowledged_alert_list[0]+ # First alarm produces one notification call (single-alarm).+ self.assertEqual(+ mock_notification_manager.return_value.add_notification_item.call_count, 1+ )++ manager.acknowledge_alert(first_alert.id)++ # Distinct new incident, same signature, arrives after ack.+ second_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='absorb_test',+ alarm_level=AlarmLevel.WARNING,+ title='Second incident',+ sensor_response_list=[],+ security_level=SecurityLevel.LOW,+ alarm_lifetime_secs=300,+ timestamp=datetimeproxy.now(),+ source_alarm_id='incident-2',+ )+ manager.upsert_alarm(second_alarm)++ # No new notification: alert now has 2 alarms in its deque.+ self.assertEqual(+ mock_notification_manager.return_value.add_notification_item.call_count, 1+ )+ return+def test_alert_manager_alert_queue_integration(self):"""Test AlertManager integration with AlertQueue - critical system interaction."""manager = AlertManager()-+# Should have working alert queueself.assertIsNotNone(manager._alert_queue)@@ -259,7 +319,7 @@ class TestAlertManagerMaintenance(AsyncTaskFastTestCase):"""Test periodic maintenance handles exceptions gracefully."""async def async_test_logic():# Mock the alert queue to raise an exception- with patch.object(self.manager._alert_queue, 'remove_expired_or_acknowledged_alerts') as mock_cleanup:+ with patch.object(self.manager._alert_queue, 'remove_expired_alerts') as mock_cleanup:mock_cleanup.side_effect = Exception("Test exception")result = await self.manager.do_periodic_maintenance()diff --git a/src/hi/apps/alert/tests/test_alert_queue.py b/src/hi/apps/alert/tests/test_alert_queue.pyindex 34e7fe03..1f2c3e46 100644--- a/src/hi/apps/alert/tests/test_alert_queue.py+++ b/src/hi/apps/alert/tests/test_alert_queue.py@@ -18,17 +18,22 @@ class TestAlertQueue(BaseTestCase):def setUp(self):super().setUp()self.queue = AlertQueue()- self.test_alarm = Alarm(+ self.test_alarm = self._make_alarm('test_alarm')+ return++ def _make_alarm(self, alarm_type: str, level=AlarmLevel.WARNING,+ source_alarm_id=None) -> Alarm:+ return Alarm(alarm_source=AlarmSource.EVENT,- alarm_type='test_alarm',- alarm_level=AlarmLevel.WARNING,- title='Test Alarm',+ alarm_type=alarm_type,+ alarm_level=level,+ title=f'Alarm {alarm_type}',sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),+ source_alarm_id=source_alarm_id,)- returndef test_alert_queue_initialization(self):"""Test AlertQueue initialization - critical state setup."""@@ -137,14 +142,76 @@ class TestAlertQueue(BaseTestCase):self.assertTrue(bool(self.queue))return- def test_alert_queue_max_size_constraint(self):- """Test MAX_ALERT_LIST_SIZE constraint - critical for memory management."""- # The AlertQueue doesn't appear to enforce the MAX_ALERT_LIST_SIZE in the current code,- # but we should test that the constant exists and can be used for future enforcement- self.assertEqual(AlertQueue.MAX_ALERT_LIST_SIZE, 50)-- # If size enforcement were implemented, it would be critical business logic- # For now, just verify the constant exists as part of the class design+ def test_alert_queue_max_size_evicts_oldest_acknowledged(self):+ """At capacity, a new alert evicts the oldest acknowledged alert.+ Unacknowledged alerts are never evicted."""+ # Override the cap to a small number for test speed.+ original_cap = AlertQueue.MAX_ALERT_LIST_SIZE+ AlertQueue.MAX_ALERT_LIST_SIZE = 3+ try:+ queue = AlertQueue()+ # Fill: two acked (old, newer) and one unacked, in that order.+ acked_old = queue.add_alarm(self._make_alarm('acked_old'))+ queue.acknowledge_alert(acked_old.id)+ acked_newer = queue.add_alarm(self._make_alarm('acked_newer'))+ queue.acknowledge_alert(acked_newer.id)+ unacked = queue.add_alarm(self._make_alarm('unacked'))++ self.assertEqual(len(queue), 3)++ # Adding a fourth distinct alert should evict the OLDEST acked+ # (acked_old) and keep the unacked alert untouched.+ queue.add_alarm(self._make_alarm('new'))++ self.assertEqual(len(queue), 3)+ with self.assertRaises(KeyError):+ queue.get_alert(acked_old.id)+ # Other two survive.+ queue.get_alert(acked_newer.id)+ queue.get_alert(unacked.id)+ finally:+ AlertQueue.MAX_ALERT_LIST_SIZE = original_cap+ return++ def test_alert_queue_max_size_unacknowledged_not_evicted(self):+ """When the queue is full of only unacknowledged alerts, growth+ is allowed -- an active alert must never be silently lost."""+ original_cap = AlertQueue.MAX_ALERT_LIST_SIZE+ AlertQueue.MAX_ALERT_LIST_SIZE = 2+ try:+ queue = AlertQueue()+ queue.add_alarm(self._make_alarm('a'))+ queue.add_alarm(self._make_alarm('b'))+ self.assertEqual(len(queue), 2)+ # No acked alerts to evict; queue should grow past the cap.+ queue.add_alarm(self._make_alarm('c'))+ self.assertEqual(len(queue), 3)+ finally:+ AlertQueue.MAX_ALERT_LIST_SIZE = original_cap+ return++ def test_alert_queue_at_cap_with_no_acked_invokes_noop_eviction(self):+ """At the cap with zero acked alerts, ``_evict_oldest_acknowledged_alert``+ is still invoked (it's a no-op in this case) and the new alert+ is appended despite the cap. Pins the no-op eviction call path+ explicitly, separate from the queue-growth assertion."""+ from unittest.mock import patch+ original_cap = AlertQueue.MAX_ALERT_LIST_SIZE+ AlertQueue.MAX_ALERT_LIST_SIZE = 2+ try:+ queue = AlertQueue()+ queue.add_alarm(self._make_alarm('a'))+ queue.add_alarm(self._make_alarm('b'))+ with patch.object(+ queue, '_evict_oldest_acknowledged_alert',+ wraps=queue._evict_oldest_acknowledged_alert,+ ) as evict_spy:+ queue.add_alarm(self._make_alarm('c'))+ evict_spy.assert_called_once()+ # Eviction was a no-op; new alert appended.+ self.assertEqual(len(queue), 3)+ finally:+ AlertQueue.MAX_ALERT_LIST_SIZE = original_capreturndef test_alert_queue_last_changed_datetime_tracking(self):@@ -345,15 +412,7 @@ class TestAlertQueue(BaseTestCase):returndef test_alert_queue_remove_expired_alerts(self):- """Test remove_expired_or_acknowledged_alerts - critical for cleanup.-- Advances ``datetimeproxy`` past the alarm's expiration rather- than constructing an alarm with non-positive lifetime- (``Alarm.__post_init__`` rejects that). The alert system- consults ``datetimeproxy.now()`` for ``end_datetime``- comparison, so the simulated clock advance is what makes the- cleanup observe the alarm as expired.- """+ """Expired alerts are removed; not-yet-expired alerts survive."""from datetime import timedeltabaseline = datetimeproxy.now()expired_alarm = Alarm(@@ -366,7 +425,7 @@ class TestAlertQueue(BaseTestCase):alarm_lifetime_secs=1,timestamp=baseline,)-+# Add expired and active alarmsexpired_alert = self.queue.add_alarm(expired_alarm)active_alert = self.queue.add_alarm(self.test_alarm)@@ -375,45 +434,125 @@ class TestAlertQueue(BaseTestCase):self.assertEqual(initial_count, 2)# Advance the simulated clock past the expired alarm's end- # but still before the active alarm's. The cleanup pass reads- # the time via ``datetimeproxy.now()`` so this is sufficient- # to make it observe the first alarm as expired.+ # but still before the active alarm's.datetimeproxy.set(baseline + timedelta(seconds=10))try:- self.queue.remove_expired_or_acknowledged_alerts()+ self.queue.remove_expired_alerts()- # Should remove expired alert but keep active oneself.assertEqual(len(self.queue), 1)-- # Should not find expired alertwith self.assertRaises(KeyError):self.queue.get_alert(expired_alert.id)-- # Should still find active alertfound_alert = self.queue.get_alert(active_alert.id)self.assertEqual(found_alert, active_alert)finally:datetimeproxy.reset()return- def test_alert_queue_remove_acknowledged_alerts(self):- """Test remove_expired_or_acknowledged_alerts removes acknowledged - critical for cleanup."""- # Add alert and acknowledge it+ def test_alert_queue_acknowledged_alert_kept_as_dedup_anchor(self):+ """Acknowledged alerts stay in the queue until their natural+ ``end_datetime`` so they continue to suppress duplicate alarms+ with the same signature. This is the regression-prevention for+ the dismissed-alert-immediately-reappears bug."""alert = self.queue.add_alarm(self.test_alarm)self.queue.acknowledge_alert(alert.id)-++ # Cleanup does not remove acked-but-not-expired alerts.+ self.queue.remove_expired_alerts()self.assertEqual(len(self.queue), 1)- self.assertTrue(alert.is_acknowledged)-- # Run cleanup- self.queue.remove_expired_or_acknowledged_alerts()-- # Should remove acknowledged alert- self.assertEqual(len(self.queue), 0)-- # Should not find acknowledged alert- with self.assertRaises(KeyError):- self.queue.get_alert(alert.id)+ self.queue.get_alert(alert.id)++ # A second matching alarm is silently absorbed by the+ # acknowledged anchor -- not surfaced as a fresh alert.+ before_count = len(self.queue)+ duplicate_alarm = self._make_alarm('test_alarm')+ returned_alert = self.queue.add_alarm(duplicate_alarm)+ self.assertEqual(returned_alert.id, alert.id)+ self.assertEqual(len(self.queue), before_count)+ self.assertEqual(len(self.queue.unacknowledged_alert_list), 0)+ return++ def test_alert_queue_acknowledged_alert_distinct_incident_appends(self):+ """A new incident with the same signature but a distinct+ ``source_alarm_id`` should still append to the acked alert's+ occurrence deque, even though it doesn't re-surface. Captures+ the "new tornado warning during an acked one" path that the+ ``source_alarm_id=None`` dedup-anchor test doesn't exercise."""+ first_alarm = self._make_alarm('test_alarm', source_alarm_id='incident-1')+ alert = self.queue.add_alarm(first_alarm)+ self.queue.acknowledge_alert(alert.id)+ self.assertEqual(alert.alarm_count, 1)++ # Same signature, distinct upstream incident id.+ second_alarm = self._make_alarm('test_alarm', source_alarm_id='incident-2')+ returned_alert = self.queue.add_alarm(second_alarm)++ self.assertEqual(returned_alert.id, alert.id)+ self.assertEqual(alert.alarm_count, 2)+ # Alert stays hidden from the operator.+ self.assertEqual(len(self.queue.unacknowledged_alert_list), 0)+ return++ def test_alert_queue_acknowledged_alert_end_datetime_not_extended(self):+ """``upsert_alarm`` must not refresh ``end_datetime`` on an+ acknowledged alert; otherwise a chronic upstream condition+ could keep the suppression alive indefinitely."""+ from datetime import timedelta+ baseline = datetimeproxy.now()+ datetimeproxy.set(baseline)+ try:+ alert = self.queue.add_alarm(self.test_alarm)+ self.queue.acknowledge_alert(alert.id)+ ack_end_datetime = alert.end_datetime++ # Time passes and the same upstream condition is re-emitted.+ datetimeproxy.set(baseline + timedelta(seconds=120))+ self.queue.add_alarm(self._make_alarm('test_alarm'))++ # end_datetime unchanged: suppression still rides the+ # original window, not the latest poll.+ self.assertEqual(alert.end_datetime, ack_end_datetime)+ finally:+ datetimeproxy.reset()+ return++ def test_alert_queue_remove_expired_counts_acknowledged_among_removed(self):+ """``acknowledged_removed`` reports the subset of expired alerts+ that had been acknowledged. No longer a removal trigger; just+ a stat."""+ from datetime import timedelta+ baseline = datetimeproxy.now()+ short_lived_acked = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='short_acked',+ alarm_level=AlarmLevel.WARNING,+ title='Short-lived acked',+ sensor_response_list=[],+ security_level=SecurityLevel.LOW,+ alarm_lifetime_secs=1,+ timestamp=baseline,+ )+ short_lived_unacked = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='short_unacked',+ alarm_level=AlarmLevel.WARNING,+ title='Short-lived unacked',+ sensor_response_list=[],+ security_level=SecurityLevel.LOW,+ alarm_lifetime_secs=1,+ timestamp=baseline,+ )+ a1 = self.queue.add_alarm(short_lived_acked)+ self.queue.add_alarm(short_lived_unacked)+ self.queue.acknowledge_alert(a1.id)++ datetimeproxy.set(baseline + timedelta(seconds=10))+ try:+ result = self.queue.remove_expired_alerts()+ self.assertEqual(result.expired_removed, 2)+ self.assertEqual(result.acknowledged_removed, 1)+ self.assertEqual(result.total_removed, 2)+ finally:+ datetimeproxy.reset()returndef test_alert_queue_concurrent_access_thread_safety(self):diff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.pyindex dc581532..bddd215e 100644--- a/src/hi/apps/attribute/forms.py+++ b/src/hi/apps/attribute/forms.py@@ -116,7 +116,7 @@ class AttributeForm( forms.ModelForm ):cleaned_data = super().clean()name = cleaned_data.get('name')value = cleaned_data.get('value')-+form_is_bound = bool( self.instance.pk )if form_is_bound:if not self.instance.is_editable:@@ -125,21 +125,68 @@ class AttributeForm( forms.ModelForm ):and ( name is not None )and ( name != self.instance.name )):raise ValidationError( 'Changing name forbidden for predefined attributes.' )-+value = cleaned_data.get('value')if self.instance.is_required and is_blank( value ):self.add_error( 'value', 'A value is required.')if self.instance.value_type.is_boolean:cleaned_data['value'] = str(str_to_bool( value ))-+ elif self.instance.value_type.is_integer and not is_blank( value ):+ self._clean_integer_value( cleaned_data, value )+ elif self.instance.value_type.is_float and not is_blank( value ):+ self._clean_float_value( cleaned_data, value )+if self.cleaned_data.get('secret'):stripped_value = value.strip()value_lines = stripped_value.splitlines()if len( value_lines) > 1:self.add_error( 'value', 'Secret attributes are limited ot a single line.')-+return cleaned_data+ def _clean_integer_value(self, cleaned_data, value):+ """Server-side enforcement for ``AttributeValueType.INTEGER``+ attributes. The HTML5 ``<input type="number">`` provides only+ client-side validation; this catches direct POSTs and any path+ where the browser's check was bypassed, and applies the+ ``value_range_int()`` bounds declared on the schema."""+ try:+ int_value = int( value )+ except (ValueError, TypeError):+ self.add_error( 'value', 'Must be an integer.' )+ return+ cleaned_data['value'] = str( int_value )+ bounds = self.instance.value_range_int()+ if bounds is None:+ return+ low, high = bounds+ if int_value < low or int_value > high:+ self.add_error(+ 'value',+ f'Must be between {low} and {high}.',+ )+ return++ def _clean_float_value(self, cleaned_data, value):+ """Server-side enforcement for ``AttributeValueType.FLOAT``+ attributes. Uses ``value_range()`` (float-valued bounds) so+ float-typed schemas can declare ``[0.0, 1.0]`` and similar."""+ try:+ float_value = float( value )+ except (ValueError, TypeError):+ self.add_error( 'value', 'Must be a number.' )+ return+ bounds = self.instance.value_range()+ if bounds is None:+ return+ low, high = bounds+ if float_value < low or float_value > high:+ self.add_error(+ 'value',+ f'Must be between {low} and {high}.',+ )+ return+def save( self, commit = True ):instance = super().save( commit = False )diff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.pyindex 83d11348..550d1d2c 100644--- a/src/hi/apps/attribute/models.py+++ b/src/hi/apps/attribute/models.py@@ -1,5 +1,6 @@import jsonimport logging+from typing import Any, List, Optional, Tuplefrom django.core.files.storage import default_storagefrom django.db import models@@ -137,7 +138,7 @@ class AttributeModel(models.Model):def is_predefined(self):return bool( self.attribute_type == AttributeType.PREDEFINED )- def choices(self):+ def choices(self) -> List[ Tuple[ str, str ] ]:# First check predefined idschoice_list = PredefinedValueRanges.get_choices( self.value_range_str )if choice_list:@@ -153,7 +154,76 @@ class AttributeModel(models.Model):except json.JSONDecodeError as e:logger.error( f'Bad value range for attribute {self.name}: {e}' )pass- return dict()+ return list()++ def _parse_value_range_raw(self) -> Optional[ Tuple[ Any, Any ] ]:+ """Shared parser for ``value_range`` / ``value_range_int``.+ Returns the ``(min, max)`` pair as the raw JSON-decoded+ values without type coercion, so each typed wrapper can apply+ its own validation policy. Returns ``None`` for missing,+ unparseable, or unrecognized-shape data.++ Recognized shapes (parallel to ``choices()`` so authors can+ declare numeric ranges in either form):+ * Two-element list: ``"[5, 86400]"``+ * Object with min/max keys: ``'{"min": 5, "max": 86400}'``"""+ if not self.value_range_str:+ return None+ try:+ value_range = json.loads( self.value_range_str )+ except (json.JSONDecodeError, TypeError):+ return None+ if isinstance( value_range, list ) and len( value_range ) == 2:+ return ( value_range[0], value_range[1] )+ if ( isinstance( value_range, dict )+ and 'min' in value_range and 'max' in value_range ):+ return ( value_range['min'], value_range['max'] )+ return None++ def value_range(self) -> Optional[ Tuple[ float, float ] ]:+ """Parse ``value_range_str`` as a numeric ``(min, max)`` range+ for FLOAT-typed attributes (also serves callers that just need+ either-int-or-float bounds as floats). Returns ``None`` when+ the field is missing, malformed, or has the bounds reversed.++ Integer-typed call sites should prefer ``value_range_int()`` --+ this method coerces both bounds via ``float()`` and will+ therefore accept declarations like ``"[5.7, 10.2]"`` that an+ integer caller shouldn't honor."""+ raw = self._parse_value_range_raw()+ if raw is None:+ return None+ low_raw, high_raw = raw+ try:+ low = float( low_raw )+ high = float( high_raw )+ except (ValueError, TypeError):+ return None+ if low > high:+ return None+ return ( low, high )++ def value_range_int(self) -> Optional[ Tuple[ int, int ] ]:+ """Integer-typed variant of ``value_range()``. Accepts the same+ list / dict shapes but requires both bounds to be JSON+ integers (so ``"[5, 10]"`` is honored and ``"[5.0, 10.0]"`` is+ rejected -- the author declared floats and ``int(5.0)`` would+ silently coerce). Returns ``None`` on any failure mode of the+ underlying parse or on a non-int bound.++ ``bool`` is excluded explicitly because Python's+ ``isinstance(True, int)`` is True; allowing it would silently+ coerce a misplaced ``"[true, 100]"`` into ``(1, 100)``."""+ raw = self._parse_value_range_raw()+ if raw is None:+ return None+ low_raw, high_raw = raw+ for bound in ( low_raw, high_raw ):+ if isinstance( bound, bool ) or not isinstance( bound, int ):+ return None+ if low_raw > high_raw:+ return None+ return ( low_raw, high_raw )@propertydef supports_thumbnail_generation(self):diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_float.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_float.htmlindex a98a6562..cda01497 100644--- a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_float.html+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_float.html@@ -4,13 +4,16 @@ Renders a number input for float attributes{% endcomment %}<div class="attr-v2-float-value">- <input type="number"+ {% with bounds=attribute_form.instance.value_range %}+ <input type="number"id="{{ attribute_form.value.id_for_label }}"name="{{ attribute_form.value.html_name }}"class="form-control"value="{{ attribute_form.value.value|default_if_none:'' }}"step="any"+ {% if bounds %}min="{{ bounds.0 }}" max="{{ bounds.1 }}"{% endif %}{% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %} />+ {% endwith %}{% if attribute_form.value.errors %}<div class="attr-v2-field-errors">{% for error in attribute_form.value.errors %}diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_integer.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_integer.htmlindex 1adb5ab0..bedff2d4 100644--- a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_integer.html+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_integer.html@@ -4,13 +4,16 @@ Renders a number input for integer attributes{% endcomment %}<div class="attr-v2-integer-value">- <input type="number"+ {% with bounds=attribute_form.instance.value_range_int %}+ <input type="number"id="{{ attribute_form.value.id_for_label }}"name="{{ attribute_form.value.html_name }}"class="form-control"value="{{ attribute_form.value.value|default_if_none:'' }}"step="1"+ {% if bounds %}min="{{ bounds.0 }}" max="{{ bounds.1 }}"{% endif %}{% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %} />+ {% endwith %}{% if attribute_form.value.errors %}<div class="attr-v2-field-errors">{% for error in attribute_form.value.errors %}diff --git a/src/hi/apps/attribute/tests/test_models.py b/src/hi/apps/attribute/tests/test_models.pyindex 1cb5bca9..a4dc4f44 100644--- a/src/hi/apps/attribute/tests/test_models.py+++ b/src/hi/apps/attribute/tests/test_models.py@@ -97,7 +97,7 @@ class TestAttributeModel(BaseTestCase):# Test with invalid JSONattr.value_range_str = 'invalid json {'choices = attr.choices()- self.assertEqual(choices, {}) # Should return empty dict on parse error+ self.assertEqual(choices, [])# Test with empty value_range_strattr.value_range_str = Nonediff --git a/src/hi/apps/audio/settings.py b/src/hi/apps/audio/settings.pyindex 97310213..aa2fe610 100644--- a/src/hi/apps/audio/settings.py+++ b/src/hi/apps/audio/settings.py@@ -20,7 +20,7 @@ class AudioSetting(SettingEnum):label = 'Event Info Alert Sound',description = 'The sound to play when an event INFO level alert arrives.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.INFO,@@ -29,7 +29,7 @@ class AudioSetting(SettingEnum):label = 'Event Warning Alert Sound',description = 'The sound to play when an event WARNING level alert arrives.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.WARNING,@@ -38,7 +38,7 @@ class AudioSetting(SettingEnum):label = 'Event Critical Alert Sound',description = 'The sound to play when an event CRITICAL level alert arrives.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.CRITICAL,@@ -49,7 +49,7 @@ class AudioSetting(SettingEnum):label = 'Weather Info Alert Sound',description = 'The sound to play when a weather INFO level alert arrives.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.CHIME,@@ -58,7 +58,7 @@ class AudioSetting(SettingEnum):label = 'Weather Warning Alert Sound',description = 'The sound to play when a weather WARNING level alert arrives.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.WEATHER_ALERT,@@ -67,7 +67,7 @@ class AudioSetting(SettingEnum):label = 'Weather Critical Alert Sound',description = 'The sound to play when a weather CRITICAL level alert arrives.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.WEATHER_ALERT,@@ -78,7 +78,7 @@ class AudioSetting(SettingEnum):label = 'Tornado Alert Sound',description = 'The sound to play when a tornado alert arrives (any level).',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.TORNADO_SIREN,@@ -89,7 +89,7 @@ class AudioSetting(SettingEnum):label = 'Console Warning Sound',description = 'The sound to play when server connection is lost.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.BUZZER,@@ -98,7 +98,7 @@ class AudioSetting(SettingEnum):label = 'Console Info Sound',description = 'The sound to play when server connection is restored.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ value_range = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,is_editable = True,is_required = False,initial_value = AudioFile.STORE_DOOR_CHIME,diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.pyindex 436a84ef..77e4f5cf 100644--- a/src/hi/apps/collection/collection_manager.py+++ b/src/hi/apps/collection/collection_manager.py@@ -107,9 +107,9 @@ class CollectionManager(Singleton):return Noneif collection_view_type.is_list:return DisplayContext.ROW- # GRID, GRID_LARGE, and SECURITY all use TILE — they differ- # only in the wrapper-level column-count budget, not in the- # panel template selection.+ # GRID, GRID_LARGE, GRID_SMALL, and SECURITY all use TILE --+ # they differ only in the wrapper-level column-count budget,+ # not in the panel template selection.return DisplayContext.TILEdef create_collection( self, name : str ) -> Collection:diff --git a/src/hi/apps/collection/enums.py b/src/hi/apps/collection/enums.pyindex aeb8df3d..a164d658 100644--- a/src/hi/apps/collection/enums.py+++ b/src/hi/apps/collection/enums.py@@ -33,6 +33,7 @@ class CollectionViewType(LabeledEnum):DEFAULT = ( 'Default', '' )GRID = ( 'Grid', '' )GRID_LARGE = ( 'Grid (Large)', '' )+ GRID_SMALL = ( 'Grid (Small)', '' )LIST = ( 'List', '' )SECURITY = ( 'Security', '' )@@ -48,6 +49,10 @@ class CollectionViewType(LabeledEnum):def is_grid_large(self):return self == CollectionViewType.GRID_LARGE+ @property+ def is_grid_small(self):+ return self == CollectionViewType.GRID_SMALL+@propertydef is_list(self):return self == CollectionViewType.LISTdiff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_header.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_header.htmldeleted file mode 100644index 0d8178fc..00000000--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_header.html+++ /dev/null@@ -1,16 +0,0 @@-{% load icons %}-{% if request.view_parameters.collection_id %}-<div class="mx-1 my-2">- <a href="{% url 'collection_edit_mode' collection_id=request.view_parameters.collection_id %}"- class="btn btn-primary w-100" role="button" data-async="true">- {% icon "edit" size="md" css_class="" %}- <small>Edit:</small> {{ request.view_parameters.collection.name }}- </a>-</div>-{% else %}-<div class="alert alert-info mx-1 my-2">- No collection selected.-</div>-{% endif %}--diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_panel.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_panel.htmlindex a1cf3f42..7e5e16b9 100644--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_panel.html+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_mode_panel.html@@ -1,27 +1,26 @@+{% extends "edit/panes/sidebar_tabbed.html" %}{% load icons %}-<div class="d-flex justify-content-between my-2">- <div class="align-self-center h4">Collection Edit</div>- <div class="align-self-center ">- <a href="{% url 'edit_item_details_close' %}"- class="btn btn-sm btn-outline-danger" role="button" data-async="true">- {% icon "close" size="sm" css_class="" %}- </a>- </div>-</div>+{% block view_tab_active %} active{% endblock %}++{% block tab_content %}<div id="{{ DIVID.COLLECTION_EDIT_PANE }}">{% include "collection/edit/panes/collection_properties_edit.html" %}</div>{% if collection_position_form %}+<hr />+<div class="h5">Position</div><div id="{{ DIVID.COLLECTION_POSITION_EDIT_PANE }}">{% include "collection/edit/panes/collection_position_edit.html" %}</div>{% endif %}-<div class="my-3">+<hr class="my-4" />+<div class="my-2"><a href="{% url 'collection_edit_collection_delete' collection_id=collection.id %}"- class="btn btn-sm btn-danger btn-block btn-control" role="button" data-async="true">+ class="btn btn-outline-danger btn-sm btn-block btn-control" role="button" data-async="true">DELETE COLLECTION</a></div>+{% endblock %}diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.htmlindex ab615c73..4196b5fa 100644--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.html+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_manage_items.html@@ -1,12 +1,6 @@{% extends "edit/panes/entity_picker.html" %}{% load icons %}-{% block header %}-<div class="mt-2">- {% include "collection/edit/panes/collection_edit_mode_header.html" %}-</div>-{% endblock %}-{% block entity_groups %}{% for entity_collection_group in entity_collection_group_list %}<div class="{{ DIVID.ENTITY_PICKER_GROUP_SECTION_CLASS }}" data-group="{{ entity_collection_group.entity_group_type.label|slugify }}">diff --git a/src/hi/apps/collection/templates/collection/panes/collection_buttons.html b/src/hi/apps/collection/templates/collection/panes/collection_buttons.htmlindex aa48fb7a..a7f42cd6 100644--- a/src/hi/apps/collection/templates/collection/panes/collection_buttons.html+++ b/src/hi/apps/collection/templates/collection/panes/collection_buttons.html@@ -1,5 +1,5 @@{% load icons %}-<div class="d-flex justify-content-start draggable-container">+<div class="d-flex justify-content-start draggable-container hi-button-bar-flex">{% for collection in collection_list %}<div id="{{ collection.html_id }}-button"class="{% if request.view_parameters.is_editing %}draggable{% endif %} mx-1"@@ -8,19 +8,10 @@<a href="{% url 'collection_view' collection_id=collection.id %}"class="btn {% if collection == request.view_parameters.active_collection %}btn-secondary{% else %}btn-primary{% endif %} btn-control"role="button" >- {{ collection.name }}+ {{ collection.name|truncatechars:18 }}</a></div>{% empty %}<div><em>No collections defined.</em></div>{% endfor %}- {% if request.view_parameters.is_editing %}- <div class="ml-3">- <a href="{% url 'collection_add' %}"- class="btn btn-primary btn-control" role="button"- data-async="modal" >- {% icon "plus" size="sm" css_class="hi-icon-left" %}ADD- </a>- </div>- {% endif %}</div>diff --git a/src/hi/apps/collection/templates/collection/panes/collection_view.html b/src/hi/apps/collection/templates/collection/panes/collection_view.htmlindex 83877b2c..da97166f 100644--- a/src/hi/apps/collection/templates/collection/panes/collection_view.html+++ b/src/hi/apps/collection/templates/collection/panes/collection_view.html@@ -26,11 +26,11 @@</div>{% else %}- {# GRID, GRID_LARGE, and SECURITY dispatch panels to the TILE #}- {# context; the wrapper modifier class drives the column-count #}- {# budget. SECURITY is an aspirational placeholder, rendering #}- {# identically to GRID today. #}- <div class="collection-tile-grid{% if collection.collection_view_type.is_grid_large %} collection-tile-grid--large{% endif %}">+ {# GRID, GRID_LARGE, GRID_SMALL, and SECURITY dispatch panels #}+ {# to the TILE context; the wrapper modifier class drives the #}+ {# column-count budget. SECURITY is an aspirational placeholder, #}+ {# rendering identically to GRID today. #}+ <div class="collection-tile-grid{% if collection.collection_view_type.is_grid_large %} collection-tile-grid--large{% elif collection.collection_view_type.is_grid_small %} collection-tile-grid--small{% endif %}">{% for state_panel_data in state_panel_data_list %}<div id="{{ state_panel_data.entity.html_id }}"class="entity-item {{ state_panel_data.display_category.css_class }} {% if request.view_parameters.is_editing %}draggable{% endif %}"diff --git a/src/hi/apps/collection/tests/test_enums.py b/src/hi/apps/collection/tests/test_enums.pyindex 373614ff..b6d97ff9 100644--- a/src/hi/apps/collection/tests/test_enums.py+++ b/src/hi/apps/collection/tests/test_enums.py@@ -65,6 +65,7 @@ class TestCollectionViewType(BaseTestCase):view_type.is_default,view_type.is_grid,view_type.is_grid_large,+ view_type.is_grid_small,view_type.is_list,view_type.is_security,]diff --git a/src/hi/apps/config/setting_enums.py b/src/hi/apps/config/setting_enums.pyindex 9bb56a60..abf013fd 100644--- a/src/hi/apps/config/setting_enums.py+++ b/src/hi/apps/config/setting_enums.py@@ -1,6 +1,7 @@import importlibfrom dataclasses import dataclassfrom enum import Enum+from typing import Dict, List, Optional, Unionfrom hi.apps.attribute.enums import AttributeValueType@@ -10,10 +11,15 @@ class SettingDefinition:label : strdescription : strvalue_type : AttributeValueType- value_range_str : str+ # ``str`` carries a PredefinedValueRanges key (looked up via the+ # model's ``choices()``); ``list``/``dict`` carries an inline+ # numeric range or enum choice map (JSON-encoded into the+ # ``AttributeModel.value_range_str`` field at write time);+ # ``None`` means unbounded.+ value_range : Optional[ Union[ str, List, Dict ] ]is_editable : boolis_required : bool- initial_value : str+ initial_value : strclass SettingEnum(Enum):diff --git a/src/hi/apps/config/settings_manager.py b/src/hi/apps/config/settings_manager.pyindex 2fd65976..f09ef591 100644--- a/src/hi/apps/config/settings_manager.py+++ b/src/hi/apps/config/settings_manager.py@@ -40,22 +40,32 @@ class SettingsManager( Singleton ):returndef reload(self):+ # Build the new map locally and atomically swap. Readers+ # (``get_setting_value``) do not hold ``_attributes_lock``, so+ # mutating the live map in place would briefly expose an empty+ # or partially-populated view to any concurrent reader -- which+ # caused spurious ``None`` returns during settings saves.+ # CPython GIL dependency: lock-free reads work because the+ # name rebind ``self._attribute_value_map = ...`` is a single+ # ``STORE_ATTR`` bytecode, atomic against concurrent readers.+ # Do NOT convert ``_attribute_value_map`` to a property or+ # descriptor; that would break the atomicity guarantee.with self._attributes_lock:self._subsystem_list = sorted(self._subsystem_list, key=lambda s: s.name)- self._attribute_value_map = dict()+ new_attribute_value_map = dict()for subsystem in self._subsystem_list:try:subsystem.refresh_from_db()for subsystem_attribute in subsystem.attributes.all():attr_type = subsystem_attribute.setting_key- self._attribute_value_map[attr_type] = subsystem_attribute.value+ new_attribute_value_map[attr_type] = subsystem_attribute.valuecontinueexcept Subsystem.DoesNotExist:- # Log error - this should not normally happen outside of test teardownlogger.error(f'Subsystem {subsystem} no longer exists in database during reload. ''This may indicate a configuration issue or test teardown problem.')continue-+ self._attribute_value_map = new_attribute_value_map+self._notify_change_listeners()return@@ -133,7 +143,7 @@ def settings_manager_model_changed( sender, instance, **kwargs ):Queue the SettingsManager.reload() call to execute after the transactionis committed. This prevents reloading multiple times if multiplemodels saved as part of a transaction (which is the normal case for- SettingsDefinition and its related models.)+ SettingDefinition and its related models.)"""_settings_processor.schedule_processing()diff --git a/src/hi/apps/config/signals.py b/src/hi/apps/config/signals.pyindex 7875d97d..ebdf0a35 100644--- a/src/hi/apps/config/signals.py+++ b/src/hi/apps/config/signals.py@@ -1,3 +1,4 @@+import jsonimport loggingfrom django.db import transaction@@ -103,7 +104,9 @@ class SettingsInitializer:name = setting_definition.label,value = setting_definition.initial_value,value_type_str = str(setting_definition.value_type),- value_range_str = setting_definition.value_range_str,+ value_range_str = self._coerce_value_range_str(+ setting_definition.value_range,+ ),attribute_type_str = AttributeType.PREDEFINED,is_editable = setting_definition.is_editable,is_required = setting_definition.is_required,@@ -117,9 +120,39 @@ class SettingsInitializer:if attribute.order_id != order_id:attribute.order_id = order_idupdate_fields.append( 'order_id' )+ # Reconcile ``value_range_str`` so long-lived installs pick+ # up format corrections to a SettingDefinition's range --+ # without this, rows written under a legacy format (e.g.+ # the old dash-separated ``'5-86400'`` form) silently+ # bypass the framework's JSON-only range validation.+ expected_value_range_str = self._coerce_value_range_str(+ setting_definition.value_range,+ )+ if attribute.value_range_str != expected_value_range_str:+ attribute.value_range_str = expected_value_range_str+ update_fields.append( 'value_range_str' )if update_fields:attribute.save(update_fields = update_fields,track_history = False,)return attribute++ def _coerce_value_range_str( self, value_range ):+ # PredefinedValueRanges IDs and JSON ranges share the same DB+ # column. Strings pass through untouched; lists/dicts get+ # JSON-encoded; ``None`` becomes empty so the model's+ # ``not self.value_range_str`` early-out fires (rather than+ # storing the literal string ``'null'``). Other types are+ # rejected loudly so a miswritten SettingDefinition fails at+ # app boot rather than corrupting the DB.+ if value_range is None:+ return ''+ if isinstance( value_range, str ):+ return value_range+ if isinstance( value_range, ( list, dict )):+ return json.dumps( value_range )+ raise TypeError(+ f'SettingDefinition.value_range must be None, str,'+ f' list, or dict; got {type(value_range).__name__}.'+ )diff --git a/src/hi/apps/config/tests/test_app_settings.py b/src/hi/apps/config/tests/test_app_settings.pyindex d7da298e..a1067362 100644--- a/src/hi/apps/config/tests/test_app_settings.py+++ b/src/hi/apps/config/tests/test_app_settings.py@@ -15,7 +15,7 @@ class TestModuleSetting(SettingEnum):label='Test Setting One',description='First test setting',value_type=AttributeValueType.TEXT,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value='test_default_one',@@ -24,7 +24,7 @@ class TestModuleSetting(SettingEnum):label='Test Setting Two',description='Second test setting',value_type=AttributeValueType.INTEGER,- value_range_str='[0, 100]',+ value_range=[0, 100],is_editable=True,is_required=False,initial_value='10',@@ -36,7 +36,7 @@ class AnotherTestSetting(SettingEnum):label='Another Test Setting',description='Another test setting',value_type=AttributeValueType.BOOLEAN,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value='false',@@ -248,7 +248,7 @@ class TestAppSettings(BaseTestCase):self.assertEqual(setting_two_def.label, 'Test Setting Two')self.assertEqual(setting_two_def.description, 'Second test setting')self.assertEqual(setting_two_def.value_type, AttributeValueType.INTEGER)- self.assertEqual(setting_two_def.value_range_str, '[0, 100]')+ self.assertEqual(setting_two_def.value_range, [0, 100])self.assertTrue(setting_two_def.is_editable)self.assertFalse(setting_two_def.is_required)self.assertEqual(setting_two_def.initial_value, '10')diff --git a/src/hi/apps/config/tests/test_integration.py b/src/hi/apps/config/tests/test_integration.pyindex 4817eef1..dd2d034d 100644--- a/src/hi/apps/config/tests/test_integration.py+++ b/src/hi/apps/config/tests/test_integration.py@@ -17,7 +17,7 @@ class IntegrationTestSettings(SettingEnum):label='Test Workflow Setting',description='Setting for testing complete workflows',value_type=AttributeValueType.TEXT,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value='workflow_default',@@ -26,7 +26,7 @@ class IntegrationTestSettings(SettingEnum):label='Notification Setting',description='Setting for testing change notifications',value_type=AttributeValueType.BOOLEAN,- value_range_str='',+ value_range=None,is_editable=True,is_required=False,initial_value='true',diff --git a/src/hi/apps/config/tests/test_setting_enums.py b/src/hi/apps/config/tests/test_setting_enums.pyindex 407f81ed..23c3ff55 100644--- a/src/hi/apps/config/tests/test_setting_enums.py+++ b/src/hi/apps/config/tests/test_setting_enums.py@@ -13,7 +13,7 @@ class TestSetting(SettingEnum):label='First Setting',description='Description for first setting',value_type=AttributeValueType.TEXT,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value='default_first',@@ -22,7 +22,7 @@ class TestSetting(SettingEnum):label='Second Setting',description='Description for second setting',value_type=AttributeValueType.INTEGER,- value_range_str='[1, 100]',+ value_range=[1, 100],is_editable=False,is_required=False,initial_value='50',@@ -34,7 +34,7 @@ class AnotherTestSetting(SettingEnum):label='Another Setting',description='Description for another setting',value_type=AttributeValueType.BOOLEAN,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value='true',@@ -47,7 +47,7 @@ class NestedModuleTestSetting(SettingEnum):label='Nested Setting',description='Setting in nested module context',value_type=AttributeValueType.TEXT,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value='nested_default',@@ -57,24 +57,28 @@ class NestedModuleTestSetting(SettingEnum):class TestSettingDefinition(BaseTestCase):def test_setting_definition_creation(self):- """Test SettingDefinition dataclass creation."""+ """Test SettingDefinition dataclass creation. The ``str`` form+ of ``value_range`` is the canonical PredefinedValueRanges+ identifier shape -- the dataclass passes it through verbatim+ and the framework dispatches on it at choices()-lookup time."""+ from hi.apps.attribute.value_ranges import PredefinedValueRangesdefinition = SettingDefinition(label='Test Setting',description='A test setting for testing',- value_type=AttributeValueType.TEXT,- value_range_str='[a-z]+',+ value_type=AttributeValueType.ENUM,+ value_range=PredefinedValueRanges.TIMEZONE_CHOICES_ID,is_editable=True,is_required=False,- initial_value='default',+ initial_value='America/Chicago',)-+self.assertEqual(definition.label, 'Test Setting')self.assertEqual(definition.description, 'A test setting for testing')- self.assertEqual(definition.value_type, AttributeValueType.TEXT)- self.assertEqual(definition.value_range_str, '[a-z]+')+ self.assertEqual(definition.value_type, AttributeValueType.ENUM)+ self.assertEqual(definition.value_range, PredefinedValueRanges.TIMEZONE_CHOICES_ID)self.assertTrue(definition.is_editable)self.assertFalse(definition.is_required)- self.assertEqual(definition.initial_value, 'default')+ self.assertEqual(definition.initial_value, 'America/Chicago')returndef test_setting_definition_all_value_types(self):@@ -95,7 +99,7 @@ class TestSettingDefinition(BaseTestCase):label=f'{value_type.name} Setting',description=f'Setting for {value_type.name}',value_type=value_type,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value=initial_value,@@ -225,13 +229,13 @@ class TestSettingEnum(BaseTestCase):editable_setting = TestSetting.FIRST_SETTINGself.assertTrue(editable_setting.definition.is_editable)self.assertTrue(editable_setting.definition.is_required)- self.assertEqual(editable_setting.definition.value_range_str, '')-+ self.assertIsNone(editable_setting.definition.value_range)+# Test non-editable setting attributesreadonly_setting = TestSetting.SECOND_SETTINGself.assertFalse(readonly_setting.definition.is_editable)self.assertFalse(readonly_setting.definition.is_required)- self.assertEqual(readonly_setting.definition.value_range_str, '[1, 100]')+ self.assertEqual(readonly_setting.definition.value_range, [1, 100])returndef test_enum_value_type_preservation(self):diff --git a/src/hi/apps/config/tests/test_settings_manager.py b/src/hi/apps/config/tests/test_settings_manager.pyindex a4f40549..7d04ef49 100644--- a/src/hi/apps/config/tests/test_settings_manager.py+++ b/src/hi/apps/config/tests/test_settings_manager.py@@ -17,7 +17,7 @@ class TestSetting(SettingEnum):label='Test Setting',description='A test setting',value_type=AttributeValueType.TEXT,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value='test_initial',diff --git a/src/hi/apps/config/tests/test_signals.py b/src/hi/apps/config/tests/test_signals.pynew file mode 100644index 00000000..abbb019a--- /dev/null+++ b/src/hi/apps/config/tests/test_signals.py@@ -0,0 +1,59 @@+"""Tests for ``SettingsInitializer._coerce_value_range_str``.++Pins the type-coercion contract that bridges+``SettingDefinition.value_range`` (Python-typed input) to+``AttributeModel.value_range_str`` (string-stored DB column).+"""++from hi.apps.config.signals import SettingsInitializer+from hi.testing.base_test_case import BaseTestCase+++class TestCoerceValueRangeStr(BaseTestCase):++ def setUp(self):+ super().setUp()+ self._initializer = SettingsInitializer()++ def test_none_becomes_empty_string(self):+ """``None`` -> ``''`` so the model's ``not self.value_range_str``+ early-out fires. Must NOT become the literal string ``'null'``."""+ self.assertEqual(self._initializer._coerce_value_range_str(None), '')++ def test_str_passes_through_unchanged(self):+ """PredefinedValueRanges identifier strings carry across the+ boundary untouched -- they're consumed by+ ``PredefinedValueRanges.get_choices`` later."""+ self.assertEqual(+ self._initializer._coerce_value_range_str(+ 'hi.apps.attribute.value_ranges.timezone'+ ),+ 'hi.apps.attribute.value_ranges.timezone',+ )++ def test_list_is_json_encoded(self):+ """Inline numeric ranges round-trip through JSON. The model's+ ``value_range_int`` / ``value_range`` parsers expect this+ format."""+ self.assertEqual(+ self._initializer._coerce_value_range_str([1, 100]),+ '[1, 100]',+ )++ def test_dict_is_json_encoded(self):+ """Inline enum choice maps also round-trip through JSON."""+ self.assertEqual(+ self._initializer._coerce_value_range_str({'on': 'On', 'off': 'Off'}),+ '{"on": "On", "off": "Off"}',+ )++ def test_unsupported_type_raises_type_error(self):+ """A miswritten SettingDefinition (e.g., a stray tuple, set, or+ object) must fail loudly at app boot rather than silently+ corrupting the DB with an un-roundtrippable payload."""+ with self.assertRaises(TypeError):+ self._initializer._coerce_value_range_str((1, 100))+ with self.assertRaises(TypeError):+ self._initializer._coerce_value_range_str({1, 2, 3})+ with self.assertRaises(TypeError):+ self._initializer._coerce_value_range_str(42)diff --git a/src/hi/apps/console/console_helper.py b/src/hi/apps/console/console_helper.pyindex 09f81f35..ee8eb5ac 100644--- a/src/hi/apps/console/console_helper.py+++ b/src/hi/apps/console/console_helper.py@@ -77,7 +77,13 @@ class ConsoleSettingsHelper( Singleton, SettingsMixin ):label can honor cross-entity context:1. Strip whole-word "camera" tokens (case-insensitive) and- collapse intermediate whitespace.+ collapse intermediate whitespace. As a follow-up suffix+ pass, also strip a trailing "camera" (case-insensitive, with+ or without a preceding space) when the original name is at+ least 9 characters -- catches concatenated forms like+ "BackdoorCamera" the word-boundary regex misses, while the+ length floor avoids reducing short names like "MyCamera"+ to a 2-letter label.2. If two or more entities share a leading whole-word token,strip that common token-prefix from each. Only applied whenevery per-entity result remains non-empty after stripping;@@ -91,7 +97,10 @@ class ConsoleSettingsHelper( Singleton, SettingsMixin ):"""def strip_camera_tokens( name : str ) -> str:cleaned = re.sub( r'\bcamera\b', '', name, flags = re.IGNORECASE )- return re.sub( r'\s+', ' ', cleaned ).strip()+ cleaned = re.sub( r'\s+', ' ', cleaned ).strip()+ if len( name ) >= 9 and cleaned.lower().endswith( 'camera' ):+ cleaned = cleaned[ :-6 ].rstrip()+ return cleanedstripped : Dict[ int, str ] = {e.id: strip_camera_tokens( e.name ) or e.name for e in entity_listdiff --git a/src/hi/apps/console/settings.py b/src/hi/apps/console/settings.pyindex 75906d45..a74bbe33 100644--- a/src/hi/apps/console/settings.py+++ b/src/hi/apps/console/settings.py@@ -18,7 +18,7 @@ class ConsoleSetting( SettingEnum ):label = 'Timezone',description = 'Timezone to use for display',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.TIMEZONE_CHOICES_ID,+ value_range = PredefinedValueRanges.TIMEZONE_CHOICES_ID,is_editable = True,is_required = True,initial_value = 'America/Chicago',@@ -27,7 +27,7 @@ class ConsoleSetting( SettingEnum ):label = 'Display Units',description = 'Units used when displaying',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.UNITS_CHOICES_ID,+ value_range = PredefinedValueRanges.UNITS_CHOICES_ID,is_editable = True,is_required = True,initial_value = str( DisplayUnits.default() ),@@ -36,7 +36,7 @@ class ConsoleSetting( SettingEnum ):label = 'Latitude, Longitude',description = 'Latitude and longitude. e.g., for weather data',value_type = AttributeValueType.TEXT,- value_range_str = '',+ value_range = None,is_editable = True,is_required = True,initial_value = DEFAULT_GEO_LOCATION,@@ -45,7 +45,7 @@ class ConsoleSetting( SettingEnum ):label = 'Theme',description = 'Overall look and feel of interfaces',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.THEME_CHOICES_ID,+ value_range = PredefinedValueRanges.THEME_CHOICES_ID,is_editable = True,is_required = True,initial_value = str( Theme.default() ),@@ -54,7 +54,7 @@ class ConsoleSetting( SettingEnum ):label = 'Lock Password',description = 'Password to use to unlock console',value_type = AttributeValueType.SECRET,- value_range_str = '',+ value_range = None,is_editable = True,is_required = False,initial_value = '',@@ -63,7 +63,7 @@ class ConsoleSetting( SettingEnum ):label = 'Sleep Overlay Opacity',description = 'Opacity to use for sleep mode: 0.0 for none to 1.0 for fully opaque.',value_type = AttributeValueType.FLOAT,- value_range_str = '[ 0.0, 1.0 ]',+ value_range = [ 0.0, 1.0 ],is_editable = True,is_required = True,initial_value = '0.95',@@ -72,7 +72,7 @@ class ConsoleSetting( SettingEnum ):label = 'Auto View Switching',description = 'Enable automatic view switching for alerts',value_type = AttributeValueType.BOOLEAN,- value_range_str = '',+ value_range = None,is_editable = True,is_required = True,initial_value = 'true',@@ -81,7 +81,7 @@ class ConsoleSetting( SettingEnum ):label = 'Auto View Duration (seconds)',description = 'How long to show auto-switched view before reverting',value_type = AttributeValueType.INTEGER,- value_range_str = '',+ value_range = None,is_editable = True,is_required = True,initial_value = '30',diff --git a/src/hi/apps/edit/templates/edit/panes/entity_picker.html b/src/hi/apps/edit/templates/edit/panes/entity_picker.htmlindex 34c8a89d..6c5d2d7a 100644--- a/src/hi/apps/edit/templates/edit/panes/entity_picker.html+++ b/src/hi/apps/edit/templates/edit/panes/entity_picker.html@@ -1,33 +1,29 @@+{% extends "edit/panes/sidebar_tabbed.html" %}{% load icons %}++{% block items_tab_active %} active{% endblock %}++{% block tab_content %}<div class="entity-picker-container"><div class="entity-picker-panel"><div class="entity-picker-header">- {% block header %}- {# Override this block in child templates to add specific header content #}- {% endblock %}- <div class="d-flex justify-content-between align-items-center mb-2">- <h4 class="mb-0">Items</h4>- <div class="d-flex">- <a href="{% url 'entity_edit_archive_list' %}"- class="btn btn-outline-secondary btn-sm btn-control mr-2" role="button"- data-async="modal" >- {% icon "history" size="sm" css_class="hi-icon-left" %}ARCHIVED- </a>- <a href="{% url 'entity_edit_entity_add' %}"- class="btn btn-primary btn-sm btn-control" role="button"- data-async="modal" >- {% icon "plus" size="sm" css_class="hi-icon-left" %}ADD NEW- </a>- </div>+ <div class="my-2">+ <a href="{% url 'entity_edit_entity_add' %}"+ class="btn btn-add btn-block btn-control" role="button"+ data-async="modal">+ {% icon "plus" size="sm" css_class="hi-icon-left" %}ADD NEW ITEM+ </a></div><div class="search-container mb-3"><div class="input-group">- <input type="text" id="{{ DIVID.ENTITY_PICKER_SEARCH_INPUT_ID }}" class="form-control entity-search-input"+ <input type="text" id="{{ DIVID.ENTITY_PICKER_SEARCH_INPUT_ID }}"+ class="form-control entity-search-input"placeholder="Search items..."><div class="input-group-append">- <button type="button" class="btn btn-outline-secondary {{ DIVID.ENTITY_PICKER_SEARCH_CLEAR_CLASS }}"+ <button type="button"+ class="btn btn-outline-secondary {{ DIVID.ENTITY_PICKER_SEARCH_CLEAR_CLASS }}"title="Clear search">{% icon "close" size="sm" %}</button>@@ -36,16 +32,20 @@</div><div class="filter-toggles mb-3">- <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }} active" {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_FILTER_ALL }}">+ <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }} active"+ {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_FILTER_ALL }}">All</button>- <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }}" {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_STATUS_IN_VIEW }}">+ <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }}"+ {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_STATUS_IN_VIEW }}">In View</button>- <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }}" {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_STATUS_NOT_IN_VIEW }}">+ <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }}"+ {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_STATUS_NOT_IN_VIEW }}">Not in View</button>- <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }}" {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_STATUS_UNUSED }}">+ <button class="{{ DIVID.ENTITY_PICKER_FILTER_BTN_CLASS }}"+ {{ DIVID.ENTITY_PICKER_DATA_FILTER_ATTR }}="{{ DIVID.ENTITY_PICKER_STATUS_UNUSED }}">Unused</button></div>@@ -59,6 +59,15 @@{% block collections_section %}{# Override this block for location views that need collections section #}{% endblock %}++ <div class="my-3">+ <a href="{% url 'entity_edit_archive_list' %}"+ class="btn btn-sm btn-outline-secondary btn-block btn-control" role="button"+ data-async="modal">+ {% icon "history" size="sm" css_class="hi-icon-left" %}ARCHIVED ITEMS+ </a>+ </div></div></div>-</div>\ No newline at end of file+</div>+{% endblock %}diff --git a/src/hi/apps/edit/templates/edit/panes/sidebar_tabbed.html b/src/hi/apps/edit/templates/edit/panes/sidebar_tabbed.htmlnew file mode 100644index 00000000..d54ba799--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/sidebar_tabbed.html@@ -0,0 +1,54 @@+{% comment %}+Edit-mode sidebar base. Three tabs -- Items / View / Space -- pure+visual chrome: each tab is an antinode link that loads a different+side-panel template, and the loaded template hardcodes its own+``active_tab`` block. No client-side tab state. URL routing branches+on ``request.view_parameters.view_type`` so LocationView and+CollectionView contexts dispatch to the right manage-items / edit+target without per-child boilerplate.++Child templates override:+ active_tab - one of ``items`` / ``view`` / ``space``.+ tab_header - optional title strip inside the pane (e.g.+ ``Editing: <name>``); omitted on the default+ Items picker view.+ tab_content - the pane body.+{% endcomment %}+{% load icons %}++{% comment %}+Context-aware URL resolution: the Items + View tabs route differently+depending on whether the active view is a LocationView or a+CollectionView. Space tab always points at the active location.+{% endcomment %}+{% if request.view_parameters.view_type.is_collection %}+ {% url 'collection_edit_collection_manage_items' as items_tab_url %}+ {% if request.view_parameters.collection_id %}+ {% url 'collection_edit_mode' collection_id=request.view_parameters.collection_id as view_tab_url %}+ {% endif %}+{% else %}+ {% url 'location_edit_location_view_manage_items' as items_tab_url %}+ {% if request.view_parameters.location_view.id %}+ {% url 'location_view_edit_mode' location_view_id=request.view_parameters.location_view.id as view_tab_url %}+ {% endif %}+{% endif %}+{% if request.view_parameters.location.id %}+ {% url 'location_edit_mode' location_id=request.view_parameters.location.id as space_tab_url %}+{% endif %}++<nav class="hi-edit-sidebar-tabs">+ <a href="{{ items_tab_url|default:'#' }}"+ class="hi-edit-sidebar-tab{% block items_tab_active %}{% endblock %}{% if not items_tab_url %} disabled{% endif %}"+ {% if items_tab_url %}data-async="true"{% endif %}>Items</a>+ <a href="{{ view_tab_url|default:'#' }}"+ class="hi-edit-sidebar-tab{% block view_tab_active %}{% endblock %}{% if not view_tab_url %} disabled{% endif %}"+ {% if view_tab_url %}data-async="true"{% endif %}>{% if request.view_parameters.view_type.is_collection %}Collection{% else %}View{% endif %}</a>+ <a href="{{ space_tab_url|default:'#' }}"+ class="hi-edit-sidebar-tab{% block space_tab_active %}{% endblock %}{% if not space_tab_url %} disabled{% endif %}"+ {% if space_tab_url %}data-async="true"{% endif %}>Space</a>+</nav>++<div class="hi-edit-sidebar-content">+ {% block tab_header %}{% endblock %}+ {% block tab_content %}{% endblock %}+</div>diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.htmlindex 1de413fd..ab4f162f 100644--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html@@ -1,55 +1,44 @@+{% extends "edit/panes/sidebar_tabbed.html" %}{% load icons static %}{% load integration_tags %}-<div class="d-flex justify-content-between mt-2">- <div class="h4">Item Layout</div>- <div class="">- <a href="{% url 'edit_item_details_close' %}"- class="btn btn-sm btn-outline-danger" role="button" data-async="true">- {% icon "close" size="sm" css_class="" %}- </a>- </div>-</div>+{% comment %}+Drilled-in entity detail. Reached by clicking an icon in the main+pane (not by a tab), so the Items tab stays marked active to show+the user where they are within the sidebar's domain model.+{% endcomment %}-{% if entity.integration_id %}-<div class="my-2">- <div class="text-muted">- {% integration_logo_path entity as logo_path %}- {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}- From: <strong>{% integration_display_name entity %}</strong>- </div>-</div>-{% elif entity.previous_integration_id %}-<div class="my-2">- <div class="text-muted font-italic">- {% previous_integration_logo_path entity as prev_logo_path %}- {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}- From: <strong>{% previous_integration_display_name entity %}</strong>+{% block items_tab_active %} active{% endblock %}++{% block tab_header %}+<div class="d-flex justify-content-between align-items-center mb-2">+ <div class="text-muted small">+ {% if entity.integration_id %}+ {% integration_logo_path entity as logo_path %}+ {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}+ From: <strong>{% integration_display_name entity %}</strong>+ {% elif entity.previous_integration_id %}+ <span class="font-italic">+ {% previous_integration_logo_path entity as prev_logo_path %}+ {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}+ From: <strong>{% previous_integration_display_name entity %}</strong>+ </span>+ {% else %}+ Item Details+ {% endif %}</div>+ <a href="{% url 'edit_item_details_close' %}"+ class="hi-tap-target text-muted" role="button" data-async="true"+ title="Back to items">+ {% icon "close" size="md" %}+ </a></div>-{% endif %}+{% endblock %}+{% block tab_content %}<div id="{{ DIVID.ENTITY_PROPERTIES_PANE }}">{% include "entity/edit/panes/entity_properties_edit.html" %}</div>-{% if not entity.integration_id %}-<div class="my-2">- <a href="{% url 'entity_edit_entity_archive' entity_id=entity.id %}"- class="btn btn-sm btn-outline-secondary btn-block btn-control" role="button" data-async="modal">- {% icon "history" size="sm" css_class="hi-icon-left" %}ARCHIVE ITEM- </a>-</div>-{% endif %}--{% if entity.can_user_delete %}-<div class="my-2">- <a href="{% url 'entity_edit_entity_delete' entity_id=entity.id %}"- class="btn btn-sm btn-danger btn-block btn-control" role="button" data-async="true">- DELETE ITEM- </a>-</div>-{% endif %}-<hr /><div class="h5">Paired Items</div><div id="hi-edit-entity-principals">@@ -60,20 +49,37 @@<em>No current pairings.</em>{% endfor %}</ul>-- <div class="">- <a href="{% url 'entity_edit_manage_pairings' entity_id=entity.id %}"- class="btn btn-sm btn-primary btn-block btn-control" role="button" data-async="true">- MANAGE PAIRINGS- </a>- </div>-+ <a href="{% url 'entity_edit_manage_pairings' entity_id=entity.id %}"+ class="btn btn-outline-primary btn-block btn-control" role="button" data-async="true">+ MANAGE PAIRINGS+ </a></div>+{% if entity_position_form %}<hr /><div class="h5">Geometry</div>-<div id="{{ DIVID.ENTITY_POSITION_EDIT_PANE }}" class="mb-4">+<div id="{{ DIVID.ENTITY_POSITION_EDIT_PANE }}">{% include "entity/edit/panes/entity_position_edit.html" %}</div>{% endif %}+{% if not entity.integration_id or entity.can_user_delete %}+<hr class="my-4" />+{% if not entity.integration_id %}+<div class="my-2">+ <a href="{% url 'entity_edit_entity_archive' entity_id=entity.id %}"+ class="btn btn-outline-secondary btn-sm btn-block btn-control" role="button" data-async="modal">+ {% icon "history" size="sm" css_class="hi-icon-left" %}ARCHIVE ITEM+ </a>+</div>+{% endif %}+{% if entity.can_user_delete %}+<div class="my-2">+ <a href="{% url 'entity_edit_entity_delete' entity_id=entity.id %}"+ class="btn btn-outline-danger btn-sm btn-block btn-control" role="button" data-async="true">+ DELETE ITEM+ </a>+</div>+{% endif %}+{% endif %}+{% endblock %}diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.htmlindex aeb2a3c2..e239b197 100644--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html@@ -1,7 +1,8 @@{% load icons %}<form action="{% url 'entity_properties_edit' entity_id=entity.id %}"method="post"- class="form" data-async="true">+ class="form" data-async="true"+ oninput="Hi.updateFormDirtyState(this)">{% csrf_token %}<div>{% include "entity/edit/panes/entity_edit_form.html" %}@@ -9,7 +10,7 @@<div class="text-center" ><button id="hi-entity-properties-edit-button" type="submit" class="btn btn-primary btn-block"- name="action" value="update">+ name="action" value="update" disabled>{% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE</button></div>diff --git a/src/hi/apps/event/migrations/0007_replace_zero_alarm_lifetime.py b/src/hi/apps/event/migrations/0007_replace_zero_alarm_lifetime.pyindex 6a6d5be5..07d9930f 100644--- a/src/hi/apps/event/migrations/0007_replace_zero_alarm_lifetime.py+++ b/src/hi/apps/event/migrations/0007_replace_zero_alarm_lifetime.py@@ -5,22 +5,16 @@ alarm-queue layer never honored that intent — it treated zero as"expires immediately", which made connectivity and battery alarmssilently vanish on creation.-The new contract (see ``Alarm.MAX_LIFETIME_SECS`` and-``Alarm.__post_init__``): use the explicit MAX value for-"effectively never expires"; zero is rejected at construction. This-migration normalizes any pre-existing zero rows to the same MAX so-their alarms behave correctly going forward.--Reverse path is intentionally a no-op — once normalized to MAX, the-original zero values are not preserved (they were broken anyway).+Reverse path is intentionally a no-op, the original zero values are not+preserved (they were broken anyway).+"""from django.db import migrations# Inlined to avoid importing from ``hi.apps.alert.alarm`` inside a# migration: imports of app-level models from migrations are fragile-# during squash / rebuild cycles. This value must stay in sync with-# ``Alarm.MAX_LIFETIME_SECS``.+# during squash / rebuild cycles._MAX_LIFETIME_SECS = 365 * 24 * 60 * 60diff --git a/src/hi/apps/event/models.py b/src/hi/apps/event/models.pyindex fd232d32..3ac857b1 100644--- a/src/hi/apps/event/models.py+++ b/src/hi/apps/event/models.py@@ -176,17 +176,9 @@ class AlarmAction( models.Model ):max_length = 32,null = False, blank = False,)-- # How long will this alarm be relevant to the user. Alarms exist- # until they expire or are acknowledged. Use ``Alarm.MAX_LIFETIME_SECS``- # for an alarm that should remain visible until the user- # acknowledges it (zero would expire immediately and is rejected- # by ``Alarm.__post_init__``).- #alarm_lifetime_secs = models.PositiveIntegerField('Lifetime Secs',)-created_datetime = models.DateTimeField('Created',auto_now_add = True,diff --git a/src/hi/apps/location/templates/location/edit/panes/location_edit_mode_panel.html b/src/hi/apps/location/templates/location/edit/panes/location_edit_mode_panel.htmlindex 3387897e..85f99491 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_edit_mode_panel.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_edit_mode_panel.html@@ -1,13 +1,27 @@+{% extends "edit/panes/sidebar_tabbed.html" %}{% load icons %}-<div class="d-flex justify-content-between my-2">- <div class="align-self-center h4">Space Layout</div>- <div class="align-self-center">- <a href="{% url 'edit_item_details_close' %}"- class="btn btn-sm btn-outline-danger" role="button" data-async="true">- {% icon "close" size="sm" css_class="" %}- </a>- </div>-</div>++{% block space_tab_active %} active{% endblock %}++{% block tab_content %}<div id="{{ DIVID.LOCATION_PROPERTIES_PANE }}">{% include "location/edit/panes/location_properties_edit.html" %}</div>++<div class="mt-3">+ <a href="{% url 'location_svg_background' location_id=location.id %}"+ id="hi-svg-background-link" class="btn btn-outline-primary btn-block btn-control" role="button"+ data-async="true">+ {% icon "layers" size="sm" css_class="hi-icon-left" %}BACKGROUND IMAGE+ </a>+</div>++<hr class="my-4" />+<div class="my-2">+ <a href="{% url 'location_edit_location_delete' location_id=location.id %}"+ id="hi-delete-location-link" class="btn btn-outline-danger btn-sm btn-block btn-control" role="button"+ data-async="true">+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DELETE SPACE AND ALL VIEWS+ </a>+</div>+{% endblock %}diff --git a/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.html b/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.htmlindex 8651e070..c680f6ca 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_properties_edit.html@@ -2,35 +2,17 @@<form action="{% url 'location_properties_edit' location_id=location.id %}"method="post"- class="form" data-async="true">+ class="form" data-async="true"+ oninput="Hi.updateFormDirtyState(this)">{% csrf_token %}<div>{% include "location/edit/panes/location_edit_form.html" %}</div>-+<div class="sidebar-form-actions"><button id="hi-location-properties-edit-button" type="submit" class="btn btn-primary btn-block"- name="action" value="update">+ name="action" value="update" disabled>{% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE</button></div></form>--<hr />-{% if request.view_parameters.is_editing %}-<div class="sidebar-form-actions">- <a href="{% url 'location_svg_background' location_id=location.id %}"- id="hi-svg-background-link" class="btn btn-tertiary btn-block" role="button"- data-async="true">- {% icon "layers" size="sm" css_class="hi-icon-left" %}BACKGROUND IMAGE- </a>-</div>--<div class="sidebar-form-actions pt-4">- <a href="{% url 'location_edit_location_delete' location_id=location.id %}"- id="hi-delete-location-link" class="btn btn-sm btn-danger btn-block btn-control" role="button"- data-async="true">- {% icon "delete" size="sm" css_class="hi-icon-left" %}DELETE SPACE AND ALL VIEWS- </a>-</div>-{% endif %}diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_header.html b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_header.htmldeleted file mode 100644index 68a32bf6..00000000--- a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_header.html+++ /dev/null@@ -1,14 +0,0 @@-{% load icons %}-{% if request.view_parameters.location_view.id %}-<div class="mx-1 my-2">- <a href="{% url 'location_view_edit_mode' location_view_id=request.view_parameters.location_view.id %}"- class="btn btn-primary w-100" role="button" data-async="true">- {% icon "edit" size="md" css_class="" %}- <small>Edit:</small> {{ request.view_parameters.location_view.name }}- </a>-</div>-{% else %}-<div class="alert alert-info mx-1 my-2">- No view selected.-</div>-{% endif %}diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_panel.html b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_panel.htmlindex eb86e74c..6a981737 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_panel.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_edit_mode_panel.html@@ -1,13 +1,19 @@+{% extends "edit/panes/sidebar_tabbed.html" %}{% load icons %}-<div class="d-flex justify-content-between my-2">- <div class="align-self-center h4">View Layout</div>- <div class="align-self-center">- <a href="{% url 'edit_item_details_close' %}"- class="btn btn-sm btn-outline-danger" role="button" data-async="true">- {% icon "close" size="sm" css_class="" %}- </a>- </div>-</div>++{% block view_tab_active %} active{% endblock %}++{% block tab_content %}<div id="{{ DIVID.LOCATION_VIEW_EDIT_PANE }}">{% include "location/edit/panes/location_view_properties_edit.html" %}</div>++<hr class="my-4" />+<div class="my-2">+ <a href="{% url 'location_edit_location_view_delete' location_view_id=location_view.id %}"+ id="hi-delete-location-view-link" class="btn btn-outline-danger btn-sm btn-block btn-control" role="button"+ data-async="true">+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DELETE THIS VIEW+ </a>+</div>+{% endblock %}diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html b/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.htmlindex 169f2c71..741936b5 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html@@ -1,12 +1,6 @@{% extends "edit/panes/entity_picker.html" %}{% load icons %}-{% block header %}-<div class="mt-2">- {% include "location/edit/panes/location_view_edit_mode_header.html" %}-</div>-{% endblock %}-{% block entity_groups %}{% for entity_view_group in entity_view_group_list %}<div class="{{ DIVID.ENTITY_PICKER_GROUP_SECTION_CLASS }}" data-group="{{ entity_view_group.entity_group_type.label|slugify }}">diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_properties_edit.html b/src/hi/apps/location/templates/location/edit/panes/location_view_properties_edit.htmlindex a30d1989..e17b5ea6 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_view_properties_edit.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_properties_edit.html@@ -1,25 +1,18 @@{% load icons %}<form action="{% url 'location_view_edit_mode' location_view_id=location_view.id %}"method="post"- class="form" data-async="true">+ class="form" data-async="true"+ oninput="Hi.updateFormDirtyState(this)">{% csrf_token %}-+<div>{% include "location/edit/panes/location_view_edit_mode_form.html" %}</div><div class="sidebar-form-actions"><button id="hi-add-location-view-button" type="submit" class="btn btn-primary btn-block"- name="action" value="update">+ name="action" value="update" disabled>{% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE</button></div></form>-<div class="sidebar-form-actions">- <a href="{% url 'location_edit_location_view_delete' location_view_id=location_view.id %}"- id="hi-delete-location-view-link" class="btn btn-sm btn-danger btn-block btn-control" role="button"- data-async="true">- {% icon "delete" size="sm" css_class="hi-icon-left" %}DELETE THIS VIEW- </a>-</div>-diff --git a/src/hi/apps/location/templates/location/panes/location_dropdown.html b/src/hi/apps/location/templates/location/panes/location_dropdown.htmlindex 2591d853..a1df376c 100644--- a/src/hi/apps/location/templates/location/panes/location_dropdown.html+++ b/src/hi/apps/location/templates/location/panes/location_dropdown.html@@ -4,17 +4,18 @@<div class="dropdown"><button class="btn btn-outline-primary btn-control dropdown-toggle" type="button"id="hi-location-menu" data-toggle="dropdown">- {% icon "layers" size="sm" css_class="hi-icon-left" %}SWITCH SPACE+ {% icon "layers" size="sm" css_class="hi-icon-left" %}ALL SPACES<span class="caret"></span></button><div class="dropdown-menu"role="menu" aria-labelledby="hi-location-menu">{% for location in location_list %}- {% if forloop.counter > 1 %}- <div class="dropdown-divider"></div>- {% endif %}- <a role="menuitem" class="dropdown-item plain"- href="{% url 'location_switch' location_id=location.id %} ">+ <a role="menuitem"+ class="dropdown-item plain{% if location == request.view_parameters.location %} active{% endif %}"+ href="{% url 'location_switch' location_id=location.id %}">+ {% if location == request.view_parameters.location %}+ {% icon "check-circle" size="sm" css_class="hi-icon-left" %}+ {% endif %}{{ location.name }}</a>{% empty %}@@ -24,7 +25,7 @@{% endfor %}{% if request.view_parameters.is_editing %}<div class="dropdown-divider"></div>- <a role="menuitem" class="dropdown-item plain"+ <a role="menuitem" class="dropdown-item dropdown-item-add"href="{% url 'location_edit_location_add' %}"data-async="modal">{% icon "plus" size="sm" css_class="hi-icon-left" %}ADD NEW SPACEdiff --git a/src/hi/apps/location/templates/location/panes/location_view_buttons.html b/src/hi/apps/location/templates/location/panes/location_view_buttons.htmlindex 8d801329..01b61c03 100644--- a/src/hi/apps/location/templates/location/panes/location_view_buttons.html+++ b/src/hi/apps/location/templates/location/panes/location_view_buttons.html@@ -1,24 +1,15 @@{% load icons %}-<div class="d-flex justify-content-start draggable-container">+<div class="d-flex justify-content-start draggable-container hi-button-bar-flex">{% for location_view in location_view_list %}- <div id="{{ location_view.html_id }}-button"+ <div id="{{ location_view.html_id }}-button"class="{% if request.view_parameters.is_editing %}draggable{% endif %} mx-1"{% if request.view_parameters.is_editing %}draggable="true"{% endif %}><a href="{% url 'location_view' location_view_id=location_view.id %}"class="btn {% if location_view == request.view_parameters.active_location_view %}btn-secondary{% else %}btn-primary{% endif %} btn-control"role="button" >- {{ location_view.name }}+ {{ location_view.name|truncatechars:18 }}</a></div>{% endfor %}- {% if request.view_parameters.is_editing %}- <div class="ml-3">- <a href="{% url 'location_edit_location_view_add' %}"- class="btn btn-primary btn-control" role="button"- data-async="modal" >- {% icon "plus" size="sm" css_class="hi-icon-left" %}ADD- </a>- </div>- {% endif %}</div>diff --git a/src/hi/apps/location/tests/test_view_mixins.py b/src/hi/apps/location/tests/test_view_mixins.pynew file mode 100644index 00000000..a0683390--- /dev/null+++ b/src/hi/apps/location/tests/test_view_mixins.py@@ -0,0 +1,126 @@+"""Tests for ``LocationViewMixin.get_entity_svg_update_response``.++Pins the icon-vs-path selector-split contract documented in+``view_mixins.py`` and mirrored in ``entity_state_status.js``.+A regression here would silently re-introduce the parent-<g>-fill+cascade bug that obliterated the light bulb's outline on click-toggle.+"""++import json+from unittest.mock import MagicMock, patch++from hi.apps.location.view_mixins import LocationViewMixin+from hi.testing.base_test_case import BaseTestCase+++class _MixinHost( LocationViewMixin ):+ """Concrete host for the mixin so tests can instantiate it."""+ pass+++class TestGetEntitySvgUpdateResponse( BaseTestCase ):++ def _make_status_display_data( self, state_id: int, attribute_dict: dict ):+ """A minimal stand-in for ``EntityStateDisplayData``: needs only+ ``.entity_state.id`` and ``.attribute_dict`` for the method+ under test."""+ display_data = MagicMock()+ display_data.entity_state.id = state_id+ display_data.attribute_dict = attribute_dict+ return display_data++ def _invoke_and_parse(self, status_display_data_list):+ """Run the mixin method with a patched StatusDisplayManager and+ a patched ``EntityStateDisplayData`` (returns the prepared+ stand-ins). Returns the parsed JSON of the antinode response's+ ``setAttributes`` field."""+ host = _MixinHost()++ # The mixin walks ``entity_status_data.entity_state_status_data_list``+ # and wraps each entry in ``EntityStateDisplayData``. Patch+ # both surfaces: the manager call returns a synthetic+ # container, and ``EntityStateDisplayData(...)`` returns the+ # prepared stand-ins in order.+ container = MagicMock()+ container.entity_state_status_data_list = [+ MagicMock() for _ in status_display_data_list+ ]++ with patch(+ 'hi.apps.location.view_mixins.StatusDisplayManager'+ ) as mock_manager_cls, patch(+ 'hi.apps.location.view_mixins.EntityStateDisplayData',+ side_effect=status_display_data_list,+ ):+ mock_manager_cls.return_value.get_entity_status_data.return_value = container+ response = host.get_entity_svg_update_response(entity=MagicMock())++ payload = json.loads(response.content)+ return payload.get('setAttributes', {})++ def test_emits_both_selectors_with_correct_carve_out(self):+ """For a state whose ``attribute_dict`` carries the full+ SvgStatusStyle payload, the response must contain TWO+ selectors per state-id: the ``[data-status]`` selector with+ ONLY ``status``, and the ``[data-svg-style]`` selector with+ the full dict."""+ full = {+ 'status': 'on',+ 'stroke': 'yellow',+ 'stroke-width': 2.0,+ 'fill': 'yellow',+ 'fill-opacity': 0.5,+ }+ set_attrs = self._invoke_and_parse([+ self._make_status_display_data(state_id=42, attribute_dict=full),+ ])++ icon_selector = '[data-state-id="42"][data-status]'+ path_selector = '[data-state-id="42"][data-svg-style]'++ self.assertIn(icon_selector, set_attrs)+ self.assertIn(path_selector, set_attrs)+ # Icon gets ``status`` ONLY: nothing else may cascade into+ # children of the <g> wrapper.+ self.assertEqual(set_attrs[icon_selector], {'status': 'on'})+ # Path gets the full presentation attribute set.+ self.assertEqual(set_attrs[path_selector], full)++ def test_empty_attribute_dict_emits_no_entry(self):+ """A state with an empty ``attribute_dict`` (e.g., the+ ``svg_status_style`` was None / unrecognized) must not+ contribute either selector to the response."""+ set_attrs = self._invoke_and_parse([+ self._make_status_display_data(state_id=99, attribute_dict={}),+ ])++ self.assertNotIn('[data-state-id="99"][data-status]', set_attrs)+ self.assertNotIn('[data-state-id="99"][data-svg-style]', set_attrs)++ def test_attribute_dict_without_status_still_emits_path_selector(self):+ """An attribute dict that has style attrs but no ``status``+ key must still produce the ``[data-svg-style]`` selector for+ path elements while skipping the ``[data-status]`` one."""+ style_only = { 'stroke': 'red', 'stroke-width': 3.0 }+ set_attrs = self._invoke_and_parse([+ self._make_status_display_data(state_id=7, attribute_dict=style_only),+ ])++ self.assertNotIn('[data-state-id="7"][data-status]', set_attrs)+ self.assertIn('[data-state-id="7"][data-svg-style]', set_attrs)+ self.assertEqual(set_attrs['[data-state-id="7"][data-svg-style]'], style_only)++ def test_multiple_states_each_produce_their_own_selector_pair(self):+ """Multiple states on one entity each contribute an independent+ selector pair keyed by their respective state ids."""+ a = { 'status': 'on', 'fill': 'yellow' }+ b = { 'status': 'off', 'fill': 'grey' }+ set_attrs = self._invoke_and_parse([+ self._make_status_display_data(state_id=1, attribute_dict=a),+ self._make_status_display_data(state_id=2, attribute_dict=b),+ ])++ self.assertEqual(set_attrs['[data-state-id="1"][data-status]'], {'status': 'on'})+ self.assertEqual(set_attrs['[data-state-id="1"][data-svg-style]'], a)+ self.assertEqual(set_attrs['[data-state-id="2"][data-status]'], {'status': 'off'})+ self.assertEqual(set_attrs['[data-state-id="2"][data-svg-style]'], b)diff --git a/src/hi/apps/location/tests/test_views.py b/src/hi/apps/location/tests/test_views.pyindex e1d5b0d2..2cc8132d 100644--- a/src/hi/apps/location/tests/test_views.py+++ b/src/hi/apps/location/tests/test_views.py@@ -674,6 +674,81 @@ class TestLocationItemStatusView(SyncViewTestCase):data = response.json()self.assertIn('setAttributes', data)+ def test_long_press_bypasses_one_click_in_automation_view(self):+ """Long-press gesture (``?long_press=1``) in an AUTOMATION view+ must bypass the one-click control branch and redirect to the+ entity status modal — the gesture's whole purpose is reaching+ status when a tap would otherwise toggle the device."""+ from hi.enums import ItemType+ session = self.client.session+ session['view_type'] = str(ViewType.LOCATION_VIEW)+ session['location_view_id'] = self.automation_view.id+ session.save()++ html_id = ItemType.ENTITY.html_id(self.entity.id)+ url = reverse('location_item_status', kwargs={'html_id': html_id})++ response = self.client.get(url + '?long_press=1')++ self.assertEqual(response.status_code, 302)+ expected_url = reverse('entity_status', kwargs={'entity_id': self.entity.id})+ self.assertEqual(response.url, expected_url)++ def test_long_press_no_op_in_non_automation_view(self):+ """In a non-AUTOMATION view, a tap already routes to status, so+ ``?long_press=1`` should be a harmless no-op (same response)."""+ from hi.enums import ItemType+ session = self.client.session+ session['view_type'] = str(ViewType.LOCATION_VIEW)+ session['location_view_id'] = self.default_view.id+ session.save()++ html_id = ItemType.ENTITY.html_id(self.entity.id)+ url = reverse('location_item_status', kwargs={'html_id': html_id})++ response = self.client.get(url + '?long_press=1')++ self.assertEqual(response.status_code, 302)+ expected_url = reverse('entity_status', kwargs={'entity_id': self.entity.id})+ self.assertEqual(response.url, expected_url)++ @patch('hi.apps.control.one_click_control_service.ControllerManager')+ def test_long_press_param_truthy_variants_all_bypass(self, mock_controller_manager):+ """The view consumes ``long_press`` via ``str_to_bool``, so any+ truthy variant (``true``, ``yes``, ``on``) bypasses one-click;+ falsy variants (``false``, missing) keep the one-click path."""+ from hi.enums import ItemType+ from hi.apps.control.transient_models import ControllerOutcome+ mock_manager = Mock()+ mock_controller_manager.return_value = mock_manager+ mock_manager.do_control.return_value = ControllerOutcome(+ controller=self.controller,+ new_value='ON',+ error_list=[]+ )++ session = self.client.session+ session['view_type'] = str(ViewType.LOCATION_VIEW)+ session['location_view_id'] = self.automation_view.id+ session.save()++ html_id = ItemType.ENTITY.html_id(self.entity.id)+ url = reverse('location_item_status', kwargs={'html_id': html_id})++ for truthy in ['1', 'true', 'yes', 'on']:+ response = self.client.get(url + f'?long_press={truthy}')+ self.assertEqual(+ response.status_code, 302,+ f'long_press={truthy!r} should bypass one-click',+ )++ # ``false`` is the canonical falsy variant; verify one-click path runs.+ response = self.client.get(url + '?long_press=false')+ self.assertEqual(+ response.status_code, 200,+ 'long_press=false should NOT bypass one-click',+ )+@patch('hi.apps.location.views.OneClickControlService')def test_automation_view_handles_unsupported_exception(self, mock_service_class):"""Test that OneClickNotSupported falls back to status modal."""diff --git a/src/hi/apps/location/view_mixins.py b/src/hi/apps/location/view_mixins.pyindex d90e5e2c..7c19704c 100644--- a/src/hi/apps/location/view_mixins.py+++ b/src/hi/apps/location/view_mixins.py@@ -54,8 +54,8 @@ class LocationViewMixin:)return antinode.redirect_response( redirect_url )- def get_entity_svg_update_reponse( self, entity : Entity ) -> HttpResponse:- """ For updating a single entity in the location view vis antinode reponse """+ def get_entity_svg_update_response( self, entity : Entity ) -> HttpResponse:+ """ For updating a single entity in the location view via antinode response """entity_status_data = StatusDisplayManager().get_entity_status_data(entity = entity,@@ -65,10 +65,30 @@ class LocationViewMixin:status_display_data = EntityStateDisplayData(entity_state_status_data = entity_state_status_data,)- selector = f'[data-state-id="{status_display_data.entity_state.id}"]'- set_attributes_map.update({- selector: status_display_data.attribute_dict- })+ attribute_dict = status_display_data.attribute_dict+ if not attribute_dict:+ continue+ state_id = status_display_data.entity_state.id+ # Mirror the polling-refresh dispatch contract documented+ # in ``entity_state_status.js``: elements opt into the+ # ``data-status`` hint (icon wrappers; see+ # ``location/panes/svg_icon_item.html``) for status-only+ # updates, or ``data-svg-style`` (path elements; see+ # ``location/panes/svg_path_item_*.html``) for the full+ # presentation attribute set. Icon wrappers get only the+ # ``status`` attribute so the parent <g>'s ``fill`` /+ # ``fill-opacity`` / ``stroke`` don't cascade into child+ # paths that depend on browser-default ``fill: black`` or+ # on full opacity. Path elements live on the element+ # being styled, so the full attribute set is the right+ # payload there.+ icon_selector = f'[data-state-id="{state_id}"][data-status]'+ path_selector = f'[data-state-id="{state_id}"][data-svg-style]'+ if 'status' in attribute_dict:+ set_attributes_map[ icon_selector ] = {+ 'status': attribute_dict[ 'status' ],+ }+ set_attributes_map[ path_selector ] = attribute_dictcontinuereturn antinode.response(set_attributes_map = set_attributes_map,diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.pyindex 133cef1b..cd1eae32 100644--- a/src/hi/apps/location/views.py+++ b/src/hi/apps/location/views.py@@ -6,7 +6,7 @@ from django.http import HttpRequest, HttpResponse, HttpResponseRedirectfrom django.shortcuts import reversefrom django.views.generic import View-from hi.apps.common.utils import is_ajax+from hi.apps.common.utils import is_ajax, str_to_boolimport hi.apps.common.antinode as antinodefrom hi.apps.attribute.view_mixins import AttributeEditViewMixin@@ -124,11 +124,21 @@ class LocationItemStatusView( View, LocationViewMixin, EntityViewMixin ):raise BadRequest( f'Unknown item type "{item_type}".' )def _handle_entity(self, request : HttpRequest, entity : Entity ):-+location_view_id = request.view_parameters.location_view_idlocation_view = LocationView.objects.get( id = location_view_id )- if location_view.location_view_type not in [ LocationViewType.AUTOMATION ]:+ # ``long_press`` signals that the gesture-based escape hatch+ # was used; in AUTOMATION views a tap fires one-click control,+ # so the long-press is the only way operators have to reach+ # status / history / edit for a controllable entity in that+ # view. The JS doesn't dictate which view to surface -- it+ # just reports the gesture -- and the server picks the route.+ # ``str_to_bool`` tolerates ``1``/``true``/``yes``/``on``/etc.+ # and returns False for a missing param.+ long_press = str_to_bool( request.GET.get( 'long_press' ) )+ if ( long_press+ or location_view.location_view_type not in [ LocationViewType.AUTOMATION ] ):return self._entity_status_response(request = request,entity = entity,@@ -149,7 +159,7 @@ class LocationItemStatusView( View, LocationViewMixin, EntityViewMixin ):entity_state = controller_outcome.controller.entity_state,override_value = override_sensor_value,)- return self.get_entity_svg_update_reponse( entity = entity )+ return self.get_entity_svg_update_response( entity = entity )except OneClickNotSupported:return self._entity_status_response(diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex 25a28ca1..91976217 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -1,7 +1,6 @@import jsonfrom typing import Dict-from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevelfrom hi.apps.control.enums import ControllerTypefrom hi.apps.control.models import Controller@@ -32,9 +31,22 @@ class HiModelHelper:EntityStateType.MULTIVALUED,}+ # Default alarm lifetime for persistent-state alarms (connectivity,+ # battery, smoke, CO, gas, etc.). After the AlertQueue+ # dedup-anchor refactor, this value governs the post-acknowledgement+ # nag window -- after the operator dismisses, the suppression lasts+ # this long before another bad-state alarm with the same signature+ # can re-surface. Twenty-four hours balances same-day deferral+ # against next-day reminder for the operator who didn't address the+ # underlying condition. Tracked in #378 -- the longer-term answer+ # is a producer-side ``clear_signature`` API that drops acked+ # alerts on state-recovery, after which this constant can give way+ # to per-source decisions.+ NAG_INTERVAL_SECS = 24 * 60 * 60+DEFAULT_CONNECTIVITY_EVENT_WINDOW_SECS = 180DEFAULT_CONNECTIVITY_DEDUPE_WINDOW_SECS = 300- DEFAULT_CONNECTIVITY_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+ DEFAULT_CONNECTIVITY_ALARM_LIFETIME_SECS = NAG_INTERVAL_SECSDEFAULT_OPEN_CLOSE_EVENT_WINDOW_SECS = 180DEFAULT_OPEN_CLOSE_DEDUPE_WINDOW_SECS = 300@@ -50,7 +62,7 @@ class HiModelHelper:DEFAULT_BATTERY_EVENT_WINDOW_SECS = 180DEFAULT_BATTERY_DEDUPE_WINDOW_SECS = 300- DEFAULT_BATTERY_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+ DEFAULT_BATTERY_ALARM_LIFETIME_SECS = NAG_INTERVAL_SECS# Threshold-based low-battery alarm for continuous BATTERY_LEVEL# percentage sensors. Distinct from the discrete HIGH_LOW battery@@ -60,23 +72,23 @@ class HiModelHelper:DEFAULT_BATTERY_LEVEL_THRESHOLD_PERCENT = 20DEFAULT_BATTERY_LEVEL_EVENT_WINDOW_SECS = 180DEFAULT_BATTERY_LEVEL_DEDUPE_WINDOW_SECS = 86400- DEFAULT_BATTERY_LEVEL_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+ DEFAULT_BATTERY_LEVEL_ALARM_LIFETIME_SECS = NAG_INTERVAL_SECSDEFAULT_SMOKE_EVENT_WINDOW_SECS = 180DEFAULT_SMOKE_DEDUPE_WINDOW_SECS = 300- DEFAULT_SMOKE_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+ DEFAULT_SMOKE_ALARM_LIFETIME_SECS = NAG_INTERVAL_SECSDEFAULT_MOISTURE_EVENT_WINDOW_SECS = 180DEFAULT_MOISTURE_DEDUPE_WINDOW_SECS = 300- DEFAULT_MOISTURE_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+ DEFAULT_MOISTURE_ALARM_LIFETIME_SECS = NAG_INTERVAL_SECSDEFAULT_CO_EVENT_WINDOW_SECS = 180DEFAULT_CO_DEDUPE_WINDOW_SECS = 300- DEFAULT_CO_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+ DEFAULT_CO_ALARM_LIFETIME_SECS = NAG_INTERVAL_SECSDEFAULT_GAS_EVENT_WINDOW_SECS = 180DEFAULT_GAS_DEDUPE_WINDOW_SECS = 300- DEFAULT_GAS_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+ DEFAULT_GAS_ALARM_LIFETIME_SECS = NAG_INTERVAL_SECS@classmethoddef create_blob_sensor( cls,diff --git a/src/hi/apps/monitor/monitor_manager.py b/src/hi/apps/monitor/monitor_manager.pyindex afaeb07b..9e7ba00c 100644--- a/src/hi/apps/monitor/monitor_manager.py+++ b/src/hi/apps/monitor/monitor_manager.py@@ -62,7 +62,7 @@ class AppMonitorManager( Singleton ):# Sort monitors by query interval (ascending) for priority ordering# This ensures critical monitors with shorter intervals start first- sorted_monitors = sorted(self._get_all_monitors(), key=lambda m: m._query_interval_secs)+ sorted_monitors = sorted(self._get_all_monitors(), key=lambda m: m.get_polling_interval_secs())# Start monitors with staggered delays (no lock needed)for monitor in sorted_monitors:@@ -72,7 +72,7 @@ class AppMonitorManager( Singleton ):continue# Staggered startup: sleep before starting each monitor- logger.debug(f'Delaying startup of {monitor.id} by {self.START_DELAY_INTERVAL_SECS}s (interval: {monitor._query_interval_secs}s)')+ logger.debug(f'Delaying startup of {monitor.id} by {self.START_DELAY_INTERVAL_SECS}s (interval: {monitor.get_polling_interval_secs()}s)')await asyncio.sleep(self.START_DELAY_INTERVAL_SECS)logger.debug(f'Starting app monitor: {monitor.id}')diff --git a/src/hi/apps/monitor/periodic_monitor.py b/src/hi/apps/monitor/periodic_monitor.pyindex 826bd554..40ac81b8 100644--- a/src/hi/apps/monitor/periodic_monitor.py+++ b/src/hi/apps/monitor/periodic_monitor.py@@ -10,9 +10,10 @@ class PeriodicMonitor( HealthStatusProvider ):and periodically updated from some external source."""- def __init__( self, id: str, interval_secs: int ) -> None:+ SLEEP_CHUNK_SECS = 10++ def __init__( self, id: str ) -> None:self._id = id- self._query_interval_secs = interval_secsself._query_counter = 0self._is_running = Falseself._logger = logging.getLogger(__name__)@@ -28,10 +29,33 @@ class PeriodicMonitor( HealthStatusProvider ):def is_running(self):return self._is_running+ def get_polling_interval_secs(self) -> int:+ """Return the current polling interval in seconds. Subclasses+ must override. The loop calls this each tick before sleeping+ so a value change takes effect on the very next iteration.++ Implementations should be cheap (typically a single attribute+ lookup) -- expensive source-of-truth reads belong in the+ subclass's own cache-and-subscribe code, not here. Static-+ interval monitors return a class constant; dynamic monitors+ return a cache that they keep current via their own listener.+ """+ raise NotImplementedError(+ 'Subclasses must implement get_polling_interval_secs()'+ )++ def get_expected_heartbeat_interval_secs(self):+ """A monitor's expected heartbeat is its polling cadence.+ Wires the ``HealthStatusProvider`` hook to the live polling+ value so the expected-interval row in the UI and the dynamic+ staleness thresholds track configuration changes without any+ per-subclass involvement."""+ return self.get_polling_interval_secs()+async def start(self) -> None:self._is_running = Trueself._logger.debug( f"{self.__class__.__name__} async task starting"- f" (interval: {self._query_interval_secs}s)")+ f" (interval: {self.get_polling_interval_secs()}s)")try:await self.initialize()@@ -44,16 +68,14 @@ class PeriodicMonitor( HealthStatusProvider ):try:await self.run_query()self.record_heartbeat()-+except Exception as e:self._logger.exception(f"Query execution failed in {self.__class__.__name__}: {e}")self.record_error(f"Query execution failed: {str(e)}")# Continue running despite individual query failures- # Log sleep phase for debugging hanging issues- self._logger.debug(f"{self.__class__.__name__} sleeping"- f" for {self._query_interval_secs}s")- await asyncio.sleep(self._query_interval_secs)+ self._logger.debug(f"{self.__class__.__name__} entering sleep")+ await self._sleep_until_next_poll()self._logger.debug( f"{self.__class__.__name__} woke up,"f" checking if still running: {self._is_running}")@@ -77,6 +99,33 @@ class PeriodicMonitor( HealthStatusProvider ):self._logger.info(f"Stopping {self.__class__.__name__}...")return+ async def _sleep_until_next_poll(self) -> None:+ # Sleep in chunks and re-check the configured interval each+ # chunk so a mid-sleep reduction (e.g. 300s -> 5s) takes+ # effect within one chunk rather than waiting out the original+ # interval. An increased interval finishes the current cycle+ # and governs the next one.+ #+ # Operator-visible side effect after a dramatic shrink: the+ # ``HealthStatusProvider``'s expected-heartbeat threshold is+ # now derived live from ``get_polling_interval_secs()``, so+ # immediately after dropping 300s -> 5s the most recent+ # heartbeat (taken under the old cadence, perhaps 200s ago)+ # appears stale against the new threshold and the monitor+ # may briefly read "Dead." The next successful poll+ # (within the new shorter interval) clears it. Not a fault+ # condition; just transient visibility.+ interval_secs = self.get_polling_interval_secs()+ remaining = interval_secs+ while self._is_running:+ if (( remaining <= 0 )+ or ( self.get_polling_interval_secs() < interval_secs )):+ return+ chunk = min( remaining, self.SLEEP_CHUNK_SECS )+ await asyncio.sleep( chunk )+ remaining -= chunk+ return+async def initialize(self) -> None:"""Optional initialization logic to be implemented by subclasses.@@ -96,11 +145,14 @@ class PeriodicMonitor( HealthStatusProvider ):self._logger.debug(f"Query {self._query_counter} completed successfully"f" in {query_duration:.2f}s")- # Log warning if query is taking too long relative to interval- if query_duration > (self._query_interval_secs * 0.5):+ # Log warning if query is taking too long relative to+ # interval. Captured into a local so the threshold check+ # and the message both refer to the same reading.+ interval_secs = self.get_polling_interval_secs()+ if query_duration > (interval_secs * 0.5):self._logger.warning(f"Query {self._query_counter} took {query_duration:.2f}s, "- f"which is over 50% of the {self._query_interval_secs}s interval"+ f"which is over 50% of the {interval_secs}s interval")except Exception as e:diff --git a/src/hi/apps/monitor/tests/test_monitor_manager.py b/src/hi/apps/monitor/tests/test_monitor_manager.pyindex 271cecbc..65b618eb 100644--- a/src/hi/apps/monitor/tests/test_monitor_manager.py+++ b/src/hi/apps/monitor/tests/test_monitor_manager.py@@ -15,8 +15,11 @@ logging.disable(logging.CRITICAL)class TestMonitor1(PeriodicMonitor):"""Test monitor for discovery."""def __init__(self):- super().__init__(id='test-monitor-1', interval_secs=60)-+ super().__init__(id='test-monitor-1')++ def get_polling_interval_secs(self) -> int:+ return 60+async def do_work(self):pass@@ -24,7 +27,10 @@ class TestMonitor1(PeriodicMonitor):class TestMonitor2(PeriodicMonitor):"""Another test monitor for discovery."""def __init__(self):- super().__init__(id='test-monitor-2', interval_secs=60)+ super().__init__(id='test-monitor-2')++ def get_polling_interval_secs(self) -> int:+ return 60async def do_work(self):pass@@ -220,7 +226,7 @@ class TestAppMonitorManager(AsyncTaskFastTestCase):mock_monitor_instance.id = 'test-monitor'mock_monitor_instance.is_running = Falsemock_monitor_instance.start = Mock()- mock_monitor_instance._query_interval_secs = 10+ mock_monitor_instance.get_polling_interval_secs.return_value = 10mock_monitor_class = Mock(return_value=mock_monitor_instance)@@ -272,7 +278,7 @@ class TestAppMonitorManager(AsyncTaskFastTestCase):mock_monitor_instance.id = 'running-monitor'mock_monitor_instance.is_running = True # Already runningmock_monitor_instance.start = Mock()- mock_monitor_instance._query_interval_secs = 10+ mock_monitor_instance.get_polling_interval_secs.return_value = 10mock_monitor_class = Mock(return_value=mock_monitor_instance)diff --git a/src/hi/apps/monitor/tests/test_periodic_monitor.py b/src/hi/apps/monitor/tests/test_periodic_monitor.pyindex 3fbd835f..e5f6e9a3 100644--- a/src/hi/apps/monitor/tests/test_periodic_monitor.py+++ b/src/hi/apps/monitor/tests/test_periodic_monitor.py@@ -10,31 +10,38 @@ logging.disable(logging.CRITICAL)class ConcreteTestMonitor(PeriodicMonitor):"""Concrete implementation of PeriodicMonitor for testing."""-+def __init__(self):- super().__init__(id='test-monitor', interval_secs=1)+ super().__init__(id='test-monitor')+ # Mutable so tests that need fast cycles can shrink the+ # interval without poking superclass internals; the framework+ # calls ``get_polling_interval_secs`` each tick.+ self.polling_interval_secs = 1self.do_work_called = 0self.initialize_called = Falseself.cleanup_called = Falseself.do_work_error = None # Set to raise an error in do_work-++ def get_polling_interval_secs(self) -> int:+ return self.polling_interval_secs+async def initialize(self):self.initialize_called = Trueawait super().initialize()-+@classmethoddef get_provider_info(cls) -> ProviderInfo:return ProviderInfo(provider_id = 'test_monitor',provider_name = 'Test Monitor',- description = '',+ description = '',)async def do_work(self):self.do_work_called += 1if self.do_work_error:raise self.do_work_error-+async def cleanup(self):self.cleanup_called = Trueawait super().cleanup()@@ -55,14 +62,17 @@ class TestPeriodicMonitor(AsyncTaskFastTestCase):class IncompleteMonitor(PeriodicMonitor):def __init__(self):- super().__init__(id='incomplete', interval_secs=1)-+ super().__init__(id='incomplete')++ def get_polling_interval_secs(self) -> int:+ return 1+@classmethoddef get_provider_info(cls) -> ProviderInfo:return ProviderInfo(provider_id = 'test_monitor',provider_name = 'Test Monitor',- description = '',+ description = '',)monitor = IncompleteMonitor()@@ -76,7 +86,7 @@ class TestPeriodicMonitor(AsyncTaskFastTestCase):def test_monitor_initialization(self):"""Test monitor initializes with correct properties."""self.assertEqual(self.monitor.id, 'test-monitor')- self.assertEqual(self.monitor._query_interval_secs, 1)+ self.assertEqual(self.monitor.get_polling_interval_secs(), 1)self.assertEqual(self.monitor._query_counter, 0)self.assertFalse(self.monitor.is_running)@@ -235,7 +245,7 @@ class TestPeriodicMonitor(AsyncTaskFastTestCase):async def test_logic():# Use a very short interval for testingfast_monitor = ConcreteTestMonitor()- fast_monitor._query_interval_secs = 0.05 # 50ms+ fast_monitor.polling_interval_secs = 0.05 # 50ms# Start the monitortask = asyncio.create_task(fast_monitor.start())@@ -265,7 +275,7 @@ class TestPeriodicMonitor(AsyncTaskFastTestCase):async def test_logic():fast_monitor = ConcreteTestMonitor()- fast_monitor._query_interval_secs = 0.05 # 50ms+ fast_monitor.polling_interval_secs = 0.05 # 50ms# Set error for first callfast_monitor.do_work_error = ValueError("Test error")diff --git a/src/hi/apps/notify/monitors.py b/src/hi/apps/notify/monitors.pyindex 520cc8f3..df192d7d 100644--- a/src/hi/apps/notify/monitors.py+++ b/src/hi/apps/notify/monitors.py@@ -15,19 +15,18 @@ class NotificationMonitor( PeriodicMonitor, NotificationMixin ):NOTIFICATION_POLLING_INTERVAL_SECS = 10def __init__( self ):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.NOTIFICATION_POLLING_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )return+ def get_polling_interval_secs(self) -> int:+ return self.NOTIFICATION_POLLING_INTERVAL_SECS+@classmethoddef get_provider_info(cls) -> ProviderInfo:return ProviderInfo(provider_id = cls.MONITOR_ID,provider_name = 'Notifications Monitor',description = 'Notification processing and delivery',- expected_heartbeat_interval_secs = cls.NOTIFICATION_POLLING_INTERVAL_SECS,)def alarm_ceiling(self):diff --git a/src/hi/apps/notify/settings.py b/src/hi/apps/notify/settings.pyindex 75e0fd23..bf591450 100644--- a/src/hi/apps/notify/settings.py+++ b/src/hi/apps/notify/settings.py@@ -10,7 +10,7 @@ class NotifySetting( SettingEnum ):label = 'Enable Notifications',description = 'Whether to send notifications (e.g., emails).',value_type = AttributeValueType.BOOLEAN,- value_range_str = '',+ value_range = None,is_editable = True,is_required = True,initial_value = True,@@ -19,7 +19,7 @@ class NotifySetting( SettingEnum ):label = 'Notification Email Addresses',description = 'Email addresses to send notifications to (if enabled).',value_type = AttributeValueType.TEXT,- value_range_str = '',+ value_range = None,is_editable = True,is_required = False,initial_value = '',diff --git a/src/hi/apps/security/monitors.py b/src/hi/apps/security/monitors.pyindex b44a91f9..c73fe9bf 100644--- a/src/hi/apps/security/monitors.py+++ b/src/hi/apps/security/monitors.py@@ -20,20 +20,19 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):SECURITY_POLLING_INTERVAL_SECS = 5def __init__( self ):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.SECURITY_POLLING_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )self._last_security_state_check_datetime = datetimeproxy.now()return+ def get_polling_interval_secs(self) -> int:+ return self.SECURITY_POLLING_INTERVAL_SECS+@classmethoddef get_provider_info(cls) -> ProviderInfo:return ProviderInfo(provider_id = cls.MONITOR_ID,provider_name = 'Security Monitor',description = 'Security state monitoring',- expected_heartbeat_interval_secs = cls.SECURITY_POLLING_INTERVAL_SECS,)def alarm_ceiling(self):@@ -73,10 +72,13 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):logger.debug( f'Security state "{current_state}". Auto-change not allowed.' )return f"Auto-change blocked ({current_state.label} mode)"+ # A missing value is a legitimate state (unconfigured, blanked+ # by the user, fresh install before initial population); skip+ # the transition check rather than crashing the poll cycle.day_start_time_of_day = settings_manager.get_setting_value(SecuritySetting.SECURITY_DAY_START,)- if datetimeproxy.is_time_of_day_in_interval(+ if day_start_time_of_day and datetimeproxy.is_time_of_day_in_interval(time_of_day_str = day_start_time_of_day,tz_name = tz_name,start_datetime = self._last_security_state_check_datetime,@@ -90,7 +92,7 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):night_start_time_of_day = settings_manager.get_setting_value(SecuritySetting.SECURITY_NIGHT_START,)- if datetimeproxy.is_time_of_day_in_interval(+ if night_start_time_of_day and datetimeproxy.is_time_of_day_in_interval(time_of_day_str = night_start_time_of_day,tz_name = tz_name,start_datetime = self._last_security_state_check_datetime,diff --git a/src/hi/apps/security/settings.py b/src/hi/apps/security/settings.pyindex 119e98f7..6d644c2f 100644--- a/src/hi/apps/security/settings.py+++ b/src/hi/apps/security/settings.py@@ -11,37 +11,37 @@ class SecuritySetting( SettingEnum ):label = 'Security Day Start',description = 'Determines what time of day to switch to the "Day" security posture.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.TIME_OF_DAY_CHOICES_ID,+ value_range = PredefinedValueRanges.TIME_OF_DAY_CHOICES_ID,is_editable = True,is_required = True,initial_value = '08:00',)-+SECURITY_NIGHT_START = SettingDefinition(label = 'Security Night Start',description = 'Determines what time of day to switch to the "Night" security posture.',value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.TIME_OF_DAY_CHOICES_ID,+ value_range = PredefinedValueRanges.TIME_OF_DAY_CHOICES_ID,is_editable = True,is_required = True,initial_value = '23:00',)-+SECURITY_AWAY_DELAY_MINS = SettingDefinition(label = 'Away Delay Time (mins)',description = 'Amount of time to ignore alarms when switching to "Away" security posture.',value_type = AttributeValueType.INTEGER,- value_range_str = '',+ value_range = None,is_editable = True,is_required = True,initial_value = '5',)-+SECURITY_SNOOZE_DELAY_MINS = SettingDefinition(label = 'Snooze Delay Time (mins)',description = 'Amount of time to ignore alarms when "Snooze" option is chosen.',value_type = AttributeValueType.INTEGER,- value_range_str = '',+ value_range = None,is_editable = True,is_required = True,initial_value = '5',diff --git a/src/hi/apps/security/tests/test_security_monitor.py b/src/hi/apps/security/tests/test_security_monitor.pyindex 0962fda8..6619ab57 100644--- a/src/hi/apps/security/tests/test_security_monitor.py+++ b/src/hi/apps/security/tests/test_security_monitor.py@@ -27,7 +27,7 @@ class TestSecurityMonitor(AsyncTaskFastTestCase):# Should be properly configured as periodic monitorself.assertEqual(monitor.id, monitor.MONITOR_ID)- self.assertEqual(monitor._query_interval_secs, SecurityMonitor.SECURITY_POLLING_INTERVAL_SECS)+ self.assertEqual(monitor.get_polling_interval_secs(), SecurityMonitor.SECURITY_POLLING_INTERVAL_SECS)self.assertIsNotNone(monitor._last_security_state_check_datetime)def test_security_monitor_interval_timing(self):@@ -35,7 +35,7 @@ class TestSecurityMonitor(AsyncTaskFastTestCase):monitor = SecurityMonitor()# Should use configured polling interval- self.assertEqual(monitor._query_interval_secs, 5) # SECURITY_POLLING_INTERVAL_SECS+ self.assertEqual(monitor.get_polling_interval_secs(), 5) # SECURITY_POLLING_INTERVAL_SECSasync def test_do_work_calls_check_security_state(self):"""Test do_work method calls security state checking."""diff --git a/src/hi/apps/system/health_status_provider.py b/src/hi/apps/system/health_status_provider.pyindex 519f0aff..c7236812 100644--- a/src/hi/apps/system/health_status_provider.py+++ b/src/hi/apps/system/health_status_provider.py@@ -34,9 +34,13 @@ class HealthStatusProvider(ABC):status = HealthStatusType.UNKNOWN,last_update = datetimeproxy.now(),last_message = 'Initialization',- expected_heartbeat_interval_secs = provider_info.expected_heartbeat_interval_secs,+ # ``expected_heartbeat_interval_secs`` deliberately left+ # at the dataclass default. The ``health_status`` property+ # refreshes it from ``get_expected_heartbeat_interval_secs``+ # on every read, so seeding here would be discarded+ # immediately on the first access.)-+def _ensure_health_status_provider_setup(self):if hasattr( self, '_health_status' ):return@@ -50,10 +54,31 @@ class HealthStatusProvider(ABC):"""Get the API service info for this class. Must be implemented by subclasses."""pass+ def get_expected_heartbeat_interval_secs(self) -> Optional[int]:+ """Return the current expected heartbeat interval, in seconds.+ ``None`` means this provider has no expected cadence -- its+ health is not driven by periodic ticks (aggregators, on-demand+ probes, etc.).++ The framework refreshes ``HealthStatus.expected_heartbeat_interval_secs``+ from this method on every ``health_status`` read, so a value+ change takes effect on the next read without any explicit+ mutation. Periodic providers override this to return their+ live polling cadence; everything else inherits the ``None``+ default and the expected-interval row is suppressed in the UI."""+ return None+@propertydef health_status(self) -> HealthStatus:self._ensure_health_status_provider_setup()with self._health_lock:+ # Refresh the dynamic field on every read so a change in+ # the source-of-truth (e.g., a config-page edit of a+ # polling interval) is visible immediately, without the+ # provider having to mutate state through a side channel.+ self._health_status.expected_heartbeat_interval_secs = (+ self.get_expected_heartbeat_interval_secs()+ )health_status = copy.deepcopy( self._health_status )return health_statusdiff --git a/src/hi/apps/system/monitors.py b/src/hi/apps/system/monitors.pyindex a407e6cf..c1e8e68e 100644--- a/src/hi/apps/system/monitors.py+++ b/src/hi/apps/system/monitors.py@@ -23,19 +23,18 @@ class SystemMonitor( PeriodicMonitor ):SYSTEM_MAINTENANCE_INTERVAL_SECS = 8 * 60 * 60 # 8 hoursdef __init__(self):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.SYSTEM_MAINTENANCE_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )return+ def get_polling_interval_secs(self) -> int:+ return self.SYSTEM_MAINTENANCE_INTERVAL_SECS+@classmethoddef get_provider_info(cls) -> ProviderInfo:return ProviderInfo(provider_id = cls.MONITOR_ID,provider_name = 'System Monitor',description = 'Automated system maintenance tasks',- expected_heartbeat_interval_secs = cls.SYSTEM_MAINTENANCE_INTERVAL_SECS,)def alarm_ceiling(self):diff --git a/src/hi/apps/system/provider_info.py b/src/hi/apps/system/provider_info.pyindex 9009cfee..1d73aed2 100644--- a/src/hi/apps/system/provider_info.py+++ b/src/hi/apps/system/provider_info.py@@ -14,7 +14,6 @@ class ProviderInfo:provider_id : str # Technical identifier (e.g., 'hass_api', 'zm_api')provider_name : str # Human-friendly display name (e.g., 'Home Assistant API')description : Optional[str] = None # Optional longer description- expected_heartbeat_interval_secs : Optional[int] = None # Expected heartbeat interval for dynamic thresholdsdef __str__(self) -> str:return f"{self.provider_name} ({self.provider_id})"diff --git a/src/hi/apps/system/tests/test_history_cleanup.py b/src/hi/apps/system/tests/test_history_cleanup.pyindex 72cf94d1..c976e9bc 100644--- a/src/hi/apps/system/tests/test_history_cleanup.py+++ b/src/hi/apps/system/tests/test_history_cleanup.py@@ -342,7 +342,7 @@ class SystemIntegrationTests(TransactionTestCase):# Verify monitor has correct configurationself.assertEqual(monitor.id, 'hi.apps.system.monitor')- self.assertEqual(monitor._query_interval_secs, 8 * 60 * 60) # 8 hours+ self.assertEqual(monitor.get_polling_interval_secs(), 8 * 60 * 60) # 8 hours# Test that do_work() runs without errorsdiff --git a/src/hi/apps/system/views.py b/src/hi/apps/system/views.pyindex c7f34a2b..70bf6a4a 100644--- a/src/hi/apps/system/views.py+++ b/src/hi/apps/system/views.py@@ -10,6 +10,7 @@ from hi.apps.config.views import ConfigPageViewfrom hi.apps.monitor.monitor_manager import AppMonitorManagerfrom hi.apps.weather.weather_source_manager import WeatherSourceManager+from hi.integrations.enums import IntegrationCapabilityfrom hi.integrations.integration_manager import IntegrationManagerfrom .asyncio_health_provider import AsyncioHealthStatusProvider@@ -39,6 +40,7 @@ class SystemInfoView( ConfigPageView ):integration_manager = IntegrationManager()configured_integration_data_list = integration_manager.get_integration_data_list(enabled_only = True,+ capabilities = frozenset({ IntegrationCapability.CONNECT }),)provider_by_integration_id = integration_manager.get_health_status_provider_map()integration_health_items = [diff --git a/src/hi/apps/weather/monitors.py b/src/hi/apps/weather/monitors.pyindex 9b08f189..12c95575 100644--- a/src/hi/apps/weather/monitors.py+++ b/src/hi/apps/weather/monitors.py@@ -20,22 +20,35 @@ class WeatherMonitor( PeriodicMonitor, SettingsMixin ):def __init__( self ):self._settings_helper = WeatherSettingsHelper()- super().__init__(- id = self.MONITOR_ID,- # Provisional interval; ``initialize()`` reads the configured- # value via the async settings path and overwrites it. The- # async loop reads self._query_interval_secs each tick so a- # post-init change takes effect before the next sleep.- interval_secs = WeatherSettingsHelper.DEFAULT_POLLING_INTERVAL_SECONDS,+ # Subclass-owned cache of the configured polling interval.+ # Seeded with the default; ``initialize`` reads the saved value+ # via the async-safe path, and a settings change listener+ # refreshes it whenever the operator edits it on the config+ # page. The framework calls ``get_polling_interval_secs`` each+ # tick and reads this attribute.+ self._polling_interval_secs = (+ WeatherSettingsHelper.DEFAULT_POLLING_INTERVAL_SECONDS)+ super().__init__( id = self.MONITOR_ID )self._weather_data_source_instance_list = list()self._started_datetime = datetimeproxy.now()return+ def get_polling_interval_secs(self) -> int:+ return self._polling_interval_secs+async def initialize(self) -> None:- self._query_interval_secs = (+ # Pick up the operator's saved value before the loop begins.+ # The async helper handles the singleton's first-time DB init+ # safely; subsequent sync access (from the listener below) is+ # safe because that init has already happened here.+ self._polling_interval_secs = (await self._settings_helper.get_default_polling_interval_secs_async())+ settings_manager = await self._settings_helper.settings_manager_async()+ if settings_manager is not None:+ settings_manager.register_change_listener( self._on_settings_changed )+discovered_sources = WeatherSourceDiscovery.discover_weather_data_source_instances()self._weather_data_source_instance_list = discovered_sources@@ -54,16 +67,27 @@ class WeatherMonitor( PeriodicMonitor, SettingsMixin ):weather_data_source.record_disabled()continuereturn-++ def _on_settings_changed(self) -> None:+ """Settings change listener. Sync because+ ``SettingsManager._notify_change_listeners`` calls callbacks+ synchronously; safe to do sync settings access because the+ singleton is already initialized by ``initialize`` above."""+ new_interval = self._settings_helper.get_default_polling_interval_secs()+ if new_interval != self._polling_interval_secs:+ logger.debug(+ f'WeatherMonitor polling interval changed: '+ f'{self._polling_interval_secs}s -> {new_interval}s'+ )+ self._polling_interval_secs = new_interval+ return+@classmethoddef get_provider_info(cls) -> ProviderInfo:return ProviderInfo(provider_id = cls.MONITOR_ID,provider_name = 'Weather Monitor',description = 'Weather data collection and monitoring',- expected_heartbeat_interval_secs = (- WeatherSettingsHelper.DEFAULT_POLLING_INTERVAL_SECONDS- ),)async def do_work(self):@@ -84,7 +108,7 @@ class WeatherMonitor( PeriodicMonitor, SettingsMixin ):returndisabled_count = 0-+task_list = list()for weather_data_source in self._weather_data_source_instance_list:is_enabled = await self._settings_helper.is_weather_source_enabled_async(@@ -110,4 +134,3 @@ class WeatherMonitor( PeriodicMonitor, SettingsMixin ):self.record_warning( message )weather_source_manager.record_warning( message )return-diff --git a/src/hi/apps/weather/settings.py b/src/hi/apps/weather/settings.pyindex 1218dd90..2a59afff 100644--- a/src/hi/apps/weather/settings.py+++ b/src/hi/apps/weather/settings.py@@ -21,7 +21,7 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:label=f'Enable {source.label}',description=f'Enable the {source.label} weather data source.',value_type=AttributeValueType.BOOLEAN,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value=source.get_default_enabled_state(),@@ -39,7 +39,7 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:f'Usually: {canonical_base_url}'),value_type=AttributeValueType.TEXT,- value_range_str='',+ value_range=None,is_editable=True,is_required=False,initial_value=canonical_base_url,@@ -51,17 +51,21 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:label=f'{source.label} API Key',description=f'API key for {source.label} weather service (required if is enabled).',value_type=AttributeValueType.SECRET,- value_range_str='',+ value_range=None,is_editable=True,is_required=False,initial_value='',)settings_dict['DEFAULT_POLLING_INTERVAL_SECONDS'] = SettingDefinition(- label='Default Polling Interval (Seconds)',- description='Default interval in seconds for polling weather data from enabled sources.',+ label='Minimum Polling Interval (seconds)',+ description=(+ 'Minimum time between weather data updates. Some weather '+ 'services may update less frequently to honor their own '+ 'API rate limits.'+ ),value_type=AttributeValueType.INTEGER,- value_range_str='5-86400', # 5 seconds to 24 hours+ value_range=[ 5, 86400 ],is_editable=True,is_required=True,initial_value=600,@@ -75,27 +79,27 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:'rate-limit hits during restart loops. 0 disables warmup.'),value_type=AttributeValueType.INTEGER,- value_range_str='0-300',+ value_range=[ 0, 300 ],is_editable=True,is_required=True,initial_value=30,)-+settings_dict['WEATHER_CACHE_ENABLED'] = SettingDefinition(label='Enable Weather Data Caching',description='Enable caching of weather data to reduce API calls and improve performance.',value_type=AttributeValueType.BOOLEAN,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value=True,)-+settings_dict['WEATHER_ALERTS_ENABLED'] = SettingDefinition(label='Enable Weather Alerts',description='Enable processing of weather alerts from data sources and creation of system alarms.',value_type=AttributeValueType.BOOLEAN,- value_range_str='',+ value_range=None,is_editable=True,is_required=True,initial_value=True,diff --git a/src/hi/apps/weather/templates/weather/panes/astronomical_brief.html b/src/hi/apps/weather/templates/weather/panes/astronomical_brief.htmlindex 9c8a5ec3..31eaf913 100644--- a/src/hi/apps/weather/templates/weather/panes/astronomical_brief.html+++ b/src/hi/apps/weather/templates/weather/panes/astronomical_brief.html@@ -1,25 +1,27 @@{% load static %}{% load units %}-<div class="d-flex justify-content-between" >- <div>- Sunrise:- {% if astronomical_data.sunrise %}- {{ astronomical_data.sunrise.value }}- {% else %}- --- {% endif %}- </div>- <div>- Sunset:- {% if astronomical_data.sunset %}- {{ astronomical_data.sunset.value }}- {% else %}- --- {% endif %}+<div class="d-flex justify-content-between align-items-center">+ <div class="small lh-sm">+ <div>+ Sunrise:+ {% if astronomical_data.sunrise %}+ {{ astronomical_data.sunrise.value }}+ {% else %}+ --+ {% endif %}+ </div>+ <div>+ Sunset:+ {% if astronomical_data.sunset %}+ {{ astronomical_data.sunset.value }}+ {% else %}+ --+ {% endif %}+ </div></div>- <div>- Moon:+ <div class="d-flex align-items-center small">+ <span class="mr-1">Moon:</span>{% if astronomical_data.moon_illumination %}{% with astronomical_data.moon_phase as moon_phase %}<img height="32" src="{% static moon_phase.icon_filename %}"diff --git a/src/hi/integrations/connector/integration_connector.py b/src/hi/integrations/connector/integration_connector.pyindex 3c9d6e55..f1f0a882 100644--- a/src/hi/integrations/connector/integration_connector.py+++ b/src/hi/integrations/connector/integration_connector.py@@ -30,7 +30,8 @@ from hi.integrations.enums import IntegrationCapabilityfrom .external_view_data import ExternalViewDatafrom .integration_controller import IntegrationControllerfrom .sync_check import IntegrationSyncCheck, SyncDelta-from .sync_result import IntegrationSyncResult+from .sync_preview import IntegrationSyncPreviewer+from .sync_result import IntegrationSyncResult, IntegrationSyncPreviewResultfrom hi.integrations.transient_models import IntegrationKeylogger = logging.getLogger(__name__)@@ -246,6 +247,87 @@ class IntegrationConnector( CapabilityGateway ):"""raise NotImplementedError('Subclasses must override this method')+ @property+ def supports_preview(self) -> bool:+ """Whether this connector can produce a sync preview without+ committing changes. True when the subclass overrides either+ ``_sync_preview_impl`` (higher-fidelity preview) or+ ``check_needs_sync`` (the framework default impl is built on+ the latter). The pre-sync modal's Preview affordance is gated+ on this so connectors that opt out of both don't surface a+ non-functional button.++ Structural check (method override detection) rather than a+ runtime probe so it stays cheap and succeeds before upstream+ connectivity is established.+ """+ if type(self)._sync_preview_impl is not IntegrationConnector._sync_preview_impl:+ return True+ return type(self).check_needs_sync is not IntegrationConnector.check_needs_sync++ def sync_preview(self,+ is_initial_connect : bool,+ preserve_user_data : bool = True,+ ) -> IntegrationSyncPreviewResult:+ """Public preview entry point. Parallels ``sync()`` but commits+ no upstream or HI changes -- the framework default impl uses+ ``check_needs_sync()`` (a cheap read-only upstream probe) and+ higher-fidelity overrides are expected to honor the same+ no-mutation contract.++ Acquires the same lock as ``sync()`` so the preview reflects+ the same DB state a real sync would see, and a real sync can't+ race in mid-preview. Skips ``post_sync`` and the sync-check+ cache write that ``sync()`` performs on success -- both are+ side effects of a real sync and don't apply to preview.++ Subclasses override ``_sync_preview_impl`` when they want+ higher-fidelity preview than what ``check_needs_sync`` can+ provide; the public entry point stays the same.+ """+ try:+ with ExclusionLockContext(name=self.SYNCHRONIZATION_LOCK_NAME):+ logger.debug(f'{self.__class__.__name__} sync_preview started.')+ result = self._sync_preview_impl(+ is_initial_connect = is_initial_connect,+ preserve_user_data = preserve_user_data,+ )+ except Exception as e:+ # Broad catch: any failure during preview must surface in+ # the result modal as an error rather than crashing the+ # view or -- worse -- silently rendering the "Nothing new"+ # state. Preview is a read-only diagnostic; an+ # unobservable failure defeats the purpose.+ logger.exception(e)+ result = IntegrationSyncPreviewResult(+ title = self.get_result_title(is_initial_connect=is_initial_connect),+ error_list = [str(e) or e.__class__.__name__],+ )+ finally:+ logger.debug(f'{self.__class__.__name__} sync_preview ended.')+ return result++ def _sync_preview_impl(self,+ is_initial_connect : bool,+ preserve_user_data : bool,+ ) -> IntegrationSyncPreviewResult:+ """Default preview implementation. Delegates to+ ``IntegrationSyncPreviewer.build_from_check`` which leverages+ the integration's ``check_needs_sync`` drift probe.++ Subclasses with cleanly-separated change-detection logic+ (e.g., a synchronizer whose ``_sync_impl`` accepts a+ ``dry_run`` flag) override this method to deliver+ full-fidelity preview.+ """+ return IntegrationSyncPreviewer.build_from_check(+ check_needs_sync_callable = self.check_needs_sync,+ result_title = self.get_result_title(+ is_initial_connect = is_initial_connect,+ ),+ preserve_user_data = preserve_user_data,+ )+async def check_needs_sync(self) -> Optional[SyncDelta]:"""Periodic sync-check probe. Return a ``SyncDelta`` describinghow upstream has drifted from HI's current state, or ``None``diff --git a/src/hi/integrations/connector/monitors.py b/src/hi/integrations/connector/monitors.pyindex 2ba65c82..99ac41b3 100644--- a/src/hi/integrations/connector/monitors.py+++ b/src/hi/integrations/connector/monitors.py@@ -41,12 +41,12 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):INTERVAL_SECS = IntegrationSyncCheck.INTERVAL_SECSdef __init__( self ):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )return+ def get_polling_interval_secs(self) -> int:+ return self.INTERVAL_SECS+def alarm_ceiling(self):# Drift detection is informational by design -- the user always# confirms the actual sync. Cap at INFO so probe failures@@ -62,7 +62,6 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):'Periodic check across integrations for ''changes that would warrant a Refresh.'),- expected_heartbeat_interval_secs = cls.INTERVAL_SECS,)async def do_work(self):diff --git a/src/hi/integrations/connector/sync_check.py b/src/hi/integrations/connector/sync_check.pyindex 8605fbec..6bb518bb 100644--- a/src/hi/integrations/connector/sync_check.py+++ b/src/hi/integrations/connector/sync_check.py@@ -108,7 +108,16 @@ class IntegrationSyncCheck:"""INTERVAL_SECS = 4 * 60 * 60-++ # Alarm lifetime governs the post-acknowledgement nag window+ # (after the AlertQueue dedup-anchor refactor): after a user+ # dismisses the needs-sync alert, the suppression lasts this long+ # before another needs-sync alarm can re-surface. Twenty-four+ # hours strikes a balance between letting the operator defer+ # within their workday and reminding them the next time they+ # sit down at the console.+ NAG_INTERVAL_SECS = 24 * 60 * 60+_CACHE_TTL_SECS = INTERVAL_SECS * 2_CACHE_KEY_PREFIX = 'integrations:sync_check:'@@ -242,8 +251,9 @@ class IntegrationSyncCheck:into the needs-sync state. Per-integration unique signature(``integrations.needs_sync.<integration_id>``) so twointegrations both reporting drift surface as two distinct- alerts. Lifetime is ``Alarm.MAX_LIFETIME_SECS`` -- the- canonical "until acknowledged" value."""+ alerts. Lifetime is ``NAG_INTERVAL_SECS`` -- the post-ack+ suppression window before a still-out-of-sync integration is+ allowed to re-pop another alert."""from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.alert_manager import AlertManagerfrom hi.apps.alert.enums import AlarmLevel, AlarmSource@@ -277,7 +287,7 @@ class IntegrationSyncCheck:title = result.summary_message,sensor_response_list = [ sensor_response ],security_level = SecurityLevel.OFF,- alarm_lifetime_secs = Alarm.MAX_LIFETIME_SECS,+ alarm_lifetime_secs = IntegrationSyncCheck.NAG_INTERVAL_SECS,timestamp = datetimeproxy.now(),)AlertManager().upsert_alarm( alarm )diff --git a/src/hi/integrations/connector/sync_preview.py b/src/hi/integrations/connector/sync_preview.pynew file mode 100644index 00000000..44f69ef5--- /dev/null+++ b/src/hi/integrations/connector/sync_preview.py@@ -0,0 +1,130 @@+"""+Default sync-preview construction.++The connector base class declares the interface (``sync_preview`` /+``_sync_preview_impl``); the business logic of the framework-default+preview lives here as a namespace class. Per-integration+``_sync_preview_impl`` overrides either bypass this module entirely+(for higher-fidelity previews) or call ``build_from_check`` and+post-process the result.++The default preview's fidelity is bounded by what ``check_needs_sync``+(the periodic drift probe) can return -- a set of added and removed+``IntegrationKey``s. The framework can accurately bucket removals+into ``removed_list`` / ``detached_list`` per the operator's policy+(HI-side entities are queryable and classifiable here); it cannot+predict updates or reconnects, and has no source for upstream-side+display names. ``approximation_message`` names these gaps so the+operator sees what isn't predicted.+"""+import logging++from asgiref.sync import async_to_sync++from hi.apps.entity.models import Entity++from .sync_result import IntegrationSyncPreviewResult+from .user_data_detector import EntityUserDataDetector++logger = logging.getLogger(__name__)+++class IntegrationSyncPreviewer:+ """Namespace for the default preview construction. Class methods+ rather than module-level functions so call sites carry the+ ``IntegrationSyncPreviewer.`` prefix and group naturally.+ """++ APPROXIMATION_MESSAGE = (+ "This preview detects upstream additions and removals via the "+ "integration's drift check. Update and reconnect detection are "+ "not predicted by this preview."+ )+ NO_PREVIEW_MESSAGE = (+ 'This integration does not provide a preview implementation.'+ )++ @classmethod+ def build_from_check( cls,+ check_needs_sync_callable,+ result_title : str,+ preserve_user_data : bool,+ ) -> IntegrationSyncPreviewResult:+ """Run the integration's ``check_needs_sync`` probe and massage+ the returned ``SyncDelta`` into an+ ``IntegrationSyncPreviewResult``. Returns an empty result with+ the no-preview message when the integration opts out of+ ``check_needs_sync``.++ ``check_needs_sync_callable`` is the connector's bound method+ (still async); this layer crosses the async/sync boundary so+ callers stay in normal sync flow.++ Failures from the probe (upstream unreachable, auth expired,+ client unavailable) are caught and surfaced via+ ``error_list`` rather than propagated -- otherwise the+ operator would see the preview-result modal's "Nothing new"+ branch when in fact the check itself failed to run.+ """+ result = IntegrationSyncPreviewResult( title = result_title )++ try:+ delta = async_to_sync( check_needs_sync_callable )()+ except Exception as e:+ logger.exception( 'check_needs_sync raised during preview' )+ result.error_list.append( str(e) or e.__class__.__name__ )+ return result++ if delta is None:+ result.approximation_message = cls.NO_PREVIEW_MESSAGE+ return result++ cls._populate_added( result = result, delta = delta )+ cls._populate_removed(+ result = result,+ delta = delta,+ preserve_user_data = preserve_user_data,+ )+ result.approximation_message = cls.APPROXIMATION_MESSAGE+ return result++ @staticmethod+ def _populate_added( result : IntegrationSyncPreviewResult, delta ):+ """Created items: count + technical keys. Display names are not+ available from this layer -- the upstream side is opaque to the+ framework, and ``check_needs_sync`` only returns+ ``IntegrationKey`` instances. The technical names surface+ behind a collapsed debug section in the preview-result modal+ so the operator can verify what would be created without+ committing to sync; placeholder entries in ``created_list``+ keep the stat-card count consistent with the upstream count.+ """+ if not delta.added:+ return+ result.upstream_added_keys = sorted(+ k.integration_name for k in delta.added+ )+ result.created_list = [ '' ] * len( delta.added )+ return++ @staticmethod+ def _populate_removed( result : IntegrationSyncPreviewResult,+ delta,+ preserve_user_data : bool ):+ """Removed items: bucket each HI-side entity per policy, matching+ what a real sync's removal pass would do for these keys.+ Entities classified by ``EntityUserDataDetector`` -- the same+ classifier the sync uses, so the bucketing is faithful to what+ Refresh would actually produce.+ """+ if not delta.removed:+ return+ removed_entities = (+ Entity.objects.filter_by_integration_keys( list( delta.removed ))+ )+ for entity in removed_entities:+ if preserve_user_data and EntityUserDataDetector.has_user_created_attributes( entity ):+ result.detached_list.append( entity.name )+ else:+ result.removed_list.append( entity.name )+ returndiff --git a/src/hi/integrations/connector/sync_result.py b/src/hi/integrations/connector/sync_result.pyindex d1b9f507..9bce83be 100644--- a/src/hi/integrations/connector/sync_result.py+++ b/src/hi/integrations/connector/sync_result.py@@ -90,3 +90,40 @@ class IntegrationSyncResult:or self.detached_listor self.removed_list)++ @property+ def has_displayable_created_list(self) -> bool:+ """True iff ``created_list`` contains at least one non-empty+ name worth rendering in the Created category section. The+ preview's framework default impl populates ``created_list``+ with placeholder empty entries to keep the stat-card "Created"+ count consistent with the upstream-added count; the templates+ use this to skip rendering an empty-bodied Created section in+ that case. For real sync results every entry is a real entity+ name and this is equivalent to ``bool(created_list)``."""+ return any(self.created_list)+++@dataclass+class IntegrationSyncPreviewResult(IntegrationSyncResult):+ """Preview-time result for a sync that has not been executed.++ Shape-compatible with ``IntegrationSyncResult`` so the result-modal+ partials render either; carries two preview-specific fields:++ * ``approximation_message`` -- prose disclaimer about preview+ fidelity (what wasn't predicted, or couldn't be). Rendered as a+ small callout in the preview-result modal. ``None`` when the+ preview is full-fidelity and has nothing to caveat.++ * ``upstream_added_keys`` -- the integration_name tokens for items+ detected upstream but not present in HI. The default preview+ impl can't resolve these into display names (the upstream side+ is opaque at the framework layer), so they're hidden from the+ main visible result and surfaced via a collapsible debug section+ so the operator can verify what would be created without+ committing to sync. Stays empty when an integration's higher-+ fidelity override populates ``created_list`` with real names.+ """+ approximation_message: Optional[str] = None+ upstream_added_keys: List[str] = field(default_factory=list)diff --git a/src/hi/integrations/connector/urls.py b/src/hi/integrations/connector/urls.pyindex 553a3923..253a19d1 100644--- a/src/hi/integrations/connector/urls.py+++ b/src/hi/integrations/connector/urls.py@@ -31,6 +31,9 @@ urlpatterns = [re_path( r'^sync/(?P<integration_id>[\w\-]+)$',views.IntegrationSyncView.as_view(),name='integrations_connect_sync' ),+ re_path( r'^sync-preview/(?P<integration_id>[\w\-]+)$',+ views.IntegrationSyncPreviewView.as_view(),+ name='integrations_connect_sync_preview' ),re_path( r'^manage/(?P<integration_id>[\w\-]*)$',views.ConnectorManageView.as_view(),name='integrations_connect_manage' ),diff --git a/src/hi/integrations/connector/views.py b/src/hi/integrations/connector/views.pyindex 4fb73737..bce8b14b 100644--- a/src/hi/integrations/connector/views.py+++ b/src/hi/integrations/connector/views.py@@ -114,10 +114,16 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):)removal_summary = None+ supports_preview = Falseif not is_initial_connect:removal_summary = EntityIntegrationOperations.summarize_for_removal(integration_id = integration_data.integration_id,)+ # Preview is only meaningful on the update-check path -- on+ # initial-connect there's nothing in HI to be cautious+ # about yet. Surface the link only when the connector also+ # declares it can produce a preview.+ supports_preview = connector.supports_previewcontext = {'integration_data': integration_data,@@ -127,10 +133,62 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):),'sync_url': sync_url,'removal_summary': removal_summary,+ 'supports_preview': supports_preview,}return self.modal_response( request, context )+class IntegrationSyncPreviewView( HiModalView, IntegrationViewMixin ):+ """Read-only preview of what a sync would do, without committing+ any changes. Reached from the pre-sync modal's Preview link as a+ cautious-operator option before pulling the trigger on Refresh.++ The preview-result modal carries forward the same RETAIN / REMOVE+ policy actions the pre-sync modal exposes, but only when the+ preview's ``detached_list`` is non-empty -- meaning the policy+ choice actually matters for this sync's removals. Connectors that+ don't support preview return 404."""++ def get_template_name( self ) -> str:+ return 'integrations/connector/modals/sync_preview_result.html'++ def get( self, request, *args, **kwargs ):+ integration_data = self.get_integration_data( request, *args, **kwargs )+ connector = integration_data.integration_gateway.get_connector()+ if connector is None or not connector.supports_preview:+ return page_not_found_response( request )++ # Threaded through so the result title's update-vs-connect+ # framing stays correct in the edge case that this endpoint+ # is reached for an integration with no HI entities yet. The+ # framework doesn't *surface* the affordance there (the+ # pre-sync modal gates the Preview link on not-initial), but+ # we don't refuse a direct call either.+ is_initial_connect = not Entity.objects.filter(+ integration_id = integration_data.integration_id,+ ).exists()++ sync_result = connector.sync_preview(+ is_initial_connect = is_initial_connect,+ preserve_user_data = True,+ )++ sync_url = reverse(+ 'integrations_connect_sync',+ kwargs = { 'integration_id': integration_data.integration_id },+ )++ return self.modal_response(+ request,+ context = {+ 'sync_result': sync_result,+ 'integration_data': integration_data,+ 'is_initial_connect': is_initial_connect,+ 'sync_url': sync_url,+ },+ )++class IntegrationSyncView( HiModalView, IntegrationViewMixin, ConnectorViewMixin ):"""Framework sync execution view. Invokes the integration's connector@@ -327,7 +385,11 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditViif not integration_data.integration.is_enabled:raise BadRequest( f'{integration_data.label} integration is not configured' )- health_status_provider = integration_data.integration_gateway.get_connector().get_health_status_provider()+ connector = integration_data.integration_gateway.get_connector()+ if not connector:+ raise BadRequest( f'{integration_data.label} integration not supported' )++ health_status_provider = connector.get_health_status_provider()attr_item_context = IntegrationAttributeItemEditContext(integration_data = integration_data,diff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.pyindex 79ce1b3b..edcfa080 100644--- a/src/hi/integrations/enums.py+++ b/src/hi/integrations/enums.py@@ -1,4 +1,4 @@-from typing import Dict, FrozenSet, Optional+from typing import Dict, FrozenSet, List, Optional, Unionfrom hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.common.enums import LabeledEnum@@ -36,14 +36,28 @@ class IntegrationAttributeType( LabeledEnum ):label : str,description : str,value_type : AttributeValueType,- value_range_dict : Dict[ str, str ],+ value_range : Optional[ Union[ List, Dict ] ],is_editable : bool,is_required : bool,initial_value : str = '',capabilities : Optional[ FrozenSet[ IntegrationCapability ] ] = None ):super().__init__( label, description )self.value_type = value_type- self.value_range_dict = value_range_dict+ # Shape is value_type-specific and parallels the underlying+ # ``Attribute.value_range_str`` reader on the model side:+ # * ENUM -> dict of {value: label} OR list of values+ # (consumed via ``Attribute.choices()``)+ # * INTEGER -> two-element list [min, max] OR+ # dict {"min": ..., "max": ...}+ # (consumed via ``Attribute.value_range_int()``)+ # * FLOAT -> same shapes as INTEGER+ # (consumed via ``Attribute.value_range()``)+ # * TEXT / SECRET / BOOLEAN / FILE -> ``None`` (no constraint)+ # Persisted by IntegrationManager as ``json.dumps(value_range)``+ # so the attribute model's ``value_range_str`` carries a+ # canonical JSON representation regardless of which shape the+ # author used.+ self.value_range = value_rangeself.is_editable = is_editableself.is_required = is_requiredself.initial_value = initial_valuediff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex 4cb35f50..5a01c4e8 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -27,9 +27,11 @@ class IntegrationGateway:def notify_settings_changed(self):"""Called when Integration or IntegrationAttribute models are- modified. Subclass implementations should reload configuration and- notify dependent components."""- raise NotImplementedError('Subclasses must override this method')+ modified. Default is no-op; integrations with cached upstream+ clients or manager state override to reload them. Reference-+ only integrations (no connector, no monitor) have nothing to+ reload on a settings change and inherit the default."""+ returndef get_connector(self) -> Optional[IntegrationConnector]:"""Return the integration's connector when it supports the CONNECTdiff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.pyindex 58b80880..0a9e0095 100644--- a/src/hi/integrations/integration_manager.py+++ b/src/hi/integrations/integration_manager.py@@ -467,13 +467,25 @@ class IntegrationManager( Singleton ):# ``attribute_type.value`` as the row's ``order_id`` makes the# config-page render order match the operator-facing order# the integration author defined.+ # Only json-serialize when a range/choices declaration is+ # actually present. Without this guard ``json.dumps(None)``+ # would serialize the literal string ``'null'`` into the DB,+ # which then trips the ``if not self.value_range_str`` early-+ # return paths in the reader methods (the four-character+ # string is truthy). Most attributes are TEXT / SECRET /+ # BOOLEAN with no range, so this is the common case.+ if attribute_type.value_range is not None:+ value_range_str = json.dumps( attribute_type.value_range )+ else:+ value_range_str = None+attribute = IntegrationAttribute(integration = integration,name = attribute_type.label,value = attribute_type.initial_value,description = attribute_type.description or '',value_type_str = str(attribute_type.value_type),- value_range_str = json.dumps( attribute_type.value_range_dict ),+ value_range_str = value_range_str,integration_key_str = str(integration_key),attribute_type_str = AttributeType.PREDEFINED,is_editable = attribute_type.is_editable,diff --git a/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html b/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.htmlindex b14b4cbd..45b0f2fb 100644--- a/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html+++ b/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html@@ -90,6 +90,13 @@ Check {{ integration_data.label }} for updates?{% endblock %}{% block action_center %}+{% if supports_preview %}+<a class="btn btn-outline-primary"+ href="{% url 'integrations_connect_sync_preview' integration_id=integration_data.integration_id %}"+ role="button" data-async="modal">+ {% icon "eye" size="sm" css_class="hi-icon-left" %}PREVIEW CHANGES+</a>+{% endif %}{% if removal_summary.has_mixed_state %}<button type="submit" class="btn btn-outline-danger ml-2"name="preserve_user_data" value="false">diff --git a/src/hi/integrations/templates/integrations/connector/modals/sync_preview_result.html b/src/hi/integrations/templates/integrations/connector/modals/sync_preview_result.htmlnew file mode 100644index 00000000..e20c7bfd--- /dev/null+++ b/src/hi/integrations/templates/integrations/connector/modals/sync_preview_result.html@@ -0,0 +1,110 @@+{% extends "modals/action_3.html" %}+{% load icons %}++{% comment %}+Sync preview-result modal. Same shape as sync_result.html but with+preview framing -- the operator sees what a sync would do without+committing it, and decides to proceed or back out.++Reuses the five sync-result partials so the information layout+matches the post-sync modal exactly. Preview-specific surfaces (the+approximation disclaimer and the technical-key debug expander) sit+alongside them.++Footer action selection mirrors the pre-sync modal's policy logic+but is driven by the preview's actual ``detached_list`` rather than+the integration's general removal_summary -- the preview's smarter+because it already knows which removals would carry user data. When+the preview reports no detachments, only a single SYNC button shows.+When it reports detachments, the operator picks RETAIN MISSING or+REMOVE MISSING (same wire format as pre_sync_confirm.html).++Context:+ sync_result : IntegrationSyncPreviewResult (required)+ integration_data : IntegrationData (required)+ sync_url : str (required) -- target of the SYNC actions.+{% endcomment %}++{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}++{% block title_text %}+Preview: {{ sync_result.title }}+{% endblock %}++{% block preamble %}+<form action="{{ sync_url }}" method="post" class="form" data-async="modal">+ {% csrf_token %}+{% endblock %}++{% block body %}+{% include "integrations/panes/integration_modal_header.html" %}++<div class="alert alert-info small text-center mb-3">+ <strong>Preview</strong> — no changes have been made.+</div>++{% include "integrations/connector/panes/sync_result_hero.html" with is_initial_connect=False %}++{% if sync_result.has_changes %}+ {% include "integrations/connector/panes/sync_result_stats.html" %}+ {% include "integrations/connector/panes/sync_result_categories.html" %}+{% endif %}++{% if sync_result.approximation_message %}+ <div class="alert alert-light small mb-3 border">+ <strong>Note:</strong> {{ sync_result.approximation_message }}+ </div>+{% endif %}++{% if sync_result.upstream_added_keys %}+ <div class="mt-2 mb-3">+ <a class="text-muted small" data-toggle="collapse"+ href="#hi-sync-preview-upstream-keys" role="button"+ aria-expanded="false" aria-controls="hi-sync-preview-upstream-keys">+ Show upstream identifiers ({{ sync_result.upstream_added_keys|length }})+ </a>+ <div class="collapse" id="hi-sync-preview-upstream-keys">+ <ul class="small mt-1 mb-0 text-muted">+ {% for key in sync_result.upstream_added_keys %}+ <li><code>{{ key }}</code></li>+ {% endfor %}+ </ul>+ </div>+ </div>+{% endif %}++{% include "integrations/connector/panes/sync_result_errors.html" %}+{% include "integrations/connector/panes/sync_result_info.html" %}+{% endblock %}++{% block action_left %}+<a id="hi-modal-cancel" role="button"+ class="btn btn-outline-tertiary" href="#" data-dismiss="modal">CANCEL</a>+{% endblock %}++{% block action_center %}+{% if sync_result.detached_list %}+<button type="submit" class="btn btn-outline-danger"+ name="preserve_user_data" value="false">+ {% icon "warning" size="sm" css_class="hi-icon-left" %}REMOVE MISSING+</button>+{% endif %}+{% endblock %}++{% block action_right %}+{% if sync_result.detached_list %}+<button type="submit" class="btn btn-primary"+ name="preserve_user_data" value="true">+ {% icon "shield" size="sm" css_class="hi-icon-left" %}RETAIN MISSING+</button>+{% else %}+<button type="submit" class="btn btn-primary"+ name="preserve_user_data" value="true">+ {% icon "sync" size="lg" css_class="hi-icon-left" %}UPDATE+</button>+{% endif %}+{% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/integrations/templates/integrations/connector/modals/sync_result.html b/src/hi/integrations/templates/integrations/connector/modals/sync_result.htmlindex 0e4ac9f0..da898686 100644--- a/src/hi/integrations/templates/integrations/connector/modals/sync_result.html+++ b/src/hi/integrations/templates/integrations/connector/modals/sync_result.html@@ -8,11 +8,16 @@surfaced rather than silently swallowed by an automatic transitionto placement.- Renders a hero headline, a stat-card row of change counts,- color-coded per-category enumerations of affected entities, and- collapsible Errors / Details sections. When the sync produced- newly-created entities, the footer's primary CTA navigates to the- placement modal; otherwise the footer is a single dismissal button.+ The body composes shared panes:+ sync_result_hero.html -- headline (success / nothing-new /+ error-partial / error-fatal).+ sync_result_stats.html -- stat-card row (success-only).+ sync_result_categories.html -- per-category enumerations.+ sync_result_errors.html -- collapsible errors block.+ sync_result_info.html -- collapsible details block.++ The preview-result modal reuses the same partials with preview+ framing.The modal title bar uses the generic HI logo + short generic title;the integration's identity is surfaced as a body subtitle row@@ -22,7 +27,7 @@Context:sync_result : IntegrationSyncResult (required)integration_data : IntegrationData (required)- placement_url : str (optional) -- target of the 'Place N items'+ placement_url : str (optional) -- target of the 'Place N items'CTA. Required when sync_result.created_list isnon-empty; ignored otherwise.{% endcomment %}@@ -36,163 +41,11 @@{% block body %}{% include "integrations/panes/integration_modal_header.html" %}-{% comment %}- Hero headline -- errors take precedence; otherwise the- change-count summary speaks.-{% endcomment %}-{% if sync_result.error_list and not sync_result.has_changes %}- <div class="text-center mb-4">- <div class="text-danger mb-1 hi-sync-result-hero-icon">⚠</div>- <h3 class="text-danger mb-1">- {% if is_initial_connect %}Connect failed{% else %}Update check failed{% endif %}- </h3>- <div class="text-muted small">- {{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.- </div>- </div>-{% elif sync_result.error_list %}- <div class="text-center mb-4">- <div class="text-warning mb-1 hi-sync-result-hero-icon">⚠</div>- <h3 class="text-warning mb-1">- {% if is_initial_connect %}Connect completed with errors{% else %}Update check completed with errors{% endif %}- </h3>- <div class="text-muted small">- {{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.- </div>- </div>-{% elif not sync_result.has_changes %}- <div class="text-center mb-4">- <div class="text-muted mb-1 hi-sync-result-hero-icon">—</div>- <h3 class="text-muted mb-1">- {% if is_initial_connect %}No items found.{% else %}Nothing new{% endif %}- </h3>- <div class="text-muted small">- {% if is_initial_connect %}- The connection succeeded but the upstream source returned no items.- {% else %}- No changes since the last update check.- {% endif %}- </div>- </div>-{% else %}- <div class="text-center mb-3">- <div class="text-success mb-1 hi-sync-result-hero-icon">✓</div>- <h3 class="text-success mb-1">- {% if is_initial_connect %}Connect complete{% else %}Update check complete{% endif %}- </h3>- </div>-- {% comment %}- Only non-zero categories render -- symmetry is less important- than not implying a stat that doesn't exist.- {% endcomment %}- <div class="d-flex justify-content-around flex-wrap text-center mb-4 pb-3 border-bottom">- {% if sync_result.created_list %}- <div class="px-3">- <div class="text-success font-weight-bold hi-sync-result-stat-number">- {{ sync_result.created_list|length }}- </div>- <div class="text-muted small text-uppercase hi-uppercase-label">Created</div>- </div>- {% endif %}- {% if sync_result.updated_list %}- <div class="px-3">- <div class="text-info font-weight-bold hi-sync-result-stat-number">- {{ sync_result.updated_list|length }}- </div>- <div class="text-muted small text-uppercase hi-uppercase-label">Updated</div>- </div>- {% endif %}- {% if sync_result.reconnected_list %}- <div class="px-3">- <div class="text-info font-weight-bold hi-sync-result-stat-number">- {{ sync_result.reconnected_list|length }}- </div>- <div class="text-muted small text-uppercase hi-uppercase-label">Reconnected</div>- </div>- {% endif %}- {% if sync_result.detached_list %}- <div class="px-3">- <div class="text-secondary font-weight-bold hi-sync-result-stat-number">- {{ sync_result.detached_list|length }}- </div>- <div class="text-muted small text-uppercase hi-uppercase-label">Detached</div>- </div>- {% endif %}- {% if sync_result.removed_list %}- <div class="px-3">- <div class="text-danger font-weight-bold hi-sync-result-stat-number">- {{ sync_result.removed_list|length }}- </div>- <div class="text-muted small text-uppercase hi-uppercase-label">Removed</div>- </div>- {% endif %}- </div>-- {% if sync_result.removed_list %}- <div class="mb-3 pl-3 hi-category-section hi-category-section--danger">- <div class="small text-danger text-uppercase mb-1 hi-uppercase-label">- Removed ({{ sync_result.removed_list|length }})- </div>- <ul class="list-unstyled small mb-0 hi-sync-result-item-list">- {% for name in sync_result.removed_list %}- <li>{{ name }}</li>- {% endfor %}- </ul>- </div>- {% endif %}+{% include "integrations/connector/panes/sync_result_hero.html" %}- {% if sync_result.detached_list %}- <div class="mb-3 pl-3 hi-category-section hi-category-section--secondary">- <div class="small text-secondary text-uppercase mb-1 hi-uppercase-label">- Detached ({{ sync_result.detached_list|length }})- </div>- <ul class="list-unstyled small mb-0 hi-sync-result-item-list">- {% for name in sync_result.detached_list %}- <li>{{ name }}</li>- {% endfor %}- </ul>- </div>- {% endif %}-- {% if sync_result.updated_list %}- <div class="mb-3 pl-3 hi-category-section hi-category-section--info">- <div class="small text-info text-uppercase mb-1 hi-uppercase-label">- Updated ({{ sync_result.updated_list|length }})- </div>- <ul class="list-unstyled small mb-0 hi-sync-result-item-list">- {% for name in sync_result.updated_list %}- <li>{{ name }}</li>- {% endfor %}- </ul>- </div>- {% endif %}-- {% if sync_result.reconnected_list %}- <div class="mb-3 pl-3 hi-category-section hi-category-section--info">- <div class="small text-info text-uppercase mb-1 hi-uppercase-label">- Reconnected ({{ sync_result.reconnected_list|length }})- </div>- <ul class="list-unstyled small mb-0 hi-sync-result-item-list">- {% for name in sync_result.reconnected_list %}- <li>{{ name }}</li>- {% endfor %}- </ul>- </div>- {% endif %}-- {% if sync_result.created_list %}- <div class="mb-3 pl-3 hi-category-section hi-category-section--success">- <div class="small text-success text-uppercase mb-1 hi-uppercase-label">- Created ({{ sync_result.created_list|length }})- </div>- <ul class="list-unstyled small mb-0 hi-sync-result-item-list">- {% for name in sync_result.created_list %}- <li>{{ name }}</li>- {% endfor %}- </ul>- </div>- {% endif %}+{% if sync_result.has_changes %}+ {% include "integrations/connector/panes/sync_result_stats.html" %}+ {% include "integrations/connector/panes/sync_result_categories.html" %}{% endif %}{% if sync_result.footer_message %}@@ -201,39 +54,8 @@</div>{% endif %}-{% if sync_result.error_list %}-<div class="mb-2 pl-3 hi-category-section hi-category-section--danger">- <a class="small text-danger text-uppercase hi-uppercase-label" data-toggle="collapse"- href="#hi-sync-result-errors" role="button"- aria-expanded="true" aria-controls="hi-sync-result-errors">- Errors ({{ sync_result.error_list|length }})- </a>- <div class="collapse show" id="hi-sync-result-errors">- <ul class="list-unstyled small mt-1 mb-0">- {% for error_message in sync_result.error_list %}- <li class="text-danger">{{ error_message }}</li>- {% endfor %}- </ul>- </div>-</div>-{% endif %}--{% if sync_result.info_list %}-<div class="mt-2">- <a class="text-muted small" data-toggle="collapse"- href="#hi-sync-result-info" role="button"- aria-expanded="false" aria-controls="hi-sync-result-info">- Show details ({{ sync_result.info_list|length }})- </a>- <div class="collapse" id="hi-sync-result-info">- <ul class="small mt-1 mb-0 text-muted hi-sync-result-info-list">- {% for info_message in sync_result.info_list %}- <li>{{ info_message }}</li>- {% endfor %}- </ul>- </div>-</div>-{% endif %}+{% include "integrations/connector/panes/sync_result_errors.html" %}+{% include "integrations/connector/panes/sync_result_info.html" %}{% endblock %}{% comment %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/sync_result_categories.html b/src/hi/integrations/templates/integrations/connector/panes/sync_result_categories.htmlnew file mode 100644index 00000000..d2702454--- /dev/null+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_result_categories.html@@ -0,0 +1,81 @@+{% comment %}+Color-coded per-category enumerations of affected entities. Five+categories rendered in this order (severity-descending): removed,+detached, updated, reconnected, created. Each gated on its own+list being non-empty.++The Created section additionally gates on ``has_displayable_created_list``+because the preview's framework default impl populates ``created_list``+with placeholder empty entries to keep the stat-card "Created" count+consistent with the upstream-added count -- those placeholders have+no name to display here, so the section is skipped in that case+(the preview template surfaces the technical keys behind a separate+debug expander).++Context:+ sync_result : IntegrationSyncResult (or subclass).+{% endcomment %}+{% if sync_result.removed_list %}+<div class="mb-3 pl-3 hi-category-section hi-category-section--danger">+ <div class="small text-danger text-uppercase mb-1 hi-uppercase-label">+ Removed ({{ sync_result.removed_list|length }})+ </div>+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">+ {% for name in sync_result.removed_list %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+</div>+{% endif %}++{% if sync_result.detached_list %}+<div class="mb-3 pl-3 hi-category-section hi-category-section--secondary">+ <div class="small text-secondary text-uppercase mb-1 hi-uppercase-label">+ Detached ({{ sync_result.detached_list|length }})+ </div>+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">+ {% for name in sync_result.detached_list %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+</div>+{% endif %}++{% if sync_result.updated_list %}+<div class="mb-3 pl-3 hi-category-section hi-category-section--info">+ <div class="small text-info text-uppercase mb-1 hi-uppercase-label">+ Updated ({{ sync_result.updated_list|length }})+ </div>+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">+ {% for name in sync_result.updated_list %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+</div>+{% endif %}++{% if sync_result.reconnected_list %}+<div class="mb-3 pl-3 hi-category-section hi-category-section--info">+ <div class="small text-info text-uppercase mb-1 hi-uppercase-label">+ Reconnected ({{ sync_result.reconnected_list|length }})+ </div>+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">+ {% for name in sync_result.reconnected_list %}+ <li>{{ name }}</li>+ {% endfor %}+ </ul>+</div>+{% endif %}++{% if sync_result.has_displayable_created_list %}+<div class="mb-3 pl-3 hi-category-section hi-category-section--success">+ <div class="small text-success text-uppercase mb-1 hi-uppercase-label">+ Created ({{ sync_result.created_list|length }})+ </div>+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">+ {% for name in sync_result.created_list %}+ {% if name %}<li>{{ name }}</li>{% endif %}+ {% endfor %}+ </ul>+</div>+{% endif %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/sync_result_errors.html b/src/hi/integrations/templates/integrations/connector/panes/sync_result_errors.htmlnew file mode 100644index 00000000..437f8ee0--- /dev/null+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_result_errors.html@@ -0,0 +1,25 @@+{% comment %}+Collapsible error block. Default open -- errors are the operator's+first concern when present. Caller renders this regardless of result+state; the partial gates internally so it's a no-op when there are+no errors.++Context:+ sync_result : IntegrationSyncResult (or subclass).+{% endcomment %}+{% if sync_result.error_list %}+<div class="mb-2 pl-3 hi-category-section hi-category-section--danger">+ <a class="small text-danger text-uppercase hi-uppercase-label" data-toggle="collapse"+ href="#hi-sync-result-errors" role="button"+ aria-expanded="true" aria-controls="hi-sync-result-errors">+ Errors ({{ sync_result.error_list|length }})+ </a>+ <div class="collapse show" id="hi-sync-result-errors">+ <ul class="list-unstyled small mt-1 mb-0">+ {% for error_message in sync_result.error_list %}+ <li class="text-danger">{{ error_message }}</li>+ {% endfor %}+ </ul>+ </div>+</div>+{% endif %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/sync_result_hero.html b/src/hi/integrations/templates/integrations/connector/panes/sync_result_hero.htmlnew file mode 100644index 00000000..c59f1c68--- /dev/null+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_result_hero.html@@ -0,0 +1,55 @@+{% comment %}+Sync-result hero headline. One of four states:+ * error-fatal : errors present, no changes recorded.+ * error-partial : errors present, some changes recorded.+ * nothing-new : no changes, no errors.+ * success : changes recorded.+Initial-connect rewords the headline copy without changing the state+selection.++Context:+ sync_result : IntegrationSyncResult (or subclass).+ is_initial_connect : bool.+{% endcomment %}+{% if sync_result.error_list and not sync_result.has_changes %}+ <div class="text-center mb-4">+ <div class="text-danger mb-1 hi-sync-result-hero-icon">⚠</div>+ <h3 class="text-danger mb-1">+ {% if is_initial_connect %}Connect failed{% else %}Update check failed{% endif %}+ </h3>+ <div class="text-muted small">+ {{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.+ </div>+ </div>+{% elif sync_result.error_list %}+ <div class="text-center mb-4">+ <div class="text-warning mb-1 hi-sync-result-hero-icon">⚠</div>+ <h3 class="text-warning mb-1">+ {% if is_initial_connect %}Connect completed with errors{% else %}Update check completed with errors{% endif %}+ </h3>+ <div class="text-muted small">+ {{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.+ </div>+ </div>+{% elif not sync_result.has_changes %}+ <div class="text-center mb-4">+ <div class="text-muted mb-1 hi-sync-result-hero-icon">—</div>+ <h3 class="text-muted mb-1">+ {% if is_initial_connect %}No items found.{% else %}Nothing new{% endif %}+ </h3>+ <div class="text-muted small">+ {% if is_initial_connect %}+ The connection succeeded but the upstream source returned no items.+ {% else %}+ No changes since the last update check.+ {% endif %}+ </div>+ </div>+{% else %}+ <div class="text-center mb-3">+ <div class="text-success mb-1 hi-sync-result-hero-icon">✓</div>+ <h3 class="text-success mb-1">+ {% if is_initial_connect %}Connect complete{% else %}Update check complete{% endif %}+ </h3>+ </div>+{% endif %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/sync_result_info.html b/src/hi/integrations/templates/integrations/connector/panes/sync_result_info.htmlnew file mode 100644index 00000000..c9e0ac0a--- /dev/null+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_result_info.html@@ -0,0 +1,25 @@+{% comment %}+Collapsible "show details" block carrying diagnostic notes the+per-item lists can't express ("Found N upstream items", "Filtered+N by allowlist", ambiguous-reconnect breadcrumbs, etc.). Default+closed -- secondary to the change counts above.++Context:+ sync_result : IntegrationSyncResult (or subclass).+{% endcomment %}+{% if sync_result.info_list %}+<div class="mt-2">+ <a class="text-muted small" data-toggle="collapse"+ href="#hi-sync-result-info" role="button"+ aria-expanded="false" aria-controls="hi-sync-result-info">+ Show details ({{ sync_result.info_list|length }})+ </a>+ <div class="collapse" id="hi-sync-result-info">+ <ul class="small mt-1 mb-0 text-muted hi-sync-result-info-list">+ {% for info_message in sync_result.info_list %}+ <li>{{ info_message }}</li>+ {% endfor %}+ </ul>+ </div>+</div>+{% endif %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/sync_result_stats.html b/src/hi/integrations/templates/integrations/connector/panes/sync_result_stats.htmlnew file mode 100644index 00000000..0bb3e0e1--- /dev/null+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_result_stats.html@@ -0,0 +1,52 @@+{% comment %}+Stat-card row for the sync-result hero. Only non-zero categories+render -- symmetry is less important than not implying a stat that+doesn't exist. Caller is responsible for gating on+``sync_result.has_changes`` so this partial is not rendered for the+error / nothing-new states.++Context:+ sync_result : IntegrationSyncResult (or subclass).+{% endcomment %}+<div class="d-flex justify-content-around flex-wrap text-center mb-4 pb-3 border-bottom">+ {% if sync_result.created_list %}+ <div class="px-3">+ <div class="text-success font-weight-bold hi-sync-result-stat-number">+ {{ sync_result.created_list|length }}+ </div>+ <div class="text-muted small text-uppercase hi-uppercase-label">Created</div>+ </div>+ {% endif %}+ {% if sync_result.updated_list %}+ <div class="px-3">+ <div class="text-info font-weight-bold hi-sync-result-stat-number">+ {{ sync_result.updated_list|length }}+ </div>+ <div class="text-muted small text-uppercase hi-uppercase-label">Updated</div>+ </div>+ {% endif %}+ {% if sync_result.reconnected_list %}+ <div class="px-3">+ <div class="text-info font-weight-bold hi-sync-result-stat-number">+ {{ sync_result.reconnected_list|length }}+ </div>+ <div class="text-muted small text-uppercase hi-uppercase-label">Reconnected</div>+ </div>+ {% endif %}+ {% if sync_result.detached_list %}+ <div class="px-3">+ <div class="text-secondary font-weight-bold hi-sync-result-stat-number">+ {{ sync_result.detached_list|length }}+ </div>+ <div class="text-muted small text-uppercase hi-uppercase-label">Detached</div>+ </div>+ {% endif %}+ {% if sync_result.removed_list %}+ <div class="px-3">+ <div class="text-danger font-weight-bold hi-sync-result-stat-number">+ {{ sync_result.removed_list|length }}+ </div>+ <div class="text-muted small text-uppercase hi-uppercase-label">Removed</div>+ </div>+ {% endif %}+</div>diff --git a/src/hi/integrations/tests/test_sync_check.py b/src/hi/integrations/tests/test_sync_check.pyindex 5cfaf719..b4722594 100644--- a/src/hi/integrations/tests/test_sync_check.py+++ b/src/hi/integrations/tests/test_sync_check.py@@ -420,7 +420,6 @@ class TransitionAlarmTests(TestCase):# ---- alarm shape ----def test_fire_needs_sync_alarm_constructs_expected_alarm(self):- from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcecaptured = []@@ -444,12 +443,14 @@ class TransitionAlarmTests(TestCase):f'integrations.needs_sync.{self.INTEGRATION_ID}',)self.assertEqual(alarm.alarm_level, AlarmLevel.INFO)- # Drift alarms should persist until acknowledged, which is- # expressed in this codebase as ``Alarm.MAX_LIFETIME_SECS``- # (a sentinel "never expires" value — non-zero so- # ``end_datetime`` arithmetic remains uniform across all- # alarm types).- self.assertEqual(alarm.alarm_lifetime_secs, Alarm.MAX_LIFETIME_SECS)+ # Drift alarms suppress re-alerts for the configured nag+ # window after acknowledgement -- balances operator deferral+ # within their workday against ensuring they're reminded if+ # the issue still hasn't been addressed the next day.+ self.assertEqual(+ alarm.alarm_lifetime_secs,+ IntegrationSyncCheck.NAG_INTERVAL_SECS,+ )# Per-integration unique signature so two integrations# drifting yield two distinct alerts.self.assertIn(self.INTEGRATION_ID, alarm.signature)diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.pyindex cbdcd3e9..9742c472 100644--- a/src/hi/integrations/tests/test_views.py+++ b/src/hi/integrations/tests/test_views.py@@ -199,6 +199,11 @@ class _SyncTestSynchronizer:# when building the attribute edit context.capability = IntegrationCapability.CONNECT+ # Pre-sync view reads this to decide whether to surface a Preview+ # button. The stub doesn't implement the preview flow; False keeps+ # the existing pre-sync tests focused on the sync path only.+ supports_preview = False+def __init__(self, description='Test integration sync description.'):self._description = descriptionself.sync_called = Falsediff --git a/src/hi/services/frigate/enums.py b/src/hi/services/frigate/enums.pyindex 134bf167..32ec7be5 100644--- a/src/hi/services/frigate/enums.py+++ b/src/hi/services/frigate/enums.py@@ -2,6 +2,8 @@ from hi.apps.attribute.enums import AttributeValueTypefrom hi.integrations.enums import IntegrationAttributeType+from .constants import FrigateTimeouts+class FrigateAttributeType( IntegrationAttributeType ):@@ -31,3 +33,14 @@ class FrigateAttributeType( IntegrationAttributeType ):False,True,)+ POLLING_INTERVAL_SECS = (+ 'Polling Interval (seconds)',+ 'How often the monitor polls Frigate for new events. Lower '+ 'values are more responsive but increase API load on the '+ 'Frigate server.',+ AttributeValueType.INTEGER,+ [ 1, 86400 ], # 1 second to 24 hours+ True,+ True,+ str( FrigateTimeouts.POLLING_INTERVAL_SECS ),+ )diff --git a/src/hi/services/frigate/frigate_manager.py b/src/hi/services/frigate/frigate_manager.pyindex 9d2dc80d..fb31b280 100644--- a/src/hi/services/frigate/frigate_manager.py+++ b/src/hi/services/frigate/frigate_manager.py@@ -21,7 +21,7 @@ from hi.integrations.transient_models import (from hi.integrations.models import Integration-from .constants import FrigateApi+from .constants import FrigateApi, FrigateTimeoutsfrom .enums import FrigateAttributeTypefrom .frigate_client import FrigateClientfrom .frigate_client_factory import FrigateClientFactory@@ -55,6 +55,7 @@ class FrigateManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusself._change_listeners = set()self._frigate_client : Optional[ FrigateClient ] = Noneself._attribute_map : Dict[ FrigateAttributeType, IntegrationAttribute ] = {}+ self._polling_interval_secs = FrigateTimeouts.POLLING_INTERVAL_SECSself.add_api_health_status_provider( self )return@@ -97,6 +98,7 @@ class FrigateManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusself._attribute_map = self._build_attribute_map(integration_attributes = integration_attributes,)+ self._polling_interval_secs = self._read_polling_interval_secs()try:self._frigate_client = FrigateClientFactory.create_client(integration_attributes = integration_attributes,@@ -108,6 +110,34 @@ class FrigateManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusself.record_healthy( 'Reloaded' )return+ def _read_polling_interval_secs(self) -> int:+ """Read the configured polling interval. Form-level validation+ (``AttributeForm._clean_integer_value`` + the schema's+ ``value_range`` declaration) enforces type and range at save+ time, so any persisted value should already be a positive int+ within bounds. The defensive fallbacks here only fire on the+ edge cases form validation can't cover: the attribute row is+ missing (integration enabled but never saved) or the DB was+ manually edited / migrated from legacy data."""+ attribute = self._attribute_map.get(+ FrigateAttributeType.POLLING_INTERVAL_SECS,+ )+ if attribute is None or not attribute.value:+ return FrigateTimeouts.POLLING_INTERVAL_SECS+ try:+ return int( attribute.value )+ except (ValueError, TypeError):+ logger.warning(+ f'Malformed Frigate polling interval value "{attribute.value}" '+ f'(form validation should have caught this); falling '+ f'back to default {FrigateTimeouts.POLLING_INTERVAL_SECS}s'+ )+ return FrigateTimeouts.POLLING_INTERVAL_SECS++ @property+ def polling_interval_secs(self) -> int:+ return self._polling_interval_secs+@staticmethoddef _build_attribute_map(integration_attributes : List[ IntegrationAttribute ],diff --git a/src/hi/services/frigate/monitors.py b/src/hi/services/frigate/monitors.pyindex 06e70150..e62e976e 100644--- a/src/hi/services/frigate/monitors.py+++ b/src/hi/services/frigate/monitors.py@@ -52,26 +52,33 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):MONITOR_ID = 'hi.services.frigate.monitor'- POLLING_INTERVAL_SECS = FrigateTimeouts.POLLING_INTERVAL_SECS- API_TIMEOUT_SECS = FrigateTimeouts.API_TIMEOUT_SECS-# Force-close an open event whose age in HI's tracking set# exceeds this. Pulled into a class attribute so tests can shrink# the threshold to exercise the timeout path.MAX_OPEN_EVENT_AGE_SECS = FrigateTimeouts.MAX_OPEN_EVENT_AGE_SECSdef __init__(self):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.POLLING_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )self._poll_cursor_datetime : Optional[ datetime ] = Noneself._tracked_events : Dict[ str, TrackedFrigateEvent ] = {}self._was_initialized = Falsereturn+ def get_polling_interval_secs(self) -> int:+ # The framework calls this at sort time (before _initialize+ # has run ``await self.frigate_manager_async()`` and cached+ # the manager reference on this instance), and on every tick+ # after that. Use the manager's reloaded value when the+ # mixin's cached ``_frigate_manager`` attribute exists; fall+ # back to the static constant before then -- avoids+ # triggering the manager mixin's sync ``ensure_initialized``+ # from the async event-loop thread.+ if hasattr( self, '_frigate_manager' ):+ return self._frigate_manager.polling_interval_secs+ return FrigateTimeouts.POLLING_INTERVAL_SECS+def get_api_timeout(self) -> float:- return self.API_TIMEOUT_SECS+ return FrigateTimeouts.API_TIMEOUT_SECSdef alarm_ceiling(self):# Frigate is a security-camera dependency; treat outages as@@ -84,7 +91,6 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):provider_id = cls.MONITOR_ID,provider_name = 'Frigate Monitor',description = 'Frigate camera motion + object detection',- expected_heartbeat_interval_secs = cls.POLLING_INTERVAL_SECS,)async def _initialize(self):diff --git a/src/hi/services/hass/constants.py b/src/hi/services/hass/constants.pynew file mode 100644index 00000000..7922f39e--- /dev/null+++ b/src/hi/services/hass/constants.py@@ -0,0 +1,16 @@+class HassTimeouts:+ """+ Centralized timeout and interval constants for Home Assistant+ integration. Lives here so the manager / enums layer can reference+ these without importing from the monitor (which would invert the+ dependency direction).+ """++ # Default polling cadence. Used both as the manager's fallback and+ # as the schema-declared initial value for the user-editable+ # IntegrationAttribute, so the at-rest behavior matches what the+ # config page shows on a fresh install.+ POLLING_INTERVAL_SECS = 4++ # Shorter timeout appropriate for the polling cadence above.+ API_TIMEOUT_SECS = 10.0diff --git a/src/hi/services/hass/enums.py b/src/hi/services/hass/enums.pyindex f86bad9a..0c34b1e5 100644--- a/src/hi/services/hass/enums.py+++ b/src/hi/services/hass/enums.py@@ -1,6 +1,8 @@from hi.apps.attribute.enums import AttributeValueTypefrom hi.integrations.enums import IntegrationAttributeType+from .constants import HassTimeouts+class HassAttributeType( IntegrationAttributeType ):@@ -48,6 +50,17 @@ class HassAttributeType( IntegrationAttributeType ):'sensor\n''switch',)+ POLLING_INTERVAL_SECS = (+ 'Polling Interval (seconds)',+ 'How often the monitor polls Home Assistant for state changes. '+ 'Lower values are more responsive but increase API load on the '+ 'Home Assistant server.',+ AttributeValueType.INTEGER,+ [ 1, 86400 ], # 1 second to 24 hours+ True,+ True,+ str( HassTimeouts.POLLING_INTERVAL_SECS ),+ )class HassStateValue:diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.pyindex bbfda85c..20f9376d 100644--- a/src/hi/services/hass/hass_manager.py+++ b/src/hi/services/hass/hass_manager.py@@ -24,6 +24,7 @@ from hi.integrations.transient_models import ()from hi.integrations.models import Integration, IntegrationAttribute+from .constants import HassTimeoutsfrom .enums import HassAttributeTypefrom .hass_client import HassClientfrom .hass_client_factory import HassClientFactory@@ -46,6 +47,7 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProself._client_factory = HassClientFactory()self._change_listeners = set()+ self._polling_interval_secs = HassTimeouts.POLLING_INTERVAL_SECS# Selective-insert LRU cache (see update_latest_attrs_cache# for the policy). The lock guards both writes and reads@@ -111,6 +113,7 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusPro"""try:self._hass_attr_type_to_attribute = self._load_attributes()+ self._polling_interval_secs = self._read_polling_interval_secs()self._hass_client = self.create_hass_client( self._hass_attr_type_to_attribute )self.clear_caches()self._rebuild_entity_id_to_ha_state_id_map()@@ -186,15 +189,43 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProhass_integration = Integration.objects.get( integration_id = HassMetaData.integration_id )except Integration.DoesNotExist:raise IntegrationError( 'Home Assistant integration is not implemented.' )-+if not hass_integration.is_enabled:raise IntegrationDisabledError( 'Home Assistant integration is not enabled.' )-+integration_attributes = list(hass_integration.attributes.all())return self._build_hass_attr_type_to_attribute_map(integration_attributes=integration_attributes,enforce_requirements=True)++ def _read_polling_interval_secs(self) -> int:+ """Read the configured polling interval. Form-level validation+ (``AttributeForm._clean_integer_value`` + the schema's+ ``value_range`` declaration) enforces type and range at save+ time, so any persisted value should already be a positive int+ within bounds. The defensive fallbacks here only fire on the+ edge cases form validation can't cover: the attribute row is+ missing (integration enabled but never saved) or the DB was+ manually edited / migrated from legacy data."""+ attribute = self._hass_attr_type_to_attribute.get(+ HassAttributeType.POLLING_INTERVAL_SECS,+ )+ if attribute is None or not attribute.value:+ return HassTimeouts.POLLING_INTERVAL_SECS+ try:+ return int( attribute.value )+ except (ValueError, TypeError):+ logger.warning(+ f'Malformed HASS polling interval value "{attribute.value}" '+ f'(form validation should have caught this); falling '+ f'back to default {HassTimeouts.POLLING_INTERVAL_SECS}s'+ )+ return HassTimeouts.POLLING_INTERVAL_SECS++ @property+ def polling_interval_secs(self) -> int:+ return self._polling_interval_secsdef create_hass_client(self,diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.pyindex fe20c62f..5b37a1e4 100644--- a/src/hi/services/hass/monitors.py+++ b/src/hi/services/hass/monitors.py@@ -11,6 +11,7 @@ from hi.apps.sense.transient_models import SensorResponsefrom hi.apps.system.provider_info import ProviderInfofrom hi.testing.dev_overrides import DevOverrideManager+from .constants import HassTimeoutsfrom .hass_converter import HassConverterfrom .hass_mixins import HassMixin@@ -20,19 +21,27 @@ logger = logging.getLogger(__name__)class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):MONITOR_ID = 'hi.services.hass.monitor'- HASS_POLLING_INTERVAL_SECS = 4- HASS_API_TIMEOUT_SECS = 10.0 # Shorter timeout appropriate for 2-second pollingdef __init__( self ):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.HASS_POLLING_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )self._was_initialized = Falsereturn-++ def get_polling_interval_secs(self) -> int:+ # The framework calls this at sort time (before _initialize+ # has run ``await self.hass_manager_async()`` and cached the+ # manager reference on this instance), and on every tick+ # after that. Use the manager's reloaded value when the+ # mixin's cached ``_hass_manager`` attribute exists; fall+ # back to the static constant before then -- avoids+ # triggering the manager mixin's sync ``ensure_initialized``+ # from the async event-loop thread.+ if hasattr( self, '_hass_manager' ):+ return self._hass_manager.polling_interval_secs+ return HassTimeouts.POLLING_INTERVAL_SECS+def get_api_timeout(self) -> float:- return self.HASS_API_TIMEOUT_SECS+ return HassTimeouts.API_TIMEOUT_SECSdef alarm_ceiling(self):# HA outage in the background masks security and home-automation@@ -72,7 +81,6 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):provider_id = cls.MONITOR_ID,provider_name = 'Home Assistant Monitor',description = 'Home Assistant device state monitoring',- expected_heartbeat_interval_secs = cls.HASS_POLLING_INTERVAL_SECS,)async def do_work(self):diff --git a/src/hi/services/homebox/constants.py b/src/hi/services/homebox/constants.pynew file mode 100644index 00000000..4f15a885--- /dev/null+++ b/src/hi/services/homebox/constants.py@@ -0,0 +1,15 @@+class HbTimeouts:+ """+ Centralized timeout and interval constants for HomeBox integration.+ Lives here so the manager / enums layer can reference these+ without importing from the monitor (which would invert the+ dependency direction).+ """++ # Default polling cadence. Used both as the manager's fallback and+ # as the schema-declared initial value for the user-editable+ # IntegrationAttribute. HomeBox is inventory data -- changes are+ # infrequent and the default cadence is correspondingly slow.+ POLLING_INTERVAL_SECS = 300++ API_TIMEOUT_SECS = 20.0diff --git a/src/hi/services/homebox/enums.py b/src/hi/services/homebox/enums.pyindex 36d6ed6e..1f36cc1d 100644--- a/src/hi/services/homebox/enums.py+++ b/src/hi/services/homebox/enums.py@@ -2,6 +2,8 @@ from hi.apps.attribute.enums import AttributeValueTypefrom hi.integrations.enums import IntegrationAttributeType+from .constants import HbTimeouts+class HbAttributeType( IntegrationAttributeType ):@@ -45,3 +47,15 @@ class HbAttributeType( IntegrationAttributeType ):True,False,)+ POLLING_INTERVAL_SECS = (+ 'Polling Interval (seconds)',+ 'How often the monitor probes HomeBox for reachability. Lower '+ 'values produce a faster signal when the API goes down but '+ 'increase background API load; HomeBox is inventory data, so '+ 'longer intervals are usually appropriate.',+ AttributeValueType.INTEGER,+ [ 1, 86400 ], # 1 second to 24 hours+ True,+ True,+ str( HbTimeouts.POLLING_INTERVAL_SECS ),+ )diff --git a/src/hi/services/homebox/hb_manager.py b/src/hi/services/homebox/hb_manager.pyindex dc9afa79..72375592 100644--- a/src/hi/services/homebox/hb_manager.py+++ b/src/hi/services/homebox/hb_manager.py@@ -20,6 +20,7 @@ from hi.integrations.transient_models import (from hi.integrations.models import Integration, IntegrationAttributefrom hi.services.homebox.enums import HbAttributeType+from .constants import HbTimeoutsfrom .hb_client import HbClientfrom .hb_client_factory import HbClientFactoryfrom .hb_models import HbItem@@ -43,6 +44,7 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusself._hb_maintenances_list = list()self._change_listeners = set()+ self._polling_interval_secs = HbTimeouts.POLLING_INTERVAL_SECSself.add_api_health_status_provider(self)@@ -104,6 +106,7 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusdef _reload_implementation( self ):try:self._hb_attr_type_to_attribute = self._load_attributes()+ self._polling_interval_secs = self._read_polling_interval_secs()self._hb_client = self.create_hb_client( self._hb_attr_type_to_attribute )self.clear_caches()self.record_healthy('Reloaded')@@ -143,6 +146,34 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusenforce_requirements = True,)+ def _read_polling_interval_secs(self) -> int:+ """Read the configured polling interval. Form-level validation+ (``AttributeForm._clean_integer_value`` + the schema's+ ``value_range`` declaration) enforces type and range at save+ time, so any persisted value should already be a positive int+ within bounds. The defensive fallbacks here only fire on the+ edge cases form validation can't cover: the attribute row is+ missing (integration enabled but never saved) or the DB was+ manually edited / migrated from legacy data."""+ attribute = self._hb_attr_type_to_attribute.get(+ HbAttributeType.POLLING_INTERVAL_SECS,+ )+ if attribute is None or not attribute.value:+ return HbTimeouts.POLLING_INTERVAL_SECS+ try:+ return int( attribute.value )+ except (ValueError, TypeError):+ logger.warning(+ f'Malformed HomeBox polling interval value "{attribute.value}" '+ f'(form validation should have caught this); falling '+ f'back to default {HbTimeouts.POLLING_INTERVAL_SECS}s'+ )+ return HbTimeouts.POLLING_INTERVAL_SECS++ @property+ def polling_interval_secs(self) -> int:+ return self._polling_interval_secs+def create_hb_client(self,hb_attr_type_to_attribute : Dict[ HbAttributeType, IntegrationAttribute ] ) -> HbClient:diff --git a/src/hi/services/homebox/monitors.py b/src/hi/services/homebox/monitors.pyindex 8e634b69..454ba33d 100644--- a/src/hi/services/homebox/monitors.py+++ b/src/hi/services/homebox/monitors.py@@ -4,6 +4,7 @@ from hi.apps.alert.enums import AlarmLevelfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.system.provider_info import ProviderInfo+from .constants import HbTimeoutsfrom .hb_mixins import HomeBoxMixinlogger = logging.getLogger(__name__)@@ -18,19 +19,27 @@ class HomeBoxMonitor( PeriodicMonitor, HomeBoxMixin ):"""MONITOR_ID = 'hi.services.homebox.monitor'- HOMEBOX_POLLING_INTERVAL_SECS = 300- HOMEBOX_API_TIMEOUT_SECS = 20.0def __init__( self ):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.HOMEBOX_POLLING_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )self._was_initialized = Falsereturn+ def get_polling_interval_secs(self) -> int:+ # The framework calls this at sort time (before _initialize+ # has run ``await self.hb_manager_async()`` and cached the+ # manager reference on this instance), and on every tick+ # after that. Use the manager's reloaded value when the+ # mixin's cached ``_hb_manager`` attribute exists; fall back+ # to the static constant before then -- avoids triggering+ # the manager mixin's sync ``ensure_initialized`` from the+ # async event-loop thread.+ if hasattr( self, '_hb_manager' ):+ return self._hb_manager.polling_interval_secs+ return HbTimeouts.POLLING_INTERVAL_SECS+def get_api_timeout(self) -> float:- return self.HOMEBOX_API_TIMEOUT_SECS+ return HbTimeouts.API_TIMEOUT_SECSdef alarm_ceiling(self):# HomeBox tracks inventory data — degraded availability is@@ -60,7 +69,6 @@ class HomeBoxMonitor( PeriodicMonitor, HomeBoxMixin ):provider_id = cls.MONITOR_ID,provider_name = 'HomeBox Monitor',description = 'HomeBox integration health monitor',- expected_heartbeat_interval_secs = cls.HOMEBOX_POLLING_INTERVAL_SECS,)async def do_work(self):diff --git a/src/hi/services/homebox/tests/test_hb_manager.py b/src/hi/services/homebox/tests/test_hb_manager.pyindex 4e920eb5..aa802848 100644--- a/src/hi/services/homebox/tests/test_hb_manager.py+++ b/src/hi/services/homebox/tests/test_hb_manager.py@@ -34,6 +34,7 @@ class TestHomeBoxManagerAttributeMap(SimpleTestCase):self._mock_attribute(HbAttributeType.API_URL, 'https://homebox.local/api'),self._mock_attribute(HbAttributeType.API_USER, 'user'),self._mock_attribute(HbAttributeType.API_PASSWORD, 'secret'),+ self._mock_attribute(HbAttributeType.POLLING_INTERVAL_SECS, '300'),]result = self.manager._build_hb_attr_type_to_attribute_map(diff --git a/src/hi/services/zoneminder/enums.py b/src/hi/services/zoneminder/enums.pyindex 9e2e9ab7..769db9c1 100644--- a/src/hi/services/zoneminder/enums.py+++ b/src/hi/services/zoneminder/enums.py@@ -4,6 +4,8 @@ from hi.integrations.enums import IntegrationAttributeTypefrom hi.constants import TIMEZONE_NAME_LIST+from .constants import ZmTimeouts+class ZmAttributeType( IntegrationAttributeType ):@@ -57,3 +59,14 @@ class ZmAttributeType( IntegrationAttributeType ):False,True,)+ POLLING_INTERVAL_SECS = (+ 'Polling Interval (seconds)',+ 'How often the monitor polls ZoneMinder for new events. Lower '+ 'values are more responsive but increase API load on the '+ 'ZoneMinder server.',+ AttributeValueType.INTEGER,+ [ 1, 86400 ], # 1 second to 24 hours+ True,+ True,+ str( ZmTimeouts.POLLING_INTERVAL_SECS ),+ )diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex 1af4fd67..27b25940 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -40,10 +40,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )DEBUG_STATES_AND_MONITORS = Falsedef __init__( self ):- super().__init__(- id = self.MONITOR_ID,- interval_secs = self.ZONEMINDER_POLLING_INTERVAL_SECS,- )+ super().__init__( id = self.MONITOR_ID )self._fully_processed_event_ids = TTLCache( maxsize = 1000, ttl = 100000 )self._start_processed_event_ids = TTLCache( maxsize = 1000, ttl = 100000 )self._zm_tzname = None@@ -51,7 +48,20 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )self._poll_from_datetime = Noneself._was_initialized = Falsereturn-++ def get_polling_interval_secs(self) -> int:+ # The framework calls this at sort time (before _initialize+ # has run ``await self.zm_manager_async()`` and cached the+ # manager reference on this instance), and on every tick+ # after that. Use the manager's reloaded value when the+ # mixin's cached ``_zm_manager`` attribute exists; fall back+ # to the static constant before then -- avoids triggering+ # the manager mixin's sync ``ensure_initialized`` from the+ # async event-loop thread.+ if hasattr( self, '_zm_manager' ):+ return self._zm_manager.polling_interval_secs+ return self.ZONEMINDER_POLLING_INTERVAL_SECS+def get_api_timeout(self) -> float:return self.ZONEMINDER_API_TIMEOUT_SECS@@ -82,7 +92,6 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )provider_id = cls.MONITOR_ID,provider_name = 'ZoneMinder Monitor',description = 'ZoneMinder camera motion detection',- expected_heartbeat_interval_secs = cls.ZONEMINDER_POLLING_INTERVAL_SECS,)def refresh( self ):diff --git a/src/hi/services/zoneminder/tests/test_zm_manager.py b/src/hi/services/zoneminder/tests/test_zm_manager.pyindex a09578ee..76ff9a7a 100644--- a/src/hi/services/zoneminder/tests/test_zm_manager.py+++ b/src/hi/services/zoneminder/tests/test_zm_manager.py@@ -64,6 +64,7 @@ class ZoneMinderManagerConfigurationTest(TransactionTestCase):self.create_attribute(ZmAttributeType.API_USER, 'testuser')self.create_attribute(ZmAttributeType.API_PASSWORD, 'testpass')self.create_attribute(ZmAttributeType.TIMEZONE, 'America/Chicago')+ self.create_attribute(ZmAttributeType.POLLING_INTERVAL_SECS, '5')def tearDown(self):"""Clean up singleton instance for next test."""@@ -178,6 +179,12 @@ class ZoneMinderManagerThreadLocalTest(TransactionTestCase):value='America/Chicago',is_required=True)+ IntegrationAttribute.objects.create(+ integration=self.integration,+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.POLLING_INTERVAL_SECS}",+ value='5',+ is_required=True+ )def tearDown(self):"""Clean up singleton instance for next test."""@@ -265,6 +272,12 @@ class ZoneMinderManagerHealthStatusTest(TestCase):value='America/Chicago',is_required=True)+ IntegrationAttribute.objects.create(+ integration=self.integration,+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.POLLING_INTERVAL_SECS}",+ value='5',+ is_required=True+ )def tearDown(self):"""Clean up singleton instance."""@@ -320,6 +333,12 @@ class ZoneMinderManagerReloadTest(TransactionTestCase):value='America/Chicago',is_required=True)+ IntegrationAttribute.objects.create(+ integration=self.integration,+ integration_key_str=f"{ZmMetaData.integration_id}.{ZmAttributeType.POLLING_INTERVAL_SECS}",+ value='5',+ is_required=True+ )def tearDown(self):"""Clean up singleton instance."""diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex 6910407a..7aa3cf02 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -69,6 +69,7 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStaself._zm_monitor_timestamp = datetimeproxy.min()self._change_listeners = set()+ self._polling_interval_secs = ZmTimeouts.POLLING_INTERVAL_SECS# Add self as the API health status provider to aggregateself.add_api_health_status_provider(self)@@ -140,6 +141,7 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStadef _reload_implementation(self):try:self._zm_attr_type_to_attribute = self._load_attributes()+ self._polling_interval_secs = self._read_polling_interval_secs()# Clear all thread-local clients since configuration changedself._clear_thread_local_clients()self.clear_caches()@@ -198,7 +200,7 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStazm_integration = Integration.objects.get( integration_id = ZmMetaData.integration_id )except Integration.DoesNotExist:raise IntegrationError( 'ZoneMinder integration is not implemented.' )-+if not zm_integration.is_enabled:raise IntegrationDisabledError( 'ZoneMinder integration is not enabled.' )@@ -207,6 +209,34 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStaintegration_attributes=integration_attributes,enforce_requirements=True)++ def _read_polling_interval_secs(self) -> int:+ """Read the configured polling interval. Form-level validation+ (``AttributeForm._clean_integer_value`` + the schema's+ ``value_range`` declaration) enforces type and range at save+ time, so any persisted value should already be a positive int+ within bounds. The defensive fallbacks here only fire on the+ edge cases form validation can't cover: the attribute row is+ missing (integration enabled but never saved) or the DB was+ manually edited / migrated from legacy data."""+ attribute = self._zm_attr_type_to_attribute.get(+ ZmAttributeType.POLLING_INTERVAL_SECS,+ )+ if attribute is None or not attribute.value:+ return ZmTimeouts.POLLING_INTERVAL_SECS+ try:+ return int( attribute.value )+ except (ValueError, TypeError):+ logger.warning(+ f'Malformed ZM polling interval value "{attribute.value}" '+ f'(form validation should have caught this); falling '+ f'back to default {ZmTimeouts.POLLING_INTERVAL_SECS}s'+ )+ return ZmTimeouts.POLLING_INTERVAL_SECS++ @property+ def polling_interval_secs(self) -> int:+ return self._polling_interval_secsdef create_zm_client(self,diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex 68dd3463..69a28026 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -814,11 +814,15 @@ class Command(BaseCommand):# ----- NWS builders -----def _build_nws_sample(self, profile: SimProfile) -> int:- # 8-alert catalog spanning event types and severities. Every+ # 9-alert catalog spanning event types and severities. Every# alert is inactive by default so the operator toggles each on# individually to drive the active-alerts feed through one# event type at a time. Severity / certainty / urgency follow- # the canonical CAP pairings the NWS issues for each product.+ # the canonical CAP pairings the NWS issues for each product;+ # the trailing SPS entry intentionally carries severity+ # "Unknown" -- NWS routinely sends that on advisory products,+ # and exercising it surfaces the AlertSeverity.UNKNOWN styling+ # path that the other entries skip.area = 'Demo County, ZZ'self._add_nws_alert(profile,@@ -956,6 +960,24 @@ class Command(BaseCommand):'prolonged outdoor exertion.'),)+ self._add_nws_alert(+ profile,+ event_code = 'SPS',+ event_name = 'Special Weather Statement',+ severity = 'Unknown', certainty = 'Likely', urgency = 'Expected',+ category = 'met', area_desc = area,+ headline = 'Special Weather Statement for Demo County',+ description = (+ 'A line of showers and thunderstorms is moving through '+ 'Demo County. Brief heavy rainfall and gusty winds are '+ 'possible. No watches or warnings are in effect at this '+ 'time.'+ ),+ instruction = (+ 'Use caution if you must travel. Monitor later forecasts '+ 'for any updates.'+ ),+ )return profile.nws_sim_alerts.count()# ----- per-integration row builders -----@@ -1312,8 +1334,8 @@ class Command(BaseCommand):severity, certainty, urgency, category,area_desc, headline, description, instruction,status = 'Actual',- effective_offset_secs = -3600,- expires_offset_secs = 43200):+ effective_offset_secs = -900,+ expires_offset_secs = 900):NwsSimAlert.objects.create(sim_profile = profile,is_active = False,diff --git a/src/hi/simulator/weather_sources/nws/migrations/0002_alter_nwssimalert_effective_offset_secs_and_more.py b/src/hi/simulator/weather_sources/nws/migrations/0002_alter_nwssimalert_effective_offset_secs_and_more.pynew file mode 100644index 00000000..80b0726d--- /dev/null+++ b/src/hi/simulator/weather_sources/nws/migrations/0002_alter_nwssimalert_effective_offset_secs_and_more.py@@ -0,0 +1,29 @@+# Generated by Django 5.2.14 on 2026-05-29 19:53++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("nws", "0001_initial"),+ ]++ operations = [+ migrations.AlterField(+ model_name="nwssimalert",+ name="effective_offset_secs",+ field=models.IntegerField(+ default=-900,+ help_text='When the alert becomes effective, relative to "now" in seconds. Negative = in the past, positive = in the future.',+ ),+ ),+ migrations.AlterField(+ model_name="nwssimalert",+ name="expires_offset_secs",+ field=models.IntegerField(+ default=900,+ help_text='When the alert expires, relative to "now" in seconds.',+ ),+ ),+ ]diff --git a/src/hi/simulator/weather_sources/nws/models.py b/src/hi/simulator/weather_sources/nws/models.pyindex c440c83f..0a77cf2e 100644--- a/src/hi/simulator/weather_sources/nws/models.py+++ b/src/hi/simulator/weather_sources/nws/models.py@@ -69,14 +69,14 @@ class NwsSimAlert( models.Model ):instruction = models.TextField( blank = True, default = '' )area_desc = models.CharField( max_length = 255, default = 'Simulator Test Area' )effective_offset_secs = models.IntegerField(- default = -60,+ default = -900,help_text = ('When the alert becomes effective, relative to "now" in seconds. ''Negative = in the past, positive = in the future.'),)expires_offset_secs = models.IntegerField(- default = 3600,+ default = 900,help_text = 'When the alert expires, relative to "now" in seconds.',)created_datetime = models.DateTimeField( auto_now_add = True )diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex 48c86b03..f6fcf9e1 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -79,6 +79,7 @@--hi-panel-tile-target-size: 280px;--hi-panel-tile-max-size: 360px;--hi-panel-tile-large-min-size: 380px;+ --hi-panel-tile-small-min-size: 120px;--hi-panel-row-min-height: 56px;--hi-panel-row-target-height: 80px;--hi-panel-row-max-height: 128px;@@ -261,6 +262,20 @@ a.clickable-card:active {color: var(--on-tertiary-color);}+/* Bootstrap doesn't ship an .alert-tertiary variant, so the weather */+/* alerts banner falls back to no background when AlertSeverity.UNKNOWN */+/* maps the severity to "tertiary" (real NWS alerts routinely carry */+/* severity = "Unknown" on advisory products like Special Weather */+/* Statements). Filling the gap with neutral-grey tinted-bg styling */+/* matching the visual rhythm of the other alert variants -- soft */+/* enough to signal "no specific severity" rather than the heavier */+/* near-black ``bg-tertiary`` treatment. */+.alert-tertiary {+ color: #383d41;+ background-color: #e2e3e5;+ border-color: #d6d8db;+}+.bg-danger, .btn-error, .btn-danger {color: var(--on-error-color) !important;background-color: var(--error-color) !important;@@ -284,6 +299,36 @@ a.clickable-card:active {background-color: var(--muted-color) !important;}+/* Add-action button. Reusable treatment for "create new X" */+/* affordances. Dashed border + the edit-mode warm color: dashed is */+/* the long-standing UX convention for "this slot is awaiting */+/* content", and reusing the edit-mode dash color makes these buttons */+/* visually cluster with the dashed bar borders that mark edit-mode */+/* chrome. Differentiates from primary (nav), secondary (active */+/* state), and tertiary (settings) so an "add" stands out at a */+/* glance. */+.btn-add {+ color: var(--edit-mode-dash-color) !important;+ /* Light translucent warm fill rather than fully transparent. The */+ /* edit-mode bar background is itself a warm tone, so a transparent */+ /* dashed button would be warm-on-warm with minimal contrast. The */+ /* translucent chip gives the button presence as a discrete slot */+ /* while preserving the dashed-create vocabulary. */+ background-color: rgba(169, 74, 50, 0.08) !important;+ border: 2px dashed var(--edit-mode-dash-color) !important;+}+.btn-add:hover,+.btn-add:focus,+.btn-add:active,+.btn-add.active {+ color: var(--edit-mode-dash-color) !important;+ background-color: rgba(169, 74, 50, 0.18) !important;+ border-color: var(--edit-mode-border-color) !important;+}+.btn-add:focus {+ box-shadow: 0 0 0 0.2rem rgba(169, 74, 50, 0.25) !important;+}+/* Outline Button Overrides */.btn-outline-primary {color: var(--primary-color) !important;@@ -402,6 +447,101 @@ a.clickable-card:active {max-height: 2rem;width: auto;}++/* Top/bottom button bars. The right (and top-center logo) groups */+/* reserve their content width so the fixed app-nav controls are never */+/* pushed off-screen by a long list of user-defined view buttons. The */+/* left group takes the remaining width and scrolls horizontally on */+/* overflow. */+.hi-button-bar {+ flex-wrap: nowrap;+ align-items: center;+ gap: 0.5rem;+}+.hi-button-bar-fixed,+.hi-button-bar-center {+ flex: 0 0 auto;+}+.hi-button-bar-flex {+ flex: 1 1 auto;+ /* Override flexbox's default min-width:auto so this group can */+ /* actually shrink below its children's intrinsic widths. */+ min-width: 0;+ overflow-x: auto;+ scrollbar-width: thin;+}+.hi-button-bar-flex > * {+ flex-shrink: 0;+}++/* Edit-mode sidebar tab strip. Three tabs (Items / View / Space) act */+/* as visual chrome over the existing per-template side views: each */+/* tab is just an antinode link to a different side-panel URL. The */+/* "active" class is hardcoded into the loaded template, so there's */+/* no client-side tab state. */+.hi-edit-sidebar-tabs {+ display: flex;+ align-items: stretch;+ border-bottom: 1px solid var(--line-color);+ /* Keep top-level domain switcher visible while the pane content */+ /* scrolls underneath. Bg matches whichever wrapper bg the sidebar */+ /* is showing (white in items mode, warm in detail modes) so the */+ /* scrolled content can't bleed through. */+ position: sticky;+ top: 0;+ z-index: 20;+ background-color: var(--edit-mode-primary-bg);+}+.hi-edit-sidebar-tab {+ flex: 1 1 0;+ text-align: center;+ padding: 0.5rem 0.25rem;+ font-size: 1.15rem;+ font-weight: 600;+ color: var(--primary-color);+ text-decoration: none;+ border-bottom: 3px solid transparent;+ margin-bottom: -1px;+}+.hi-edit-sidebar-tab:hover {+ text-decoration: none;+ background-color: rgba(23, 112, 114, 0.05);+}+.hi-edit-sidebar-tab.active {+ color: var(--edit-mode-dash-color);+ border-bottom-color: var(--edit-mode-dash-color);+ background-color: var(--edit-mode-tertiary-bg);+}+.hi-edit-sidebar-tab.disabled {+ color: #aaa;+ pointer-events: none;+ cursor: default;+}+.hi-edit-sidebar-content {+ padding: 0.5rem;+}++/* Items-list mode: the entity rows carry status-based background */+/* shading (in-view / unused) and integration logos authored on */+/* white, so the edit-mode sidebar tint is overridden to white when */+/* the items list template is loaded. ``:has()`` lets the parent */+/* react to which child template was rendered without JS coordination, */+/* so the white extends edge-to-edge -- no scroll edge cases. */+.hi-screen[hi-edit="True"] #hi-side-content:has(.entity-picker-container) {+ background: var(--white);+}++/* Touch-target utility. Apply alongside any visual treatment */+/* (typically Bootstrap ``small``/``text-muted``) to give a small */+/* text affordance the iOS-HIG 44px tap floor without changing how */+/* it looks. Use anywhere a glyph-light link or icon needs to remain */+/* finger-friendly on a wall-mounted tablet. */+.hi-tap-target {+ display: inline-flex;+ align-items: center;+ min-height: 44px;+ padding: 0.5rem 0.75rem;+}.hi-side {padding-left: 0;padding-right: 0;@@ -409,8 +549,6 @@ a.clickable-card:active {#hi-side-content {height: calc(100vh - var(--top-buttons-height) - var(--bottom-buttons-height));display: flex;- padding-left: 0.5rem;- padding-right: 0.5rem;flex-direction: column;overflow-y: auto;}@@ -647,6 +785,56 @@ input[type="password"],color: var(--black) !important;background-color: #f8f8f8 !important;}++/* Location switcher dropdown items: touch-friendly heights and a */+/* visible current-space marker (check icon + bold) so the user can */+/* see which space they're on at a glance. */+.dropdown-item.plain {+ padding: 0.6rem 1rem;+ min-height: 44px;+ display: flex;+ align-items: center;+}+.dropdown-item.plain.active {+ background-color: transparent;+ color: var(--primary-color);+ font-weight: 600;+}+.dropdown-item.plain.active:hover,+.dropdown-item.plain.active:focus {+ background-color: rgba(23, 112, 114, 0.05);+ color: var(--primary-color);+}++/* ADD NEW SPACE: same btn-add vocabulary as other "add" affordances */+/* (top-bar ADD VIEW / ADD COLLECTION, entity-picker ADD NEW ITEM), */+/* but at a lower visual weight appropriate to its dropdown context — */+/* this is a secondary action accessed from a navigation menu, not a */+/* primary CTA. ``box-sizing: border-box`` + a horizontal margin keep */+/* the chip inset from the menu edges without pushing past the menu's */+/* right border. */+.dropdown-item-add {+ box-sizing: border-box;+ width: calc(100% - 1rem);+ margin: 0.25rem 0.5rem;+ padding: 0.35rem 0.75rem !important;+ min-height: 36px;+ display: flex;+ align-items: center;+ justify-content: center;+ border: 1px dashed var(--edit-mode-dash-color);+ border-radius: 0.25rem;+ color: var(--edit-mode-dash-color) !important;+ background-color: rgba(169, 74, 50, 0.06) !important;+ font-size: 0.9rem;+ font-weight: 500;+}+.dropdown-item-add:hover,+.dropdown-item-add:focus {+ background-color: rgba(169, 74, 50, 0.16) !important;+ border-color: var(--edit-mode-border-color) !important;+ color: var(--edit-mode-dash-color) !important;+}.hi-custom-select .input-group-text {height: calc(1.5em + 0.75rem + 2px);line-height: 1.5;@@ -693,6 +881,15 @@ svg .highlighted {g.hi-icon {pointer-events: all;+ touch-action: manipulation;+ /* Suppress iOS Safari's callout (Copy/Define popup) and+ text-selection behaviors on the 750ms touch-hold the+ long-press gesture uses. ``touch-action: manipulation``+ governs gesture interpretation but not callouts/selection. */+ -webkit-touch-callout: none;+ -webkit-user-select: none;+ -moz-user-select: none;+ user-select: none;}/* Hide background rectangles used for click targets */@@ -1529,25 +1726,21 @@ g[hover] {}}-/* Entity Picker Styles */-.entity-picker-container {- /* Let the container flow naturally with sidebar scroll */-}--.entity-picker-panel {- background: var(--white);- border: 1px solid var(--line-color);- border-radius: 8px;- /* Remove fixed height - let it grow with content */-}+/* Entity Picker Styles. The container/panel wrappers are structural */+/* only (they exist for ``:has()`` detection and for template parity */+/* with downstream JS that may key off them). Sidebar background and */+/* gutters live one layer up: ``#hi-side-content`` paints the white, */+/* ``.hi-edit-sidebar-content`` owns the padding. Nothing here. */.entity-picker-header {background: var(--muted-bg-light);border-bottom: 1px solid var(--line-color);padding: 0.5rem;- /* Make sticky within the sidebar scroll */+ /* Stick below the sidebar tabs strip when scrolling. ``top`` is */+ /* an approximation of the tabs' rendered height; both elements' */+ /* z-index lets the tabs sit above this if values drift. */position: sticky;- top: 0;+ top: 2.5rem;z-index: 10;}@@ -1589,8 +1782,8 @@ g[hover] {}.entity-picker-items {- /* Remove inner scroll - let sidebar handle scrolling */- padding: 0 5px 5px;+ /* No styling -- gutter is owned by .hi-edit-sidebar-content one */+ /* layer up. Kept as a class hook for JS / template parity. */}.entity-group-section {@@ -1765,6 +1958,20 @@ g[hover] {auto-fit, minmax(var(--hi-panel-tile-large-min-size), 1fr));}+/* GRID_SMALL halves the minimum tile size so roughly twice as many+ * columns fit in the same container. Used for collections where+ * many simple panels (binary status, single value) benefit from a+ * denser layout. Cards also get a halved min-height so the aspect+ * ratio stays comparable to GRID rather than going tall-and-narrow.+ */+.collection-tile-grid--small {+ grid-template-columns: repeat(+ auto-fit, minmax(var(--hi-panel-tile-small-min-size), 1fr)+ );+}+.collection-tile-grid--small .entity-card--tile {+ min-height: var(--hi-panel-tile-small-min-size);+}.collection-default {grid-template-columns: repeat(auto-fit, minmax(var(--hi-panel-default-tile-min-size), 1fr)@@ -1994,6 +2201,19 @@ g[hover] {margin-bottom: 0.25rem;line-height: 1.2;}+/* Marker for fields whose value differs from the server-rendered+ initial value. Paired with ``button[disabled]`` on the form's+ UPDATE button to make "unsaved changes" obvious at the field+ level as well as the action level. Set on the label by the+ ``Hi.updateFormDirtyState`` helper via ``oninput`` on the form. */+.sidebar-form-label.dirty::after {+ content: " \25CF"; /* small filled circle */+ /* Reuse the edit-mode emphasis color (dark brick red) so the+ indicator contrasts strongly against the peach+ ``--edit-mode-primary-bg`` panel and tracks any future+ edit-mode palette retheme. */+ color: var(--edit-mode-dash-color);+}.sidebar-form-input {width: 100%;diff --git a/src/hi/static/css/stream-browser.css b/src/hi/static/css/stream-browser.cssindex db367f3e..b37c6496 100644--- a/src/hi/static/css/stream-browser.css+++ b/src/hi/static/css/stream-browser.css@@ -140,6 +140,7 @@overflow: hidden;box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);background-color: var(--black);+ min-height: 400px;}.video-container img {diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.jsindex a0ec03b7..8042defe 100644--- a/src/hi/static/js/antinode.js+++ b/src/hi/static/js/antinode.js@@ -663,6 +663,7 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {//if ( 'html' in json ) {if ( $target ) {+ beforeContentRemoval( $target );if ( $mode == 'replace' ) {$target.replaceWith( json['html'] );}@@ -680,6 +681,7 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {if ( 'replace' in json ) {for ( let htmlId in json['replace'] ) {let targetObj = $("#"+htmlId);+ beforeContentRemoval( targetObj );targetObj.replaceWith( json['replace'][htmlId] ).show();handleNewContentAdded( targetObj );}@@ -691,6 +693,7 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {if ( 'insert' in json ) {for ( let htmlId in json['insert'] ) {let targetObj = $("#"+htmlId);+ beforeContentRemoval( targetObj );targetObj.empty();targetObj.html( json['insert'][htmlId] ).show();handleNewContentAdded( targetObj );@@ -787,9 +790,14 @@ function handleSetAttributes( attributesMap ) {targetObj.attr( attrName, attrValue );handleNewContentAdded( targetObj );}- } else {- console.warn(`setAttributes: No elements found for selector '${selector}'`);- }+ }++ // Zero-match is a legitimate outcome for callers that+ // emit a compound selector pair (e.g., paired+ // ``[data-status]`` / ``[data-svg-style]`` selectors+ // where one side intentionally targets a class of+ // element the current entity does not render).+} catch (e) {console.error(`setAttributes: Invalid selector '${selector}': ${e.message}`);// Continue processing other selectors instead of failing completelydiff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.jsindex 5588e643..80ac7981 100644--- a/src/hi/static/js/main.js+++ b/src/hi/static/js/main.js@@ -50,6 +50,9 @@submitForm: function( formElement ) {return _submitForm( formElement );},+ updateFormDirtyState: function( formElement ) {+ return _updateFormDirtyState( formElement );+ },togglePasswordField: function( toggleCheckbox ) {return _togglePasswordField( toggleCheckbox );},@@ -227,7 +230,53 @@if ( Hi.DEBUG ) { console.debug( 'Submitting form:', formElement, form ); }$(form).submit();}-++ function _updateFormDirtyState( formElement ) {+ // Compares each field's current value to its server-rendered+ // initial (``defaultValue`` / ``defaultChecked`` /+ // ``defaultSelected``), toggles ``.dirty`` on the field's+ // label, and enables/disables the form's submit button(s).+ // ``defaultValue`` etc. survive value mutations but are reset+ // by any re-render of the form HTML, so a successful save's+ // returned markup naturally re-baselines without explicit+ // state-reset code.+ let anyDirty = false;+ const fields = formElement.querySelectorAll( 'input, select, textarea' );+ fields.forEach( function( field ) {+ // Skip hidden CSRF tokens, submit buttons, and unnamed+ // controls that aren't part of the form's data payload.+ if ( ! field.name ) { return; }+ if ( field.type === 'hidden' ) { return; }+ if ( field.type === 'submit' || field.type === 'button' ) { return; }+ let fieldDirty = false;+ if ( field.type === 'checkbox' || field.type === 'radio' ) {+ fieldDirty = ( field.checked !== field.defaultChecked );+ } else if ( field.tagName === 'SELECT' ) {+ for ( const option of field.options ) {+ if ( option.selected !== option.defaultSelected ) {+ fieldDirty = true;+ break;+ }+ }+ } else {+ fieldDirty = ( field.value !== field.defaultValue );+ }+ if ( field.id ) {+ const label = formElement.querySelector(+ 'label[for="' + field.id + '"]'+ );+ if ( label ) {+ label.classList.toggle( 'dirty', fieldDirty );+ }+ }+ if ( fieldDirty ) { anyDirty = true; }+ });+ const submitButtons = formElement.querySelectorAll( 'button[type="submit"]' );+ submitButtons.forEach( function( button ) {+ button.disabled = ! anyDirty;+ });+ }+function _togglePasswordField( toggleCheckbox ) {let passwordField = $(toggleCheckbox).closest(Hi.FORM_FIELD_CONTAINER_SELECTOR).find('input[type="password"], input[type="text"]');diff --git a/src/hi/static/js/svg-entity-edit.js b/src/hi/static/js/svg-entity-edit.jsindex 313fbf79..19da76e0 100644--- a/src/hi/static/js/svg-entity-edit.js+++ b/src/hi/static/js/svg-entity-edit.js@@ -110,6 +110,23 @@}return false;},+ handleLongPress: function( event ) {+ /* Long-press on an entity icon is the gesture-based escape+ hatch out of a view-type-specific tap behavior (e.g.,+ AUTOMATION's one-click control). The server decides what+ to surface; we just signal that the gesture happened. */+ if ( Hi.isEditMode ) { return false; }+ var group = $( event.target ).closest( 'g' );+ if ( group.length === 0 ) { return false; }+ if ( group.attr( Hi.DATA_TYPE_ATTR ) !== Hi.DATA_TYPE_ICON_VALUE ) {+ return false;+ }+ var svgItemId = group.attr( 'id' );+ if ( ! svgItemId ) { return false; }+ AN.get( Hi.API_LOCATION_ITEM_STATUS_URL + '/' + svgItemId+ + '?long_press=1' );+ return true;+ },handleKeyDown: function( event ) {if ( ! Hi.isEditMode ) { return false; }return Hi.SvgIconCore.handleKeyDown( event );@@ -203,6 +220,9 @@}return false;},+ handleLongPress: function( event ) {+ return false;+ },handleKeyDown: function( event ) {if ( ! Hi.isEditMode ) { return false; }return Hi.SvgPathCore.handleKeyDown( event );@@ -300,6 +320,9 @@}return false;},+ handleLongPress: function( event ) {+ return false;+ },handleKeyDown: function( event ) {return Hi.SvgPanZoomCore.handleKeyDown( event );},diff --git a/src/hi/static/js/svg-entity-event-listeners.js b/src/hi/static/js/svg-entity-event-listeners.jsindex 05f77a3c..d0dc138c 100644--- a/src/hi/static/js/svg-entity-event-listeners.js+++ b/src/hi/static/js/svg-entity-event-listeners.js@@ -19,12 +19,22 @@const POTENTIAL_CLICK_POSITION_DELTA_THRESHOLD = 5;const POTENTIAL_CLICK_DELAY_MS = 50;+ // Synthetic long-press gesture. The listener layer manages+ // timing and movement cancellation, then dispatches to the same+ // icon -> path -> location chain as the other pointer events. It+ // has no opinion about what should happen on a long-press -- each+ // consuming module decides for itself.+ const LONG_PRESS_DURATION_MS = 750;+ const LONG_PRESS_MOVE_THRESHOLD_PIXELS = 5;+const activePointers = new Map();const gLastMoveEventTimes = new Map();let gCurrentSingleEvent = null;let gCurrentDoubleEvent = null;// Tracks pointer down/up events to generate synthetic click events when real clicks don't fire (e.g., MacBook trackpads on SVG elements)let gPotentialClickState = null;+ let gLongPressState = null;+ let gSuppressNextClick = false;class SinglePointerEvent {constructor( startEvent ) {@@ -159,6 +169,71 @@}}+ function startLongPressTracking( event ) {+ // Defensive: clear any prior state whose pointerup never+ // arrived (e.g., a missed event from ``setPointerCapture``+ // edge cases) so its ``setTimeout`` handle isn't leaked.+ cancelLongPress();+ gLongPressState = {+ pointerId: event.pointerId,+ startEvent: event,+ startPosition: { x: event.clientX, y: event.clientY },+ triggerTimer: setTimeout( function() {+ fireLongPress();+ }, LONG_PRESS_DURATION_MS ),+ };+ }++ function cancelLongPress() {+ if ( ! gLongPressState ) { return; }+ clearTimeout( gLongPressState.triggerTimer );+ gLongPressState = null;+ }++ function checkLongPressMove( event ) {+ if ( ! gLongPressState ) { return; }+ if ( event.pointerId !== gLongPressState.pointerId ) { return; }+ const dx = Math.abs( event.clientX - gLongPressState.startPosition.x );+ const dy = Math.abs( event.clientY - gLongPressState.startPosition.y );+ if ( Math.max( dx, dy ) > LONG_PRESS_MOVE_THRESHOLD_PIXELS ) {+ cancelLongPress();+ }+ }++ function fireLongPress() {+ if ( ! gLongPressState ) { return; }+ const startEvent = gLongPressState.startEvent;+ gLongPressState = null;+ // Side effects (suppress the trailing click, tactile feedback)+ // only apply when a consumer actually claimed the gesture.+ // Without this gate, edit-mode interactions silently lose their+ // trailing click to ``gSuppressNextClick`` even though no+ // consumer ran (edit mode's icon handler returns ``false``).+ const handled = dispatchLongPress( startEvent );+ if ( handled ) {+ gSuppressNextClick = true;+ // Stale-flag safety: if the expected trailing click never+ // arrives (pointer leaves the document, scroll preempt,+ // etc.) auto-clear so we don't silently eat the next+ // unrelated click many seconds later.+ setTimeout( function() { gSuppressNextClick = false; }, 1000 );+ if ( navigator.vibrate ) {+ navigator.vibrate( 50 );+ }+ }+ }++ function dispatchLongPress( startEvent ) {+ let handled = Hi.edit.icon.handleLongPress( startEvent );+ if ( ! handled ) {+ handled = Hi.edit.path.handleLongPress( startEvent );+ }+ if ( ! handled ) {+ handled = Hi.location.handleLongPress( startEvent );+ }+ return handled;+ }+function handlePointerDownEvent( event ) {if ( shouldIgnoreEvent( event )) { return; }@@ -169,6 +244,10 @@// Start potential click tracking for single pointer eventsif (currentActivePointersSize === 1) {startPotentialClickTracking(event);+ startLongPressTracking(event);+ } else {+ // Multi-touch is for pan/zoom/rotate; long-press is single-finger only.+ cancelLongPress();}if (( initialActivePointersSize === 0 ) && ( currentActivePointersSize === 1 )) {@@ -199,7 +278,12 @@if ( ! lastPointer ) {return;}-++ // Long-press cancellation runs before the move-throttle so even+ // throttled events count toward the cumulative-displacement+ // threshold (cheap check, no DOM work).+ checkLongPressMove( event );+// Guarding against event floods and performance issues.let now = Date.now();if ( gLastMoveEventTimes.has( event.pointerId )) {@@ -250,6 +334,13 @@gLastMoveEventTimes.delete( event.pointerId );const currentActivePointersSize = activePointers.size;+ // Released before the long-press trigger fired -- treat as a+ // normal click; cancellation is a no-op if the timer already+ // fired and cleared the state.+ if ( gLongPressState && gLongPressState.pointerId === event.pointerId ) {+ cancelLongPress();+ }+// Reset potential click state when switching to multi-touchif (currentActivePointersSize > 1) {gPotentialClickState = null;@@ -286,6 +377,11 @@}function handlePointerCancelEvent( event ) {+ // Browser-initiated cancellation (scroll start, gesture+ // preempt) may target a pointer ID that ``handlePointerUp``'s+ // active-pointer check rejects, leaving a pending long-press+ // timer alive. Kill it unconditionally before falling through.+ cancelLongPress();// Treat the same as an "up" event for now.handlePointerUpEvent(event);}@@ -406,7 +502,18 @@$(document).on('click', Hi.LOCATION_VIEW_AREA_SELECTOR, function( event ) {if ( shouldIgnoreEvent( event )) { return; }-++ // Long-press already dispatched the status request; the+ // browser's trailing click on pointer-up must not also fire+ // the default action (which in AUTOMATION view would be the+ // one-click control).+ if ( gSuppressNextClick ) {+ gSuppressNextClick = false;+ event.preventDefault();+ event.stopImmediatePropagation();+ return;+ }+// Cancel synthetic click if real click event firesif (gPotentialClickState?.waitingForClick) {gPotentialClickState = null;diff --git a/src/hi/static/js/video-timeline.js b/src/hi/static/js/video-timeline.jsindex 2892e037..3d717b18 100644--- a/src/hi/static/js/video-timeline.js+++ b/src/hi/static/js/video-timeline.js@@ -216,6 +216,16 @@PLACEHOLDER_CLASS: 'video-load-error-placeholder',REGISTERED_FLAG: 'videoErrorHandlerRegistered',+ // First-frame watchdog. Some upstream failures (ZM camera+ // unreachable, HA endpoint hung) leave the TCP connection open+ // with HTTP headers returned but no payload, so the browser+ // fires neither ``load`` nor ``error`` and the <img> sits+ // permanently in a "still loading" state. After this many ms+ // with no first frame we synthesize an error so the placeholder+ // surfaces. A later real ``load`` heals it via ``_handleLoad``.+ FIRST_LOAD_TIMEOUT_MS: 10000,+ firstLoadTimers: new Map(),+// Heading + subtitle per marker. Mirrors the server-rendered// ``.video-placeholder`` markup for the no-source case, so the// failed-to-load and no-data cases look visually identical.@@ -247,11 +257,44 @@element.dataset[ this.REGISTERED_FLAG ] = '1';const handler = this;element.addEventListener( 'error', function() {+ handler._clearFirstLoadWatchdog( element );handler._handleError( element );});element.addEventListener( 'load', function() {+ handler._clearFirstLoadWatchdog( element );handler._handleLoad( element );});+ this._startFirstLoadWatchdog( element );+ },++ _startFirstLoadWatchdog: function( element ) {+ if ( ! element.src || element.src.startsWith( 'data:' )) return;+ // Image may have settled before our listeners attached+ // (initial server render, fast cache hit). ``complete`` is+ // true on both success and failure; ``naturalWidth`` of 0+ // distinguishes the failed case.+ if ( element.complete ) {+ if ( element.naturalWidth === 0 ) this._handleError( element );+ return;+ }+ const handler = this;+ const timer = setTimeout( function() {+ handler.firstLoadTimers.delete( element );+ if ( element.src+ && ! element.src.startsWith( 'data:' )+ && element.naturalWidth === 0 ) {+ handler._handleError( element );+ }+ }, this.FIRST_LOAD_TIMEOUT_MS );+ this.firstLoadTimers.set( element, timer );+ },++ _clearFirstLoadWatchdog: function( element ) {+ const timer = this.firstLoadTimers.get( element );+ if ( timer !== undefined ) {+ clearTimeout( timer );+ this.firstLoadTimers.delete( element );+ }},_handleError: function( element ) {diff --git a/src/hi/static/state_panels/camera/camera.css b/src/hi/static/state_panels/camera/camera.cssindex 4e9b4b21..7e6cc0c5 100644--- a/src/hi/static/state_panels/camera/camera.css+++ b/src/hi/static/state_panels/camera/camera.css@@ -46,6 +46,10 @@.hi-state-panel-camera .stream .video-container {width: 100%;height: 100%;+ /* Override the main video pane's 400px collapse-guard — panels */+ /* size their stream box from their own context (tile cell or */+ /* modal stream rule below), not from the container itself. */+ min-height: 0;}.hi-state-panel-camera .stream .video-container img,.hi-state-panel-camera .stream img.img-fluid {@@ -71,6 +75,12 @@* the base rule keeps each image whole inside its cell. */.hi-state-panel-camera--modal .stream {margin-bottom: 16px;+ /* Collapse-guard for the EntityStatus modal: the image is */+ /* ``height: auto`` here, so a hung stream with no natural */+ /* dimensions would otherwise drop the box to 0. Sized smaller */+ /* than the main video pane's 400px since the modal frames a */+ /* single camera in a tighter chrome. */+ min-height: 200px;}.hi-state-panel-camera--modal .stream .video-container img,.hi-state-panel-camera--modal .stream img.img-fluid {diff --git a/src/hi/templates/panes/bottom_buttons.html b/src/hi/templates/panes/bottom_buttons.htmlindex 3f24b901..d7710fa7 100644--- a/src/hi/templates/panes/bottom_buttons.html+++ b/src/hi/templates/panes/bottom_buttons.html@@ -1,8 +1,17 @@{% load icons %}<div class="p-1">- <div class="d-flex justify-content-between">+ <div class="d-flex justify-content-between hi-button-bar">+ {% if request.view_parameters.is_editing %}+ <div class="hi-button-bar-fixed px-1">+ <a href="{% url 'collection_add' %}"+ class="btn btn-add btn-control" role="button"+ data-async="modal" >+ {% icon "plus" size="sm" css_class="hi-icon-left" %}ADD COLLECTION+ </a>+ </div>+ {% endif %}{% include "collection/panes/collection_buttons.html" %}- <div class="d-flex justify-content-end">+ <div class="d-flex justify-content-end hi-button-bar-fixed">{% if request.view_parameters.is_editing %}<div class="mx-1 d-flex align-items-center"><label class="mb-0 mx-1" style="font-size: 0.85rem;"><b>Snap:</b></label>diff --git a/src/hi/templates/panes/top_buttons.html b/src/hi/templates/panes/top_buttons.htmlindex 83cdce46..f19cd9b3 100644--- a/src/hi/templates/panes/top_buttons.html+++ b/src/hi/templates/panes/top_buttons.html@@ -1,12 +1,21 @@{% load static %}{% load icons %}<div class="p-1">- <div class="d-flex justify-content-between">+ <div class="d-flex justify-content-between hi-button-bar">+ {% if request.view_parameters.is_editing %}+ <div class="hi-button-bar-fixed px-1">+ <a href="{% url 'location_edit_location_view_add' %}"+ class="btn btn-add btn-control" role="button"+ data-async="modal" >+ {% icon "plus" size="sm" css_class="hi-icon-left" %}ADD VIEW+ </a>+ </div>+ {% endif %}{% include "location/panes/location_view_buttons.html" %}- <div>+ <div class="hi-button-bar-center"><img src="{% static 'img/hi-logo-149x64.png' %}" alt="Home Information Logo"></div>- <div class="d-flex justify-content-end">+ <div class="d-flex justify-content-end hi-button-bar-fixed">{% if request.view_parameters.location %}<div class="px-1">{% if request.view_parameters.is_editing %}@@ -14,13 +23,13 @@href="{% url 'location_edit_mode' location_id=request.view_parameters.location.id %}"data-async="true" >{% icon "edit" size="sm" css_class="" %}- {{ request.view_parameters.location.name }}+ {{ request.view_parameters.location.name|truncatechars:18 }}</a>{% else %}<a class="btn btn-primary btn-control" role="button"href="{% url 'location_edit_location_edit' location_id=request.view_parameters.location.id %}"data-async="true" >- {% icon "info-circle" size="sm" css_class="hi-icon-left" %}{{ request.view_parameters.location.name }}+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}{{ request.view_parameters.location.name|truncatechars:18 }}</a>{% endif %}</div>