Home Information - Your home, your data, organized.
Python
Add NEQ and IN operators to EventClauseOperator (#350)
Tony C2618a172a50a
diff --git a/src/hi/apps/event/edit/forms.py b/src/hi/apps/event/edit/forms.pyindex 71abf8d4..9fc73a73 100644--- a/src/hi/apps/event/edit/forms.py+++ b/src/hi/apps/event/edit/forms.py@@ -1,3 +1,4 @@+import jsonimport loggingfrom django import forms@@ -69,16 +70,34 @@ class EventClauseForm( forms.ModelForm, EntityStateSelectModelFormMixin ):)self.fields['entity_state'].widget.attrs.update({ 'class': 'custom-select' })self.fields['value'].widget.attrs.update({ 'class': 'custom-select' })- # When the operator changes, swap the value widget to a numeric- # input (for non-EQ) so threshold clauses are editable on the- # spot. EQ leaves whatever widget the entity_state-driven swap- # rendered (Select for discrete states, text input otherwise).+ # When the saved operator is IN and the state has discrete+ # choices, render value as SelectMultiple so the persisted+ # selection round-trips on edit-page load.+ operator_str = self[ 'value_operator_str' ].value() or ''+ if ( operator_str == str( EventClauseOperator.IN )+ and entity_state and entity_state.choices() ):+ self.fields['value'].widget = forms.SelectMultiple(+ choices = entity_state.choices(),+ )+ self.fields['value'].widget.attrs['class'] = 'custom-select'+ if self.instance and self.instance.pk:+ self.initial['value'] = sorted(+ self.instance.in_value_members(),+ )value_field_id = f'id_{self.prefix}-value' if self.prefix else 'id_value'operator_field_id = f'id_{self.prefix}-value_operator_str' if self.prefix else 'id_value_operator_str'self.fields['value_operator_str'].widget.attrs['onchange'] = (f'Hi.setEventClauseValueOperatorWidget('f'"{operator_field_id}", "{value_field_id}");')+ # Single source of truth for "which operators are numeric":+ # the enum. JS reads this attribute to drive its on-change+ # widget swap rather than hard-coding the list.+ self.fields['value_operator_str'].widget.attrs['data-numeric-ops'] = (+ json.dumps([+ str( op ) for op in EventClauseOperator if op.is_numeric+ ])+ )if 'class' not in self.fields['value'].widget.attrs:self.fields['value'].widget.attrs['class'] = 'form-control'return@@ -86,12 +105,19 @@ class EventClauseForm( forms.ModelForm, EntityStateSelectModelFormMixin ):def clean(self):cleaned = super().clean()op_str = cleaned.get( 'value_operator_str' )+ op = EventClauseOperator.from_name_safe( op_str ) if op_str else None+ # For IN, reassemble the POSTed value(s) into the model's+ # comma-delimited storage shape. ``getlist`` is uniform across+ # SelectMultiple (N entries) and TextInput (1 entry with+ # embedded commas) — the latter round-trips unchanged.+ if op == EventClauseOperator.IN:+ submitted = self.data.getlist( self.add_prefix( 'value' ))+ cleaned['value'] = models.EventClause.serialize_in_members( submitted )value = cleaned.get( 'value' )- # Numeric operators require a numeric value. The matcher silently- # no-ops on parse failure at runtime; reject at form time so the- # user gets immediate feedback instead of a clause that never- # fires.- if op_str and op_str != str(EventClauseOperator.EQ) and value:+ # The matcher silently no-ops on parse failure for numeric ops;+ # reject at form time so the user gets immediate feedback+ # instead of a clause that never fires.+ if op and op.is_numeric and value:try:float( value )except ( ValueError, TypeError ):diff --git a/src/hi/apps/event/edit/tests/test_forms.py b/src/hi/apps/event/edit/tests/test_forms.pyindex f16128bc..b1673a5a 100644--- a/src/hi/apps/event/edit/tests/test_forms.py+++ b/src/hi/apps/event/edit/tests/test_forms.py@@ -1,7 +1,11 @@import logging+from django import forms+from django.http import QueryDict+from hi.apps.entity.models import Entity, EntityStatefrom hi.apps.event.edit.forms import EventClauseForm+from hi.apps.event.models import EventClause, EventDefinitionfrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -26,14 +30,20 @@ class TestEventClauseFormValidation(BaseTestCase):)return- def test_non_numeric_value_with_lt_operator_is_rejected(self):- form = EventClauseForm( data = {- 'entity_state': str( self.entity_state.id ),- 'value_operator_str': 'lt',- 'value': 'abc',- })- self.assertFalse( form.is_valid() )- self.assertIn( 'value', form.errors )+ def test_non_numeric_value_with_numeric_operator_is_rejected(self):+ # Cover each numeric operator's narrowing — they all share the+ # parse-and-validate path, but pin every one so adding a fifth+ # to the enum and missing the form guard surfaces here.+ for op_str in ( 'lt', 'lte', 'gt', 'gte' ):+ with self.subTest( op_str = op_str ):+ form = EventClauseForm( data = {+ 'entity_state': str( self.entity_state.id ),+ 'value_operator_str': op_str,+ 'value': 'abc',+ })+ self.assertFalse( form.is_valid() )+ self.assertIn( 'value', form.errors )+ continuereturndef test_numeric_value_with_lt_operator_is_accepted(self):@@ -44,3 +54,170 @@ class TestEventClauseFormValidation(BaseTestCase):})self.assertTrue( form.is_valid(), msg = form.errors )return+++class TestEventClauseFormDiscreteOperators(BaseTestCase):+ """NEQ and IN operate against discrete string values, not numeric+ thresholds. The form's numeric-value guard must not reject them,+ and IN's multi-select POST must serialize to the model's+ comma-delimited storage shape."""++ def setUp(self):+ super().setUp()+ entity = Entity.objects.create(+ name = 'Test Camera',+ entity_type_str = 'camera',+ )+ self.discrete_state = EntityState.objects.create(+ entity = entity,+ name = 'Object Presence',+ entity_state_type_str = 'object_presence',+ )+ return++ def test_non_numeric_value_with_neq_operator_is_accepted(self):+ form = EventClauseForm( data = {+ 'entity_state': str( self.discrete_state.id ),+ 'value_operator_str': 'neq',+ 'value': 'object_none',+ })+ self.assertTrue( form.is_valid(), msg = form.errors )+ return++ def test_multi_select_values_serialize_to_comma_delimited_for_in(self):+ # Browser POSTs ``<select multiple>`` as repeated entries with+ # the same field name; the form clean reassembles them into+ # the comma-delimited storage shape used by EventClause.value.+ data = QueryDict( '', mutable = True )+ data['entity_state'] = str( self.discrete_state.id )+ data['value_operator_str'] = 'in'+ data.setlist( 'value', [ 'object_person', 'object_car' ] )+ form = EventClauseForm( data = data )+ self.assertTrue( form.is_valid(), msg = form.errors )+ # Sorted+joined for determinism; tests downstream of the+ # matcher don't care about order but assertions need a+ # deterministic value to compare against.+ self.assertEqual(+ form.cleaned_data['value'], 'object_car,object_person',+ )+ return++ def test_in_clause_renders_multi_select_for_discrete_state(self):+ # Form rendered for an existing IN clause on a discrete-choice+ # state should expose a SelectMultiple widget AND pre-populate+ # the initial with the parsed list — so the edit-page load+ # shows the persisted selection without any JS flicker.+ clause = self._make_in_clause( 'object_person,object_car' )+ form = EventClauseForm( instance = clause )+ self.assertIsInstance(+ form.fields['value'].widget, forms.SelectMultiple,+ )+ self.assertEqual(+ sorted( form.initial['value'] ),+ [ 'object_car', 'object_person' ],+ )+ # The widget must carry the entity_state's choices — a+ # regression that strips them or hands a stale list would+ # render an empty (or wrong) multi-select and the initial-+ # list assertion alone wouldn't notice.+ self.assertEqual(+ list( form.fields['value'].widget.choices ),+ list( self.discrete_state.choices() ),+ )+ return++ def test_in_clause_on_free_text_state_stays_text_input(self):+ # IN on an entity_state without discrete choices falls back to+ # a TextInput. The user types comma-delimited values; the+ # matcher splits at evaluation time.+ entity = Entity.objects.create(+ name = 'Free Text Entity',+ entity_type_str = 'other',+ )+ free_text_state = EntityState.objects.create(+ entity = entity,+ name = 'Notes',+ entity_state_type_str = 'multivalued',+ )+ event_definition = EventDefinition.objects.create(+ name = 'Test', event_type_str = 'security',+ event_window_secs = 0, dedupe_window_secs = 0,+ )+ clause = EventClause.objects.create(+ event_definition = event_definition,+ entity_state = free_text_state,+ value = 'foo,bar',+ value_operator_str = 'in',+ )+ form = EventClauseForm( instance = clause )+ self.assertNotIsInstance(+ form.fields['value'].widget, forms.SelectMultiple,+ )+ return++ def test_neq_clause_on_discrete_state_stays_single_select(self):+ # Regression guard: NEQ must NOT trip the IN multi-select+ # promotion. Single-value comparison stays on the entity_state-+ # driven Select.+ event_definition = EventDefinition.objects.create(+ name = 'Test', event_type_str = 'security',+ event_window_secs = 0, dedupe_window_secs = 0,+ )+ clause = EventClause.objects.create(+ event_definition = event_definition,+ entity_state = self.discrete_state,+ value = 'object_none',+ value_operator_str = 'neq',+ )+ form = EventClauseForm( instance = clause )+ self.assertNotIsInstance(+ form.fields['value'].widget, forms.SelectMultiple,+ )+ return++ def test_single_value_in_post_serializes_without_extra_commas(self):+ # The multi-select reassembly path must work uniformly for+ # one, several, or zero selections — single selection is the+ # case where the form-side default-clean (CharField over a+ # list) would otherwise stringify ``['object_person']``.+ data = QueryDict( '', mutable = True )+ data['entity_state'] = str( self.discrete_state.id )+ data['value_operator_str'] = 'in'+ data.setlist( 'value', [ 'object_person' ] )+ form = EventClauseForm( data = data )+ self.assertTrue( form.is_valid(), msg = form.errors )+ self.assertEqual( form.cleaned_data['value'], 'object_person' )+ return++ def test_operator_widget_emits_data_numeric_ops_from_enum(self):+ # The JS widget swap reads this attribute to decide when to+ # promote the value field to a number input. Keeping the list+ # enum-driven (instead of hard-coded JS) prevents drift when+ # the enum gains or loses a numeric operator.+ import json+ form = EventClauseForm( data = {+ 'entity_state': str( self.discrete_state.id ),+ 'value_operator_str': 'eq',+ 'value': 'object_person',+ })+ attr = form.fields['value_operator_str'].widget.attrs.get(+ 'data-numeric-ops',+ )+ self.assertIsNotNone( attr )+ self.assertEqual(+ sorted( json.loads( attr )),+ [ 'gt', 'gte', 'lt', 'lte' ],+ )+ return++ def _make_in_clause( self, value : str ):+ event_definition = EventDefinition.objects.create(+ name = 'Test', event_type_str = 'security',+ event_window_secs = 0, dedupe_window_secs = 0,+ )+ return EventClause.objects.create(+ event_definition = event_definition,+ entity_state = self.discrete_state,+ value = value,+ value_operator_str = 'in',+ )diff --git a/src/hi/apps/event/enums.py b/src/hi/apps/event/enums.pyindex 71477dee..b8a5bdfa 100644--- a/src/hi/apps/event/enums.py+++ b/src/hi/apps/event/enums.py@@ -11,14 +11,16 @@ class EventType(LabeledEnum):class EventClauseOperator(LabeledEnum):"""How an EventClause compares the live wire value against its- stored target value. EQ matches a discrete value (motion ACTIVE,- smoke SMOKE_DETECTED, etc.); the numeric operators trigger when- a continuous reading crosses a threshold (battery < 20%, etc.).- Numeric ops parse both sides via ``float()`` at match time and- silently no-op on parse failure so a malformed wire value never- raises into the matcher."""+ stored target value. EQ / NEQ match against a single discrete+ value; IN matches against a comma-separated list of values; the+ numeric operators trigger when a continuous reading crosses a+ threshold (battery < 20%, etc.). Numeric ops parse both sides+ via ``float()`` at match time and silently no-op on parse failure+ so a malformed wire value never raises into the matcher."""EQ = ( 'Equals' , 'Trigger when the value equals the target string.' )+ NEQ = ( 'Not Equals' , 'Trigger when the value does not equal the target string.' )+ IN = ( 'Is One Of' , 'Trigger when the value matches any item in a comma-separated list.' )LT = ( 'Less Than' , 'Trigger when the numeric value drops below the threshold.' )LTE = ( 'At Most' , 'Trigger when the numeric value is at or below the threshold.' )GT = ( 'Greater Than' , 'Trigger when the numeric value rises above the threshold.' )@@ -28,3 +30,15 @@ class EventClauseOperator(LabeledEnum):def default(cls):return cls.EQ+ @property+ def is_numeric(self) -> bool:+ """Operators that compare numeric magnitudes. Form-time+ validation requires a parseable numeric value for these; the+ matcher silently no-ops on non-numeric runtime values."""+ return self in {+ EventClauseOperator.LT,+ EventClauseOperator.LTE,+ EventClauseOperator.GT,+ EventClauseOperator.GTE,+ }+diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.pyindex 6ab8457b..219a5724 100644--- a/src/hi/apps/event/event_manager.py+++ b/src/hi/apps/event/event_manager.py@@ -148,14 +148,19 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):@staticmethoddef _clause_matches( entity_state_value : str, event_clause : EventClause ) -> bool:"""Compare a live EntityState reading against an EventClause- target per the clause's operator. EQ is plain string equality- (the historical behavior for discrete-value alarms). The- numeric operators parse both sides as ``float()`` and silently- no-op on parse failure so a transient non-numeric reading- never raises into the matcher."""+ target per the clause's operator. EQ / NEQ are plain string+ comparisons; IN parses the clause value as a comma-separated+ list and tests membership. The numeric operators parse both+ sides as ``float()`` and silently no-op on parse failure so+ a transient non-numeric reading never raises into the+ matcher."""op = event_clause.value_operatorif op == EventClauseOperator.EQ:return entity_state_value == event_clause.value+ if op == EventClauseOperator.NEQ:+ return entity_state_value != event_clause.value+ if op == EventClauseOperator.IN:+ return entity_state_value in event_clause.in_value_members()try:lhs = float( entity_state_value )rhs = float( event_clause.value )diff --git a/src/hi/apps/event/models.py b/src/hi/apps/event/models.pyindex cc5a310a..d2f5bb1b 100644--- a/src/hi/apps/event/models.py+++ b/src/hi/apps/event/models.py@@ -126,6 +126,8 @@ class EventClause( models.Model ):verbose_name = 'Trigger Clause'verbose_name_plural = 'Trigger Clauses'+ IN_VALUE_DELIMITER = ','+@propertydef value_operator(self) -> EventClauseOperator:return EventClauseOperator.from_name_safe( self.value_operator_str )@@ -135,6 +137,26 @@ class EventClause( models.Model ):self.value_operator_str = str(value_operator)return+ def in_value_members(self) -> set:+ """Members of the comma-delimited ``value`` used by the IN+ operator. Returns an empty set when ``value`` is empty or+ only contains delimiters / whitespace."""+ return {+ m.strip() for m in ( self.value or '' ).split(+ self.IN_VALUE_DELIMITER,+ )+ if m.strip()+ }++ @classmethod+ def serialize_in_members(cls, values) -> str:+ """Inverse of :meth:`in_value_members` — joins an iterable of+ member strings into the comma-delimited storage shape.+ Whitespace-tolerant, deduplicated, sorted for determinism."""+ return cls.IN_VALUE_DELIMITER.join( sorted({+ v.strip() for v in ( values or [] ) if v and v.strip()+ }))+class AlarmAction( models.Model ):diff --git a/src/hi/apps/event/tests/test_enums.py b/src/hi/apps/event/tests/test_enums.pyindex 0f899497..c45cf8ab 100644--- a/src/hi/apps/event/tests/test_enums.py+++ b/src/hi/apps/event/tests/test_enums.py@@ -1,6 +1,6 @@import logging-from hi.apps.event.enums import EventType+from hi.apps.event.enums import EventClauseOperator, EventTypefrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -17,7 +17,7 @@ class TestEventType(BaseTestCase):EventType.INFORMATION,EventType.AUTOMATION}-+actual_types = set(EventType)self.assertEqual(actual_types, expected_types)return@@ -30,3 +30,29 @@ class TestEventType(BaseTestCase):self.assertEqual(str(EventType.INFORMATION), 'information')self.assertEqual(str(EventType.AUTOMATION), 'automation')return+++class TestEventClauseOperatorIsNumeric(BaseTestCase):+ """``is_numeric`` is the load-bearing predicate the form, the JS+ widget swap (via ``data-numeric-ops``), and the matcher all key+ off of. A mistake here misclassifies an operator and silently+ breaks the form's value-validation gate."""++ def test_numeric_operators_are_numeric(self):+ for op in (+ EventClauseOperator.LT, EventClauseOperator.LTE,+ EventClauseOperator.GT, EventClauseOperator.GTE ):+ with self.subTest( op = op ):+ self.assertTrue( op.is_numeric )+ continue+ return++ def test_discrete_operators_are_not_numeric(self):+ for op in (+ EventClauseOperator.EQ,+ EventClauseOperator.NEQ,+ EventClauseOperator.IN ):+ with self.subTest( op = op ):+ self.assertFalse( op.is_numeric )+ continue+ returndiff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.pyindex fec5ab9d..a6c860f8 100644--- a/src/hi/apps/event/tests/test_event_manager.py+++ b/src/hi/apps/event/tests/test_event_manager.py@@ -724,3 +724,46 @@ class TestClauseMatchesOperatorDispatch(BaseTestCase):self.assertFalse( EventManager._clause_matches( '', clause ) )return+ def test_neq_matches_non_target_string( self ):+ clause = self._clause( 'object_none', EventClauseOperator.NEQ )+ self.assertTrue( EventManager._clause_matches( 'object_person', clause ) )+ self.assertTrue( EventManager._clause_matches( 'object_car', clause ) )+ self.assertFalse( EventManager._clause_matches( 'object_none', clause ) )+ return++ def test_neq_does_not_parse_value_as_float( self ):+ # NEQ short-circuits before the float-parse path, so a+ # non-numeric stored value (the common case for object/state+ # comparisons) must match exactly without raising.+ clause = self._clause( 'object_none', EventClauseOperator.NEQ )+ self.assertTrue( EventManager._clause_matches( 'object_person', clause ) )+ return++ def test_in_matches_any_listed_value( self ):+ clause = self._clause( 'a,b,c', EventClauseOperator.IN )+ self.assertTrue( EventManager._clause_matches( 'a', clause ) )+ self.assertTrue( EventManager._clause_matches( 'b', clause ) )+ self.assertTrue( EventManager._clause_matches( 'c', clause ) )+ self.assertFalse( EventManager._clause_matches( 'd', clause ) )+ return++ def test_in_tolerates_whitespace_around_delimiters( self ):+ # The form may submit values with whitespace (`'a, b , c'`)+ # depending on how the operator hand-typed the list; the+ # matcher must trim consistently so the rule still fires.+ clause = self._clause( 'a, b , c', EventClauseOperator.IN )+ self.assertTrue( EventManager._clause_matches( 'a', clause ) )+ self.assertTrue( EventManager._clause_matches( 'b', clause ) )+ self.assertTrue( EventManager._clause_matches( 'c', clause ) )+ return++ def test_in_empty_list_matches_nothing_without_raising( self ):+ for raw in ( '', ',,', ' , ,' ):+ with self.subTest( raw = raw ):+ clause = self._clause( raw, EventClauseOperator.IN )+ self.assertFalse(+ EventManager._clause_matches( 'anything', clause ),+ )+ continue+ return+diff --git a/src/hi/apps/event/tests/test_models.py b/src/hi/apps/event/tests/test_models.pyindex 796cde34..20e99a38 100644--- a/src/hi/apps/event/tests/test_models.py+++ b/src/hi/apps/event/tests/test_models.py@@ -520,3 +520,103 @@ class TestEventHistoryAdvanced(BaseTestCase):timestamps = [h.event_datetime for h in all_history]self.assertTrue(all(t == same_timestamp for t in timestamps))return+++class TestEventClauseInValueMembers(BaseTestCase):+ """``EventClause.in_value_members()`` is the parse side of the+ IN-operator comma-delimited storage. The matcher and the form+ both rely on it; pinning the contract at the lowest layer keeps+ behavior consistent across both consumers."""++ def _clause(self, value):+ return EventClause( value = value )++ def test_returns_empty_set_for_empty_string(self):+ self.assertEqual( self._clause( '' ).in_value_members(), set() )+ return++ def test_returns_empty_set_for_none_value(self):+ # value is normally a non-null CharField, but defensively the+ # parser tolerates a None — exercised when an EventClause is+ # constructed in memory without a value set yet.+ clause = EventClause()+ clause.value = None+ self.assertEqual( clause.in_value_members(), set() )+ return++ def test_returns_set_of_members(self):+ self.assertEqual(+ self._clause( 'a,b,c' ).in_value_members(),+ { 'a', 'b', 'c' },+ )+ return++ def test_strips_whitespace_around_members(self):+ self.assertEqual(+ self._clause( ' a , b , c ' ).in_value_members(),+ { 'a', 'b', 'c' },+ )+ return++ def test_dedupes_repeated_members(self):+ self.assertEqual(+ self._clause( 'a,a,b' ).in_value_members(),+ { 'a', 'b' },+ )+ return++ def test_drops_empty_members(self):+ for raw in ( ',,', ' , ,', 'a,,b' ):+ with self.subTest( raw = raw ):+ self.assertNotIn( '', self._clause( raw ).in_value_members() )+ continue+ return+++class TestEventClauseSerializeInMembers(BaseTestCase):+ """``EventClause.serialize_in_members()`` is the inverse of+ :meth:`in_value_members`. It produces a deterministic+ (sorted, deduplicated, whitespace-stripped) storage shape from+ an arbitrary iterable of member strings."""++ def test_empty_iterable_returns_empty_string(self):+ self.assertEqual( EventClause.serialize_in_members( [] ), '' )+ return++ def test_none_returns_empty_string(self):+ self.assertEqual( EventClause.serialize_in_members( None ), '' )+ return++ def test_joins_members_sorted_for_determinism(self):+ self.assertEqual(+ EventClause.serialize_in_members([ 'c', 'a', 'b' ]),+ 'a,b,c',+ )+ return++ def test_strips_whitespace_and_dedupes(self):+ self.assertEqual(+ EventClause.serialize_in_members([ ' a ', 'a', 'b ' ]),+ 'a,b',+ )+ return++ def test_drops_empty_and_whitespace_only_members(self):+ self.assertEqual(+ EventClause.serialize_in_members([ '', ' ', 'a', None ]),+ 'a',+ )+ return++ def test_round_trip_via_in_value_members_is_stable(self):+ # parse → serialize is idempotent: feeding the serialized form+ # back through the parser and re-serializing yields the same+ # string. Documents the contract storage-shape callers depend+ # on.+ original = 'a,b,c'+ clause = EventClause( value = original )+ re_serialized = EventClause.serialize_in_members(+ clause.in_value_members(),+ )+ self.assertEqual( re_serialized, original )+ returndiff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.pyindex 024bfc22..a982ef04 100644--- a/src/hi/apps/sense/sensor_response_manager.py+++ b/src/hi/apps/sense/sensor_response_manager.py@@ -114,19 +114,47 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):async def update_with_latest_sensor_responses(self,sensor_response_map : Dict[ IntegrationKey, SensorResponse ] ):- """- Used when states are polled and get current state at a point in time- which may or may not represent a change in state. We only want to- keep the history of changed states, so we fetch previous values to- detect changes.- """+ """Single-response-per-key entry point. The common case — one+ transition per sensor per poll cycle. Callers whose poll+ window may carry multiple transitions for the same sensor+ (e.g., Frigate switching object class within one cycle)+ should call :meth:`update_with_latest_sensor_response_lists`+ directly instead of forcing their multiple responses through+ this dict shape (which would collapse them on overwrite).++ Thin adapter: wraps each value in a single-element list and+ delegates to the list-shape entry point."""if not sensor_response_map:return+ await self.update_with_latest_sensor_response_lists(+ sensor_response_list_map = {+ key: [ response ]+ for key, response in sensor_response_map.items()+ },+ )+ return++ async def update_with_latest_sensor_response_lists(+ self,+ sensor_response_list_map : Dict[ IntegrationKey, List[ SensorResponse ] ] ):+ """Multi-response-per-key entry point.++ Each list is treated as chronologically ordered (sorted by+ timestamp internally as a safety net). Each response is+ compared against the running previous state — initially the+ cached latest from Redis, then the prior response in the+ same list. Equal-value responses are skipped; changes are+ recorded as both a history row and an entity-state transition.+ """+ if not sensor_response_list_map:+ returnchanged_sensor_response_list = list()entity_state_transition_list = list()- list_cache_keys = [ self.to_sensor_response_list_cache_key(x) for x in sensor_response_map.keys() ]- integration_keys = list( sensor_response_map.keys() )+ integration_keys = list( sensor_response_list_map.keys() )+ list_cache_keys = [+ self.to_sensor_response_list_cache_key( k ) for k in integration_keys+ ]pipeline = self._redis_client.pipeline()for list_cache_key in list_cache_keys:@@ -135,11 +163,19 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):cached_values = pipeline.execute()for integration_key, cached_value in zip( integration_keys, cached_values ):- latest_sensor_response = sensor_response_map.get( integration_key )+ response_list = sorted(+ sensor_response_list_map.get( integration_key ) or [],+ key = lambda r : r.timestamp,+ )if cached_value:previous_sensor_response = SensorResponse.from_string( cached_value )- if latest_sensor_response.value == previous_sensor_response.value:+ else:+ previous_sensor_response = None++ for latest_sensor_response in response_list:+ if ( previous_sensor_response is not None+ and latest_sensor_response.value == previous_sensor_response.value ):if settings.DEBUG and settings.DEBUG_TRACE_STATE:sensor = latest_sensor_response.sensorDevOverrideManager.trace_state(@@ -150,32 +186,35 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):)continue- entity_state_transition = await self._create_entity_state_transition(- previous_sensor_response = previous_sensor_response,- latest_sensor_response = latest_sensor_response,- )- if entity_state_transition:- entity_state_transition_list.append( entity_state_transition )-- if settings.DEBUG and settings.DEBUG_TRACE_STATE:- sensor = latest_sensor_response.sensor- DevOverrideManager.trace_state(- 'hi.sensor.commit',- integration_name = integration_key.integration_name,- hi_entity_state_id = sensor.entity_state.id if sensor else None,- hi_value = f'{previous_sensor_response.value} -> {latest_sensor_response.value}',- )- else:- if settings.DEBUG and settings.DEBUG_TRACE_STATE:- sensor = latest_sensor_response.sensor- DevOverrideManager.trace_state(- 'hi.sensor.first',- integration_name = integration_key.integration_name,- hi_entity_state_id = sensor.entity_state.id if sensor else None,- hi_value = latest_sensor_response.value,+ if previous_sensor_response is not None:+ entity_state_transition = await self._create_entity_state_transition(+ previous_sensor_response = previous_sensor_response,+ latest_sensor_response = latest_sensor_response,)+ if entity_state_transition:+ entity_state_transition_list.append( entity_state_transition )- changed_sensor_response_list.append( latest_sensor_response )+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:+ sensor = latest_sensor_response.sensor+ DevOverrideManager.trace_state(+ 'hi.sensor.commit',+ integration_name = integration_key.integration_name,+ hi_entity_state_id = sensor.entity_state.id if sensor else None,+ hi_value = f'{previous_sensor_response.value} -> {latest_sensor_response.value}',+ )+ else:+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:+ sensor = latest_sensor_response.sensor+ DevOverrideManager.trace_state(+ 'hi.sensor.first',+ integration_name = integration_key.integration_name,+ hi_entity_state_id = sensor.entity_state.id if sensor else None,+ hi_value = latest_sensor_response.value,+ )++ changed_sensor_response_list.append( latest_sensor_response )+ previous_sensor_response = latest_sensor_response+ continuecontinueawait self._add_latest_sensor_responses( changed_sensor_response_list )diff --git a/src/hi/apps/sense/tests/test_sensor_response_manager.py b/src/hi/apps/sense/tests/test_sensor_response_manager.pyindex 510e0e53..62b703d8 100644--- a/src/hi/apps/sense/tests/test_sensor_response_manager.py+++ b/src/hi/apps/sense/tests/test_sensor_response_manager.py@@ -1,6 +1,6 @@import logging-from datetime import datetime-from unittest.mock import Mock, patch+from datetime import datetime, timedelta+from unittest.mock import AsyncMock, Mock, patchfrom django.utils import timezonefrom hi.testing.async_task_utils import AsyncTaskFastTestCase, AsyncTaskTestCase@@ -397,3 +397,260 @@ class AsyncSensorResponseManagerCrossConnectionTestCase(AsyncTaskTestCase):self.manager._latest_sensor_data_dirty,'Dirty flag must be True after the Redis pipeline executes',)+++class TestUpdateWithLatestSensorResponseLists(AsyncTaskFastTestCase):+ """``update_with_latest_sensor_response_lists`` is the multi-+ response-per-key entry point. The old single-response method is+ now a thin adapter that wraps each value and delegates here, so+ these tests pin both contracts via the new method's behavior:++ * chronological ordering (incoming list sorted by timestamp)+ * running-previous comparison (cached → first response → second → ...)+ * same-value dedup against the cached prior AND within the list+ * multiple responses per key persisted as separate transitions+ * multiple keys processed independently+ * empty list per key is a no-op+ * first-ever observation (no cache) — persisted without transition+ """++ def setUp(self):+ super().setUp()+ SensorResponseManager._instances = {}+ self.manager = SensorResponseManager()++ self.key_a = IntegrationKey(+ integration_id = 'sensor_a',+ integration_name = 'test',+ )+ self.key_b = IntegrationKey(+ integration_id = 'sensor_b',+ integration_name = 'test',+ )+ self.t0 = timezone.now()++ def _response(self, key, value, offset_secs = 0):+ return SensorResponse(+ integration_key = key,+ value = value,+ timestamp = self.t0 + timedelta( seconds = offset_secs ),+ )++ def _run_update(self, sensor_response_list_map, cached_per_key = None):+ """Mock Redis and the event manager around a single call to+ ``update_with_latest_sensor_response_lists``. Returns+ (changed_responses, transitions) — the lists the manager+ would persist and dispatch.++ ``cached_per_key`` is a dict mapping integration_key →+ previously-cached SensorResponse (string form, as Redis+ returns), or None for no prior cache."""+ cached_per_key = cached_per_key or {}++ def fake_lindex_results():+ return [+ str( cached_per_key[ k ] ) if k in cached_per_key else None+ for k in sensor_response_list_map.keys()+ ]++ captured = { 'changed': None, 'transitions': None }++ async def capture_add( responses ):+ captured['changed'] = list( responses )++ async def capture_transitions( transitions ):+ captured['transitions'] = list( transitions )++ mock_pipeline = Mock()+ mock_pipeline.execute.return_value = fake_lindex_results()+ mock_redis = Mock()+ mock_redis.pipeline.return_value = mock_pipeline++ mock_event_manager = Mock()+ mock_event_manager.add_entity_state_transitions = AsyncMock(+ side_effect = capture_transitions,+ )++ def fake_create_transition( previous_sensor_response, latest_sensor_response ):+ return (+ previous_sensor_response.value,+ latest_sensor_response.value,+ )++ async def run():+ with patch.object( self.manager, '_redis_client', mock_redis ), \+ patch.object( self.manager, '_add_latest_sensor_responses',+ side_effect = capture_add ), \+ patch.object( self.manager, 'event_manager_async',+ return_value = mock_event_manager ), \+ patch.object( self.manager, '_create_entity_state_transition',+ new = AsyncMock( side_effect = fake_create_transition )):+ await self.manager.update_with_latest_sensor_response_lists(+ sensor_response_list_map = sensor_response_list_map,+ )++ self.run_async( run() )+ return captured['changed'] or [], captured['transitions'] or []++ def test_empty_map_is_noop(self):+ changed, transitions = self._run_update({})+ self.assertEqual( changed, [] )+ self.assertEqual( transitions, [] )++ def test_first_ever_observation_records_without_transition(self):+ # No cached prior → first response is recorded as a history row+ # but does not produce a transition (there's no "from" value).+ response = self._response( self.key_a, 'on' )+ changed, transitions = self._run_update({+ self.key_a: [ response ],+ })+ self.assertEqual( [ r.value for r in changed ], [ 'on' ] )+ self.assertEqual( transitions, [] )++ def test_same_value_as_cached_is_skipped(self):+ # Cached: on. Submitted: on → no change, nothing persisted.+ cached = self._response( self.key_a, 'on', offset_secs = -10 )+ submitted = self._response( self.key_a, 'on' )+ changed, transitions = self._run_update(+ { self.key_a: [ submitted ] },+ cached_per_key = { self.key_a: cached },+ )+ self.assertEqual( changed, [] )+ self.assertEqual( transitions, [] )++ def test_value_change_against_cached_records_transition(self):+ cached = self._response( self.key_a, 'off', offset_secs = -10 )+ submitted = self._response( self.key_a, 'on' )+ changed, transitions = self._run_update(+ { self.key_a: [ submitted ] },+ cached_per_key = { self.key_a: cached },+ )+ self.assertEqual( [ r.value for r in changed ], [ 'on' ] )+ self.assertEqual( transitions, [ ( 'off', 'on' ) ] )++ def test_multi_response_per_key_processes_each_against_running_previous(self):+ # No cached prior. Submit [A, B, C] for one key → first A+ # records as first-ever (no transition); A→B transition; B→C+ # transition. Three persisted, two transitions.+ responses = [+ self._response( self.key_a, 'a', offset_secs = 1 ),+ self._response( self.key_a, 'b', offset_secs = 2 ),+ self._response( self.key_a, 'c', offset_secs = 3 ),+ ]+ changed, transitions = self._run_update({ self.key_a: responses })+ self.assertEqual( [ r.value for r in changed ], [ 'a', 'b', 'c' ] )+ self.assertEqual( transitions, [ ( 'a', 'b' ), ( 'b', 'c' ) ] )++ def test_consecutive_duplicates_within_list_are_skipped(self):+ # No cached prior. Submit [A, B, B, C]. First A is first-ever+ # (records, no transition). A→B is recorded as transition.+ # Second B matches the running previous (B) → skipped. B→C+ # is recorded.+ responses = [+ self._response( self.key_a, 'a', offset_secs = 1 ),+ self._response( self.key_a, 'b', offset_secs = 2 ),+ self._response( self.key_a, 'b', offset_secs = 3 ),+ self._response( self.key_a, 'c', offset_secs = 4 ),+ ]+ changed, transitions = self._run_update({ self.key_a: responses })+ self.assertEqual( [ r.value for r in changed ], [ 'a', 'b', 'c' ] )+ self.assertEqual( transitions, [ ( 'a', 'b' ), ( 'b', 'c' ) ] )++ def test_out_of_order_responses_get_sorted_by_timestamp(self):+ # Defensive: caller might assemble the list in phase order+ # rather than chronological order. The manager sorts by+ # timestamp before applying the running-previous walk.+ responses = [+ self._response( self.key_a, 'b', offset_secs = 2 ), # later+ self._response( self.key_a, 'a', offset_secs = 1 ), # earlier+ ]+ changed, transitions = self._run_update({ self.key_a: responses })+ # Order chronologically: a (first-ever, no transition),+ # then b (a→b transition).+ self.assertEqual( [ r.value for r in changed ], [ 'a', 'b' ] )+ self.assertEqual( transitions, [ ( 'a', 'b' ) ] )++ def test_empty_list_for_a_key_is_noop(self):+ changed, transitions = self._run_update({ self.key_a: [] })+ self.assertEqual( changed, [] )+ self.assertEqual( transitions, [] )++ def test_multiple_keys_processed_independently(self):+ # Two keys, each with its own running-previous. A change on+ # key_a does not affect comparisons on key_b.+ cached_a = self._response( self.key_a, 'off', offset_secs = -10 )+ responses = {+ self.key_a: [ self._response( self.key_a, 'on', offset_secs = 1 ) ],+ self.key_b: [+ self._response( self.key_b, 'x', offset_secs = 1 ),+ self._response( self.key_b, 'y', offset_secs = 2 ),+ ],+ }+ changed, transitions = self._run_update(+ responses, cached_per_key = { self.key_a: cached_a },+ )+ self.assertEqual(+ sorted( r.value for r in changed ),+ [ 'on', 'x', 'y' ],+ )+ # key_a contributes off→on; key_b's x is first-ever (no+ # transition), x→y is the one transition.+ self.assertEqual(+ sorted( transitions ),+ sorted( [ ( 'off', 'on' ), ( 'x', 'y' ) ] ),+ )++ def test_adapter_wraps_single_response_into_list(self):+ # The old single-response entry point now delegates to the+ # list-form one. Single response, same key behavior.+ response = self._response( self.key_a, 'on' )++ captured = { 'arg': None }++ async def capture( sensor_response_list_map ):+ captured['arg'] = sensor_response_list_map++ async def run():+ with patch.object(+ self.manager, 'update_with_latest_sensor_response_lists',+ side_effect = capture,+ ):+ await self.manager.update_with_latest_sensor_responses({+ self.key_a: response,+ })++ self.run_async( run() )+ self.assertEqual( captured['arg'], { self.key_a: [ response ] } )++ def test_event_manager_dispatch_is_awaited_when_transitions_exist(self):+ # Regression guard for the dispatch site: if the production+ # code ever stops awaiting ``add_entity_state_transitions``,+ # the transition-list assertions in the other tests still+ # pass (because they capture the side_effect arg) — but the+ # transitions are no longer delivered to downstream+ # consumers. Assert the call was made.+ cached = self._response( self.key_a, 'off', offset_secs = -10 )+ submitted = self._response( self.key_a, 'on' )++ mock_pipeline = Mock()+ mock_pipeline.execute.return_value = [ str( cached ) ]+ mock_redis = Mock()+ mock_redis.pipeline.return_value = mock_pipeline++ mock_event_manager = Mock()+ mock_event_manager.add_entity_state_transitions = AsyncMock()++ async def run():+ with patch.object( self.manager, '_redis_client', mock_redis ), \+ patch.object( self.manager, '_add_latest_sensor_responses',+ new = AsyncMock() ), \+ patch.object( self.manager, 'event_manager_async',+ return_value = mock_event_manager ), \+ patch.object( self.manager, '_create_entity_state_transition',+ new = AsyncMock( return_value = ( 'off', 'on' ))):+ await self.manager.update_with_latest_sensor_response_lists({+ self.key_a: [ submitted ],+ })++ self.run_async( run() )+ mock_event_manager.add_entity_state_transitions.assert_awaited_once()diff --git a/src/hi/services/frigate/monitors.py b/src/hi/services/frigate/monitors.pyindex 64c783f5..06e70150 100644--- a/src/hi/services/frigate/monitors.py+++ b/src/hi/services/frigate/monitors.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom datetime import datetime, timedeltaimport loggingfrom typing import Dict, List, Optional, Set, Tuple@@ -11,6 +12,7 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.enums import CorrelationRolefrom hi.apps.sense.sensor_response_manager import SensorResponseMixinfrom hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKeyfrom hi.apps.system.provider_info import ProviderInfofrom hi.testing.dev_overrides import DevOverrideManager@@ -111,13 +113,13 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):self.record_warning( 'Was not initialized.' )return- sensor_response_map = dict()- sensor_response_map.update( await self._process_events() )+ sensor_response_list_map = await self._process_events()- await self.sensor_response_manager().update_with_latest_sensor_responses(- sensor_response_map = sensor_response_map,+ await self.sensor_response_manager().update_with_latest_sensor_response_lists(+ sensor_response_list_map = sensor_response_list_map,)- self.record_healthy( f'Processed {len(sensor_response_map)} Frigate states.' )+ response_count = sum( len( v ) for v in sensor_response_list_map.values() )+ self.record_healthy( f'Processed {response_count} Frigate states.' )return# ---- SensorResponse factory helpers ------------------------------@@ -176,25 +178,29 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):# ---- Event processing pipeline ---------------------------------- async def _process_events(self) -> Dict:+ async def _process_events(self) -> Dict[ IntegrationKey, List[ SensorResponse ] ]:current_poll_datetime = datetimeproxy.now()- scan_map, scan_touched = await self._scan_new_events_phase()- refresh_map, refresh_touched = await self._refresh_tracked_events_phase(+ scan_responses, scan_touched = await self._scan_new_events_phase()+ refresh_responses, refresh_touched = await self._refresh_tracked_events_phase(current_poll_datetime = current_poll_datetime,)- heartbeat_map = await self._heartbeat_idle_cameras_phase(+ heartbeat_responses = await self._heartbeat_idle_cameras_phase(current_poll_datetime = current_poll_datetime,cameras_touched = scan_touched | refresh_touched,)- sensor_response_map : Dict = {}- sensor_response_map.update( scan_map )- sensor_response_map.update( refresh_map )- sensor_response_map.update( heartbeat_map )- return sensor_response_map+ # Group all responses by integration_key, preserving multiple+ # responses per key for the same poll cycle (Person→Car within+ # one cycle yields END Person + START Car on the same sensor).+ sensor_response_list_map : Dict[ IntegrationKey, List[ SensorResponse ] ] = (+ defaultdict( list )+ )+ for response in ( scan_responses + refresh_responses + heartbeat_responses ):+ sensor_response_list_map[ response.integration_key ].append( response )+ return dict( sensor_response_list_map )- async def _scan_new_events_phase(self) -> Tuple[ Dict, Set[ str ] ]:+ async def _scan_new_events_phase(self) -> Tuple[ List[ SensorResponse ], Set[ str ] ]:"""Query ``?after=cursor`` for events whose ``start_time``is past our watermark. Cursor is monotonic so any id returnedhere is new to us (any prior open event has ``start_time@@ -202,9 +208,8 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):Each new event:- emit START transition- - if already closed: also emit END transition (open-and-close- collapsed into a single cycle is unavoidable when an- event's lifetime is shorter than the poll interval)+ - if already closed: also emit END transition (downstream+ handles both as a multi-response sequence on the same key)- else: enter the open set for phase-2 tracking"""after_epoch = self._poll_cursor_datetime.timestamp()@@ -230,28 +235,26 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):continuenew_events.append( event )- sensor_response_map : Dict = {}+ responses : List[ SensorResponse ] = []cameras_touched : Set[ str ] = set()now = datetimeproxy.now()for event in new_events:cameras_touched.add( event.camera_name )- start_response = self._build_object_presence_response(+ responses.append( self._build_object_presence_response(event = event,value = FrigateConverter.to_canonical_object_class(raw_class = event.object_class,),timestamp = event.start_datetime,correlation_role = CorrelationRole.START,- )- sensor_response_map[ start_response.integration_key ] = start_response+ ))if event.is_closed:- end_response = self._build_object_presence_response(+ responses.append( self._build_object_presence_response(event = event,value = FrigateConverter.OBJECT_NONE_VALUE,timestamp = event.end_datetime,correlation_role = CorrelationRole.END,- )- sensor_response_map[ end_response.integration_key ] = end_response+ ))else:self._tracked_events[ event.event_id ] = TrackedFrigateEvent(event = event,@@ -267,20 +270,20 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):latest_start = max( e.start_datetime for e in new_events )if latest_start > self._poll_cursor_datetime:self._poll_cursor_datetime = latest_start- return sensor_response_map, cameras_touched+ return responses, cameras_touchedasync def _refresh_tracked_events_phase(self,current_poll_datetime : datetime,- ) -> Tuple[ Dict, Set[ str ] ]:- """Per-id refresh for every event currently in the open set.+ ) -> Tuple[ List[ SensorResponse ], Set[ str ] ]:+ """Per-id refresh for every event currently in the tracked set.Outcomes per id:- 404 → force-close (vanished)- other failure → leave in set; force-close if aged out- closed → emit END, remove from set- still open → refresh snapshot; force-close if aged out"""- sensor_response_map : Dict = {}+ responses : List[ SensorResponse ] = []cameras_touched : Set[ str ] = set()tracked_ids = list( self._tracked_events.keys() ) # snapshotfor event_id in tracked_ids:@@ -296,7 +299,7 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):tracked_event = tracked_event,timestamp = current_poll_datetime,reason = 'vanished',- sensor_response_map = sensor_response_map,+ responses = responses,cameras_touched = cameras_touched,)continue@@ -309,7 +312,7 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):tracked_event = tracked_event,timestamp = current_poll_datetime,reason = 'force_close_timeout',- sensor_response_map = sensor_response_map,+ responses = responses,cameras_touched = cameras_touched,)continue@@ -324,13 +327,12 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):cameras_touched.add( frigate_event.camera_name )if frigate_event.is_closed:- end_response = self._build_object_presence_response(+ responses.append( self._build_object_presence_response(event = frigate_event,value = FrigateConverter.OBJECT_NONE_VALUE,timestamp = frigate_event.end_datetime,correlation_role = CorrelationRole.END,- )- sensor_response_map[ end_response.integration_key ] = end_response+ ))del self._tracked_events[ event_id ]continue@@ -340,16 +342,16 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):tracked_event = tracked_event,timestamp = current_poll_datetime,reason = 'force_close_timeout',- sensor_response_map = sensor_response_map,+ responses = responses,cameras_touched = cameras_touched,)- return sensor_response_map, cameras_touched+ return responses, cameras_touchedasync def _heartbeat_idle_cameras_phase(self,current_poll_datetime : datetime,cameras_touched : Set[ str ],- ) -> Dict:+ ) -> List[ SensorResponse ]:"""Emit OBJECT_NONE for cameras with no event activity thiscycle and no event currently tracked in the open set.@@ -363,13 +365,13 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):logger.warning(f'Frigate camera list fetch failed during heartbeat: {e}')- return {}+ return []open_camera_names = {tracked_event.event.camera_namefor tracked_event in self._tracked_events.values()}- sensor_response_map : Dict = {}+ responses : List[ SensorResponse ] = []for camera in cameras:camera_name = camera[ 'name' ]if camera_name in cameras_touched:@@ -381,7 +383,7 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):value = FrigateConverter.OBJECT_NONE_VALUE,timestamp = current_poll_datetime,)- sensor_response_map[ idle_response.integration_key ] = idle_response+ responses.append( idle_response )if settings.DEBUG and settings.DEBUG_TRACE_STATE:DevOverrideManager.trace_state(@@ -390,26 +392,25 @@ class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):integration_value = idle_response.value,camera_name = camera_name,)- return sensor_response_map+ return responsesdef _force_close(self,- tracked_event : TrackedFrigateEvent,- timestamp : datetime,- reason : str,- sensor_response_map : Dict,- cameras_touched : Set[ str ],+ tracked_event : TrackedFrigateEvent,+ timestamp : datetime,+ reason : str,+ responses : List[ SensorResponse ],+ cameras_touched : Set[ str ],) -> None:- """Drop ``tracked_event`` from the open set and emit a synthesized- END response in ``sensor_response_map``. Used when Frigate's+ """Drop ``tracked_event`` from the tracked set and append a+ synthesized END response to ``responses``. Used when Frigate'scanonical state cannot be obtained (404, persistent fetchfailure past the age threshold)."""- response = self._build_force_close_response(+ responses.append( self._build_force_close_response(tracked_event = tracked_event,timestamp = timestamp,reason = reason,- )- sensor_response_map[ response.integration_key ] = response+ ))cameras_touched.add( tracked_event.event.camera_name )del self._tracked_events[ tracked_event.event.event_id ]returndiff --git a/src/hi/services/frigate/tests/test_frigate_monitor.py b/src/hi/services/frigate/tests/test_frigate_monitor.pyindex 88be3bd0..327b5e12 100644--- a/src/hi/services/frigate/tests/test_frigate_monitor.py+++ b/src/hi/services/frigate/tests/test_frigate_monitor.py@@ -351,12 +351,25 @@ class _PipelineTestBase( AsyncTaskFastTestCase ):}def _find_response(self, responses, camera_name):+ """Return the sole response for the given camera. Asserts the+ list has exactly one entry — tests that legitimately expect a+ multi-response cycle must use ``_find_responses`` and assert+ on the full list explicitly."""+ response_list = self._find_responses( responses, camera_name )+ if len( response_list ) != 1:+ raise AssertionError(+ f'Expected exactly one response for {camera_name!r}, '+ f'got {len(response_list)}: {response_list}'+ )+ return response_list[ 0 ]++ def _find_responses(self, responses, camera_name):target = f'{FrigateManager.OBJECT_PRESENCE_SENSOR_PREFIX}.{camera_name}'- for r in responses.values():- if r.integration_key.integration_name == target:- return r+ for integration_key, response_list in responses.items():+ if integration_key.integration_name == target:+ return response_listcontinue- raise AssertionError( f'No OBJECT_PRESENCE response for {camera_name!r}' )+ raise AssertionError( f'No OBJECT_PRESENCE responses for {camera_name!r}' )async def _run(self):return await self.monitor._process_events()@@ -412,8 +425,9 @@ class TestFrigateScanNewEventsPhase( _PipelineTestBase ):def test_open_and_closed_within_one_cycle_emits_both_rows(self):"""Lifetime shorter than poll interval: a single scan returns- the event already-closed. Emit START and END in this cycle,- don't enter the open set."""+ the event already-closed. Both START and END must travel in+ the per-key response list — the SensorResponseManager records+ each as its own history row and transition."""s = self.start + timedelta( seconds = 5 )e = s + timedelta( seconds = 1 )self._set_events([@@ -422,20 +436,27 @@ class TestFrigateScanNewEventsPhase( _PipelineTestBase ):responses = self.run_async( self._run() )self.assertNotIn( 'X', self.monitor._tracked_events )- # The map is keyed by integration_key so START and END for the- # same camera collapse to one entry — the latest assignment- # wins. END should be the survivor since it's assigned after.- obj = self._find_response( responses, 'front_yard' )- self.assertEqual( obj.correlation_role, CorrelationRole.END )- self.assertEqual( obj.correlation_id, 'X' )+ response_list = self._find_responses( responses, 'front_yard' )+ roles = [ r.correlation_role for r in response_list ]+ self.assertEqual(+ roles, [ CorrelationRole.START, CorrelationRole.END ],+ )+ self.assertTrue(+ all( r.correlation_id == 'X' for r in response_list ),+ )def test_malformed_event_payload_is_skipped(self):+ # Use an open event for 'good' so the test exercises the+ # malformed-skip path without also producing a START+END pair+ # that would obscure the assertion.s = self.start + timedelta( seconds = 5 )self._set_events([{ 'id': 'bad', 'camera': 'front_yard' }, # missing label/start- self._api_event( event_id = 'good', start = s,- end = s + timedelta( seconds = 2 )),+ self._api_event( event_id = 'good', start = s, end = None ),])+ self._set_event_by_id({+ 'good': self._api_event( event_id = 'good', start = s, end = None ),+ })responses = self.run_async( self._run() )self.assertEqual(self._find_response( responses, 'front_yard' ).correlation_id,@@ -673,8 +694,8 @@ class TestFrigateHeartbeatPhase( _PipelineTestBase ):target = (f'{FrigateManager.OBJECT_PRESENCE_SENSOR_PREFIX}.front_yard')- for r in responses.values():- if r.integration_key.integration_name == target:+ for integration_key in responses.keys():+ if integration_key.integration_name == target:self.fail('front_yard should not receive a phase-3 heartbeat'' while it has an open event in the tracking set.'@@ -752,4 +773,65 @@ class TestFrigateOpenCloseTransitionAcrossCycles( _PipelineTestBase ):# Open set is empty again — ready to receive the next event.self.assertEqual( self.monitor._tracked_events, {} )+ def test_object_class_switch_within_one_cycle_emits_both_transitions(self):+ """Person→Car switch within one poll cycle: Frigate closes the+ prior Person event and opens a Car event. HI's cursor scan+ sees the new Car; phase 2 refresh sees the closed Person. Both+ responses must travel in the per-key list — collapse to one+ would silently drop the Car START and a downstream rule on+ ``OBJECT_PRESENCE NEQ OBJECT_NONE`` would fail to re-fire."""+ # Cycle 1: Person event is open.+ person_start = self.start + timedelta( seconds = 1 )+ self._set_events([+ self._api_event(+ event_id = 'p', start = person_start, end = None,+ label = 'person',+ ),+ ])+ self._set_event_by_id({+ 'p': self._api_event(+ event_id = 'p', start = person_start, end = None,+ label = 'person',+ ),+ })+ self.run_async( self._run() )+ self.assertIn( 'p', self.monitor._tracked_events )++ # Cycle 2: user switched Person → Car. Simulator closes the+ # Person event and opens a Car event with a later start_time.+ person_end = person_start + timedelta( seconds = 5 )+ car_start = person_end + timedelta( milliseconds = 1 )+ self._set_events([+ self._api_event(+ event_id = 'c', start = car_start, end = None,+ label = 'car',+ ),+ ])+ self._set_event_by_id({+ 'p': self._api_event(+ event_id = 'p', start = person_start, end = person_end,+ label = 'person',+ ),+ 'c': self._api_event(+ event_id = 'c', start = car_start, end = None,+ label = 'car',+ ),+ })+ cycle2 = self.run_async( self._run() )++ # Person END (phase 2) and Car START (phase 1) must BOTH be+ # in front_yard's response list, in chronological order. The+ # SensorResponseManager records each transition independently.+ response_list = self._find_responses( cycle2, 'front_yard' )+ sorted_responses = sorted( response_list, key = lambda r : r.timestamp )+ self.assertEqual( len( sorted_responses ), 2 )+ self.assertEqual( sorted_responses[ 0 ].correlation_role, CorrelationRole.END )+ self.assertEqual( sorted_responses[ 0 ].correlation_id, 'p' )+ self.assertEqual( sorted_responses[ 1 ].correlation_role, CorrelationRole.START )+ self.assertEqual( sorted_responses[ 1 ].correlation_id, 'c' )++ # Open set has swapped contents: Person gone, Car tracked.+ self.assertNotIn( 'p', self.monitor._tracked_events )+ self.assertIn( 'c', self.monitor._tracked_events )+diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.jsindex 0fe457cb..cf8c6870 100644--- a/src/hi/static/js/main.js+++ b/src/hi/static/js/main.js@@ -221,25 +221,46 @@}function _setEventClauseValueOperatorWidget( operatorFieldId, valueFieldId ) {- // EventClause operator change handler. For non-EQ operators- // (LT / LTE / GT / GTE) the value is a numeric threshold —- // swap the value field to a number input so users can enter- // one even when the entity_state has discrete choices. EQ- // leaves the existing widget alone; the entity_state-driven- // choice swap is the authoritative source for that case.- const op = $(`#${operatorFieldId}`).val().toLowerCase();- if (op === 'eq') {+ // EventClause operator change handler. Four cases:+ // numeric ops → number input; IN → multi-select; EQ/NEQ →+ // leave widget alone (collapsing a prior IN multi-select if+ // needed). The numeric-ops list comes from the operator+ // field's ``data-numeric-ops`` attribute so the enum stays+ // the single source of truth.+ const operatorElement = $(`#${operatorFieldId}`);+ const op = operatorElement.val().toLowerCase();+ const numericOps = JSON.parse(+ operatorElement.attr( 'data-numeric-ops' ) || '[]'+ );+ const valueElement = $(`#${valueFieldId}`);+ const isSelect = ( valueElement.prop( 'tagName' ).toLowerCase() === 'select' );++ if ( numericOps.includes( op )) {+ const currentValue = isSelect ? '' : valueElement.val();+ const numericInput = $('<input>')+ .attr( 'type', 'number' )+ .attr( 'step', 'any' )+ .attr( 'id', valueElement.attr('id') )+ .attr( 'name', valueElement.attr('name') )+ .val( currentValue );+ valueElement.replaceWith( numericInput );return;}- const valueElement = $(`#${valueFieldId}`);- const currentValue = valueElement.val();- const numericInput = $('<input>')- .attr( 'type', 'number' )- .attr( 'step', 'any' )- .attr( 'id', valueElement.attr('id') )- .attr( 'name', valueElement.attr('name') )- .val( currentValue );- valueElement.replaceWith( numericInput );++ if ( op === 'in' ) {+ if ( isSelect ) {+ valueElement.attr( 'multiple', 'multiple' );+ }+ return;+ }++ if ( isSelect && valueElement.attr( 'multiple' )) {+ valueElement.removeAttr( 'multiple' );+ const selected = valueElement.find( 'option:selected' );+ if ( selected.length > 1 ) {+ selected.slice( 1 ).prop( 'selected', false );+ }+ }}function _setEntityStateValueSelect( valueFieldId, instanceName, instanceId ) {