Home Information - Your home, your data, organized.
Python
Implement auto-view switching feature for AlertManager integration (#98)
cassandra-ai-agentf88ecf57ee43
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex fb4589f7..d5fb4b9c 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -15,8 +15,8 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co- [ ] Avoid: "π€ Generated with Claude Code" β**Before Creating Pull Request:**-- [ ] `src/manage.py test` (must show "OK")-- [ ] `flake8 --config=src/.flake8-ci src/hi/` (must show no output)+- [ ] `make test` (must show "OK")+- [ ] `make lint` (must show no output)- [ ] Both MUST pass before PR creation**Process Verification Pattern:**@@ -162,11 +162,11 @@ During investigation, if an issue involves **both** design/UX work **and** imple```bash# 1. Run full unit test suite-src/manage.py test+make test# Must show: "OK" with all tests passing# 2. Run code quality check (only if source code was modified)-flake8 --config=src/.flake8-ci src/hi/+make lint# Must show: no output (clean)```@@ -176,8 +176,8 @@ flake8 --config=src/.flake8-ci src/hi/Before any pull request can be merged, the following requirements must be met:-1. **Unit Tests**: All unit tests must pass (`src/manage.py test`)-2. **Code Quality**: flake8 linting with `.flake8-ci` configuration must pass with no violations (if source code modified) (`flake8 --config=src/.flake8-ci src/hi/`)+1. **Unit Tests**: All unit tests must pass (`make test`)+2. **Code Quality**: flake8 linting with `.flake8-ci` configuration must pass with no violations (if source code modified) (`make lint`)3. **GitHub CI**: GitHub Actions will automatically verify these requirements and will block PR merging if they failThese requirements are enforced by GitHub branch protection rules and cannot be bypassed.@@ -296,8 +296,8 @@ For detailed setup and daily commands, see [Development Setup](dev/Setup.md).```bash# Common commands (all run from PROJECT ROOT)-src/manage.py test-flake8 --config=src/.flake8-ci src/hi/+make test # Run unit tests+make lint # Run code quality checkssrc/manage.py runserver # http://127.0.0.1:8411```@@ -350,7 +350,7 @@ All generated code must comply with the `.flake8-ci` configuration rules. Common4. **Line Continuation**: Proper indentation for multi-line statements following PEP 85. **Line Length**: Respect maximum line length limits defined in `.flake8-ci`-Before submitting code, always run: `flake8 --config=src/.flake8-ci src/hi/` to verify compliance.+Before submitting code, always run: `make lint` to verify compliance.## Django Template Guidelines (Claude-Specific)diff --git a/docs/dev/Testing.md b/docs/dev/Testing.mdindex 94264676..d93162f3 100644--- a/docs/dev/Testing.md+++ b/docs/dev/Testing.md@@ -730,9 +730,22 @@ def test_form_validation_errors(self):_TBD_+## Development Data Injection++The development data injection system provides a runtime mechanism to modify application behavior without code changes or Django restarts. This is useful for testing scenarios that would otherwise require complex backend state setup.++**Example use case:** Injecting pre-formatted status responses for UI testing - you can override the `/api/status` endpoint to return specific transient view suggestions, allowing you to test auto-view switching behavior without manipulating the actual backend systems.++**General concept:** Any code location can become an injection point by adding a `DEBUG_FORCE_*` setting and a conditional check. The system supports both one-time and persistent overrides via management commands.++For complete usage details, implementation instructions, and extending to new injection points, see:+```+hi.testing.dev_injection.DevInjectionManager+```+## Visual Testing Page-Visit: [http://127.0.0.1:8411/tests/ui](http://127.0.0.1:8411/tests/ui).+Visit: [http://127.0.0.1:8411/testing/ui](http://127.0.0.1:8411/testing/ui).These tests/ui views are only available in the development environment when `DEBUG=True`. (They are conditionally loaded in the root `urls.py`.)@@ -752,7 +765,7 @@ Then:- Create `tests/ui/views.py`- Create `tests/ui/urls.py` (This gets auto-discovered. Esnure some default home page rule.)-The templates for these tests, by convention, would be put in the app templates directory as `templates/${APPNAME}/tests/ui`. At a minimum, you will probably want a home page `templates/${APPNAME}/tests/ui/home.html` like this:+The templates for these tests, by convention, would be put in the app templates directory as `templates/${APPNAME}/testing/ui`. At a minimum, you will probably want a home page `templates/${APPNAME}/testing/ui/home.html` like this:``` html{% extends "pages/base.html" %}@@ -777,7 +790,7 @@ class Test${APPNAMNE}HomeView( View ):def get(self, request, *args, **kwargs):context = {}- return render(request, "${APPNAME}/tests/ui/home.html", context )+ return render(request, "${APPNAME}/testing/ui/home.html", context )```And in `tests/ui/urls.py`:@@ -798,7 +811,7 @@ urlpatterns = [### UI Testing Framework Guidelines-The visual testing framework at `/tests/ui` is designed for viewing UI styling and layout during development. These are **read-only** views that should never modify system state.+The visual testing framework at `/testing/ui` is designed for viewing UI styling and layout during development. These are **read-only** views that should never modify system state.#### Critical UI Testing Principle: System State Isolationdiff --git a/src/hi/apps/alert/alarm.py b/src/hi/apps/alert/alarm.pyindex 8051a40c..0f0d204f 100644--- a/src/hi/apps/alert/alarm.py+++ b/src/hi/apps/alert/alarm.py@@ -13,6 +13,7 @@ class AlarmSourceDetails:detail_attrs : Dict[ str, str ]image_url : str = None+ sensor_id : int = None # ID of the sensor that generated this alarm@dataclass@@ -36,3 +37,15 @@ class Alarm:@propertydef signature(self):return f'{self.alarm_source}.{self.alarm_type}.{self.alarm_level}'++ def get_view_url(self) -> str:+ """+ Extract a view URL from this alarm's source details.++ Delegates to ViewUrlUtils for the actual URL generation logic.++ Returns:+ A Django view URL string, or None if no view can be determined.+ """+ from hi.apps.console.view_url_utils import ViewUrlUtils+ return ViewUrlUtils.get_view_url_for_alarm(self)diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.pyindex 60065a77..6465c58e 100644--- a/src/hi/apps/alert/alert.py+++ b/src/hi/apps/alert/alert.py@@ -20,6 +20,7 @@ class Alert:self._id = uuid.uuid4().hexself._start_datetime = first_alarm.timestampself._end_datetime = self._start_datetime + timedelta( seconds = first_alarm.alarm_lifetime_secs )+ self._queue_insertion_datetime = None# Prevent unbounded growth and kept in reverse order of arrival, so# most recent alarm is on the left side of list (popleft)@@ -30,6 +31,9 @@ class Alert:self._is_acknowledged = Falsereturn+ def __str__(self):+ return f'{self.alarm_source} : {self.alarm_level} : {self.alarm_type} [{self.start_datetime}, {self._end_datetime}]'+@propertydef id(self) -> str:return self._id@@ -42,6 +46,14 @@ class Alert:def end_datetime(self) -> datetime:return self._end_datetime+ @property+ def queue_insertion_datetime(self) -> datetime:+ return self._queue_insertion_datetime++ @queue_insertion_datetime.setter+ def queue_insertion_datetime(self, value: datetime):+ self._queue_insertion_datetime = value+@propertydef audio_signal(self) -> AudioSignal:return self._first_alarm.audio_signal@@ -136,3 +148,22 @@ class Alert:title = self.title,source_obj = self,)++ def get_view_url(self) -> str:+ """+ Get a view URL associated with this alert if one can be determined.++ This method extracts a relevant view URL from the alert's alarms,+ typically for auto-view switching to show relevant camera feeds or+ other contextual views when alerts occur.++ Returns:+ A Django view URL string, or None if no view can be determined.+ """+ # For now, we'll use the first alarm's view URL+ # In the future, we might have more sophisticated logic for+ # choosing between multiple alarms' views+ if self._first_alarm:+ return self._first_alarm.get_view_url()+ return None+diff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.pyindex 84d92518..0747d60e 100644--- a/src/hi/apps/alert/alert_manager.py+++ b/src/hi/apps/alert/alert_manager.py@@ -2,6 +2,7 @@ from datetime import datetimeimport loggingfrom hi.apps.common.singleton import Singleton+from hi.apps.console.transient_view_manager import TransientViewManagerfrom hi.apps.security.security_mixins import SecurityMixinfrom hi.apps.notify.notify_mixins import NotificationMixin@@ -57,24 +58,18 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):new_alert = self._alert_queue.get_most_important_unacknowledged_alert(since_datetime = last_alert_status_datetime,)- logger.debug(f"π new_alert from queue: {new_alert}")-if new_alert:max_alert = new_alertelse:max_alert = self._alert_queue.get_most_important_unacknowledged_alert()- logger.debug(f"π max_alert from queue: {max_alert}")-- # TODO: Use this latest new alarm for providing auto-switching to- # show something related to the latest event, e.g., camera feed.- # This would be a suggestion to the console as it would decide- # whether to show it based on the console settings and user- # interaction context.- #- _ = self._alert_queue.get_most_recent_alarm(- since_datetime = last_alert_status_datetime,- )+ if new_alert:+ logger.debug(f'New Alert = {new_alert}')++ # Delegate auto-view decisions to TransientViewManager+ # If there's a new alert, consider it for auto-view switching+ if new_alert:+ TransientViewManager().consider_alert_for_auto_view(new_alert)return AlertStatusData(alert_list = self._alert_queue.unacknowledged_alert_list,@@ -110,3 +105,4 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):except Exception as e:logger.exception( 'Problem doing periodic alert maintenance.', e )return+diff --git a/src/hi/apps/alert/alert_queue.py b/src/hi/apps/alert/alert_queue.pyindex 78a0f14a..756ff221 100644--- a/src/hi/apps/alert/alert_queue.py+++ b/src/hi/apps/alert/alert_queue.py@@ -14,6 +14,8 @@ logger = logging.getLogger(__name__)class AlertQueue:MAX_ALERT_LIST_SIZE = 50++ TRACE = False # for debuggingdef __init__(self):self._alert_list = list()@@ -41,7 +43,7 @@ class AlertQueue:def get_most_important_unacknowledged_alert( self, since_datetime : datetime = None ):"""Returns the active alert that has the highest priority and which was- created since the "since_datetime" passed (if any). If there are+ added to the queue since the "since_datetime" passed (if any). If there aremultiple events of the same priority, then an arbitrary one isreturned. Returns None if there are no active alerts in thespecified time frame.@@ -57,7 +59,8 @@ class AlertQueue:for alert in self._alert_list:if alert.is_acknowledged:continue- if alert.start_datetime <= since_datetime:+ # Use queue_insertion_datetime instead of start_datetime for "new alert" detection+ if alert.queue_insertion_datetime is None or alert.queue_insertion_datetime <= since_datetime:continueif max_alert is None:max_alert = alert@@ -111,6 +114,7 @@ class AlertQueue:return alertnew_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}' )@@ -119,6 +123,7 @@ class AlertQueue:returndef acknowledge_alert( self, alert_id : str ):+ logger.debug( f'Acknoweldging alert id: {alert_id}' )with self._active_alerts_lock:for alert in self._alert_list:if alert.id != alert_id:@@ -131,7 +136,8 @@ class AlertQueue:def remove_expired_or_acknowledged_alerts(self):with self._active_alerts_lock:- logger.debug( f'Alert Check: List size = {len(self._alert_list)}')+ if self.TRACE:+ logger.debug( f'Alert Check: List size = {len(self._alert_list)}')if len( self._alert_list ) < 1:returndiff --git a/src/hi/apps/alert/alert_status.py b/src/hi/apps/alert/alert_status.pyindex 91ea6915..fb419db1 100644--- a/src/hi/apps/alert/alert_status.py+++ b/src/hi/apps/alert/alert_status.py@@ -31,25 +31,16 @@ class AlertStatusData:alert_list = self.alert_list,)response_dict = dict()-- logger.debug(f"AlertStatusData.to_dict() - max_audio_signal: {self.max_audio_signal}")- logger.debug(f"AlertStatusData.to_dict() - new_audio_signal: {self.new_audio_signal}")- logger.debug(f"AlertStatusData.to_dict() - alert_list length: {len(self.alert_list) if self.alert_list else 0}")-+if self.max_audio_signal:response_dict[self.MaxAudioSignalNameAttr] = self.max_audio_signal.labellogger.debug(f"Added max_audio_signal: {self.max_audio_signal.label}")- else:- logger.debug("No max_audio_signal to add")if self.new_audio_signal:response_dict[self.NewAudioSignalNameAttr] = self.new_audio_signal.labellogger.debug(f"Added new_audio_signal: {self.new_audio_signal.label}")- else:- logger.debug("No new_audio_signal to add")if self.alert_list:response_dict[self.AlarmMessageHtmlAttr] = alert_list_html_str- logger.debug(f"Final response_dict keys: {list(response_dict.keys())}")return response_dictdiff --git a/src/hi/apps/alert/monitors.py b/src/hi/apps/alert/monitors.pyindex e563dc26..c2087c81 100644--- a/src/hi/apps/alert/monitors.py+++ b/src/hi/apps/alert/monitors.py@@ -11,6 +11,8 @@ class AlertMonitor( PeriodicMonitor, AlertMixin ):ALERT_POLLING_INTERVAL_SECS = 3+ TRACE = False # for debugging+def __init__( self ):super().__init__(id = 'alert-monitor',@@ -19,7 +21,8 @@ class AlertMonitor( PeriodicMonitor, AlertMixin ):returnasync def do_work(self):- logger.debug( 'Checking for alert maintenance work.' )+ if self.TRACE:+ logger.debug( 'Checking for alert maintenance work.' )alert_manager = await self.alert_manager_async()if not alert_manager:returndiff --git a/src/hi/apps/alert/tests/test_alarm.py b/src/hi/apps/alert/tests/test_alarm.pyindex 3ee85caa..933e15aa 100644--- a/src/hi/apps/alert/tests/test_alarm.py+++ b/src/hi/apps/alert/tests/test_alarm.py@@ -5,7 +5,7 @@ from hi.apps.alert.alarm import Alarm, AlarmSourceDetailsfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevel-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/alert/tests/test_alert.py b/src/hi/apps/alert/tests/test_alert.pyindex 060e119c..db8243e3 100644--- a/src/hi/apps/alert/tests/test_alert.py+++ b/src/hi/apps/alert/tests/test_alert.py@@ -6,7 +6,7 @@ from hi.apps.alert.alert import Alertfrom hi.apps.alert.alarm import Alarm, AlarmSourceDetailsfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/alert/tests/test_alert_manager.py b/src/hi/apps/alert/tests/test_alert_manager.pyindex 0e4174a8..f972a063 100644--- a/src/hi/apps/alert/tests/test_alert_manager.py+++ b/src/hi/apps/alert/tests/test_alert_manager.py@@ -5,7 +5,7 @@ from hi.apps.alert.alert_manager import AlertManagerfrom hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/alert/tests/test_alert_manager_delegation.py b/src/hi/apps/alert/tests/test_alert_manager_delegation.pynew file mode 100644index 00000000..8b727011--- /dev/null+++ b/src/hi/apps/alert/tests/test_alert_manager_delegation.py@@ -0,0 +1,279 @@+import logging+from datetime import timedelta+from unittest.mock import Mock, patch++from django.utils import timezone++from hi.apps.alert.alert_manager import AlertManager+from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.console.transient_view_manager import TransientViewManager+from hi.apps.security.enums import SecurityLevel+from hi.testing.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestAlertManagerDelegation(BaseTestCase):+ """Test AlertManager delegation to TransientViewManager for auto-view switching."""++ def setUp(self):+ super().setUp()+ # Reset singletons for test isolation+ AlertManager._instance = None+ TransientViewManager._instance = None++ self.alert_manager = AlertManager()+ self.transient_manager = TransientViewManager()++ # Ensure clean state for TransientViewManager+ self.transient_manager.clear_suggestion()++ def tearDown(self):+ # Clean up after each test+ if hasattr(self, 'transient_manager'):+ self.transient_manager.clear_suggestion()+ TransientViewManager().clear_suggestion()++ # Clear AlertManager state (the AlertQueue)+ if hasattr(self, 'alert_manager'):+ self.alert_manager._alert_queue._alert_list.clear()++ # Reset singletons for next test+ AlertManager._instance = None+ TransientViewManager._instance = None++ super().tearDown()++ def test_alert_manager_delegates_new_alerts_to_transient_view_manager(self):+ """Test AlertManager delegates new alerts to TransientViewManager - core integration."""+ from hi.apps.entity.models import Entity, EntityState+ from hi.apps.entity.enums import EntityStateType+ from hi.apps.sense.models import Sensor++ # Create test data - entity with both motion and video stream sensors+ entity = Entity.objects.create(+ integration_id='test.camera.front_door',+ integration_name='test_integration',+ name='Front Door Camera',+ entity_type_str='camera'+ )++ # Create motion sensor state+ motion_state = EntityState.objects.create(+ entity=entity,+ entity_state_type_str=str(EntityStateType.MOVEMENT),+ name='motion'+ )+ motion_sensor = Sensor.objects.create(+ entity_state=motion_state,+ integration_id='test.motion.front_door',+ integration_name='test_integration',+ name='Motion Sensor'+ )++ # Create video stream sensor state on same entity+ video_state = EntityState.objects.create(+ entity=entity,+ entity_state_type_str=str(EntityStateType.VIDEO_STREAM),+ name='video_stream'+ )+ video_sensor = Sensor.objects.create(+ entity_state=video_state,+ integration_id='test.video.front_door',+ integration_name='test_integration',+ name='Video Stream'+ )++ # Create realistic motion detection alarm with sensor details+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Front Door'},+ image_url=None,+ sensor_id=motion_sensor.id # Motion sensor that triggered the alarm+ )++ motion_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING,+ title='Motion detected at Front Door',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ # Verify no suggestion exists initially+ self.assertFalse(self.transient_manager.has_suggestion())++ # Mock settings to enable auto-view for this test+ with patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:+ mock_helper = Mock()+ mock_helper.get_auto_view_enabled.return_value = True+ mock_helper.get_auto_view_duration.return_value = 30+ mock_helper_class.return_value = mock_helper++ # Add alarm to create an alert+ self.run_async_test(self.alert_manager.add_alarm(motion_alarm))++ # Get alert status data (this should trigger delegation to TransientViewManager)+ self.alert_manager.get_alert_status_data(+ last_alert_status_datetime=timezone.now() - timedelta(seconds=5)+ )++ # Verify delegation created a suggestion (test actual behavior, not mock calls)+ self.assertTrue(self.transient_manager.has_suggestion())++ # Verify the video sensor ID is used in the URL+ suggestion = self.transient_manager.peek_current_suggestion()+ expected_url = f'/console/sensor/video-stream/{video_sensor.id}'+ self.assertEqual(suggestion.url, expected_url)++ def test_alert_manager_no_delegation_when_no_new_alert(self):+ """Test AlertManager doesn't delegate when no new alerts - conditional delegation."""+ # Verify no suggestion exists initially+ self.assertFalse(self.transient_manager.has_suggestion())++ # Get alert status without any alarms being added+ self.alert_manager.get_alert_status_data(+ last_alert_status_datetime=timezone.now() - timedelta(seconds=5)+ )++ # Should still not have any suggestions (no new alerts to delegate)+ self.assertFalse(self.transient_manager.has_suggestion())++ def test_alert_manager_focuses_on_new_alerts_not_queue_state(self):+ """Test AlertManager delegates only new alerts, not existing queue state - precise delegation."""+ from hi.apps.entity.models import Entity, EntityState+ from hi.apps.entity.enums import EntityStateType+ from hi.apps.sense.models import Sensor++ # Create test data for two different cameras+ # First camera entity+ entity1 = Entity.objects.create(+ integration_id='test.camera.one',+ integration_name='test_integration',+ name='Camera One',+ entity_type_str='camera'+ )+ motion_state1 = EntityState.objects.create(+ entity=entity1,+ entity_state_type_str=str(EntityStateType.MOVEMENT),+ name='motion'+ )+ motion_sensor1 = Sensor.objects.create(+ entity_state=motion_state1,+ integration_id='test.motion.one',+ integration_name='test_integration',+ name='Motion Sensor 1'+ )+ # video_state1 and video_sensor1 not needed for this test since we only check video_sensor2++ # Second camera entity+ entity2 = Entity.objects.create(+ integration_id='test.camera.two',+ integration_name='test_integration',+ name='Camera Two',+ entity_type_str='camera'+ )+ motion_state2 = EntityState.objects.create(+ entity=entity2,+ entity_state_type_str=str(EntityStateType.MOVEMENT),+ name='motion'+ )+ motion_sensor2 = Sensor.objects.create(+ entity_state=motion_state2,+ integration_id='test.motion.two',+ integration_name='test_integration',+ name='Motion Sensor 2'+ )+ video_state2 = EntityState.objects.create(+ entity=entity2,+ entity_state_type_str=str(EntityStateType.VIDEO_STREAM),+ name='video_stream'+ )+ video_sensor2 = Sensor.objects.create(+ entity_state=video_state2,+ integration_id='test.video.two',+ integration_name='test_integration',+ name='Video Stream 2'+ )++ # Create two different alarms+ source_details_1 = AlarmSourceDetails(+ detail_attrs={},+ image_url=None,+ sensor_id=motion_sensor1.id # First motion sensor+ )++ source_details_2 = AlarmSourceDetails(+ detail_attrs={},+ image_url=None,+ sensor_id=motion_sensor2.id # Second motion sensor+ )++ # Create alarms with different types to ensure separate alerts+ old_time = timezone.now() - timedelta(seconds=30)+ new_time = timezone.now() - timedelta(seconds=2) # More recent but not now++ old_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.INFO, # Lower priority+ title='Old Motion',+ source_details_list=[source_details_1],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=old_time+ )++ new_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING, # Higher priority, different signature+ title='New Motion',+ source_details_list=[source_details_2],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=new_time+ )++ # Add old alarm first+ self.run_async_test(self.alert_manager.add_alarm(old_alarm))++ # Verify no suggestion exists yet+ self.assertFalse(self.transient_manager.has_suggestion())++ # Add new alarm+ self.run_async_test(self.alert_manager.add_alarm(new_alarm))++ # Mock settings to enable auto-view for this test+ with patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:+ mock_helper = Mock()+ mock_helper.get_auto_view_enabled.return_value = True+ mock_helper.get_auto_view_duration.return_value = 30+ mock_helper_class.return_value = mock_helper++ # Get alert status - should delegate only the new alert+ # Use timestamp that excludes old alarm but includes new one+ self.alert_manager.get_alert_status_data(+ last_alert_status_datetime=timezone.now() - timedelta(seconds=5) # Between old (30s ago) and new (2s ago)+ )++ # Should have created a suggestion based on the new alert only+ self.assertTrue(self.transient_manager.has_suggestion())++ # The suggestion should be based on the new alert's video sensor_id+ suggestion = self.transient_manager.peek_current_suggestion()+ expected_url = f'/console/sensor/video-stream/{video_sensor2.id}'+ self.assertEqual(suggestion.url, expected_url)++ def run_async_test(self, coro):+ """Helper to run async methods in tests."""+ import asyncio+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()diff --git a/src/hi/apps/alert/tests/test_alert_queue.py b/src/hi/apps/alert/tests/test_alert_queue.pyindex 754d1ea9..845994b0 100644--- a/src/hi/apps/alert/tests/test_alert_queue.py+++ b/src/hi/apps/alert/tests/test_alert_queue.py@@ -8,7 +8,7 @@ from hi.apps.alert.alert import Alertfrom hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/alert/tests/test_enums.py b/src/hi/apps/alert/tests/test_enums.pyindex c07b4b4b..ed40d378 100644--- a/src/hi/apps/alert/tests/test_enums.py+++ b/src/hi/apps/alert/tests/test_enums.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.alert.enums import AlarmLevel, AlarmSource, AlertState-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/alert/tests/test_views.py b/src/hi/apps/alert/tests/test_views.pyindex ab8e4546..de24c138 100644--- a/src/hi/apps/alert/tests/test_views.py+++ b/src/hi/apps/alert/tests/test_views.py@@ -6,7 +6,7 @@ from django.utils import timezonefrom hi.apps.alert.alert_manager import AlertManagerfrom hi.apps.alert.alert import Alert-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/api/tests/test_views.py b/src/hi/apps/api/tests/test_views.pyindex f80dc0dc..e83fcebb 100644--- a/src/hi/apps/api/tests/test_views.py+++ b/src/hi/apps/api/tests/test_views.py@@ -3,7 +3,7 @@ from datetime import datetime, timezonefrom django.urls import reverse-from hi.tests.view_test_base import AsyncViewTestCase+from hi.testing.view_test_base import AsyncViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/api/views.py b/src/hi/apps/api/views.pyindex cd3eabda..5f7ab581 100644--- a/src/hi/apps/api/views.py+++ b/src/hi/apps/api/views.py@@ -3,6 +3,7 @@ import hashlibimport jsonimport logging+from django.conf import settingsfrom django.core.exceptions import BadRequestfrom django.http import HttpResponsefrom django.views.generic import View@@ -10,9 +11,11 @@ from django.views.generic import Viewfrom hi.apps.alert.alert_mixins import AlertMixinimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.config.settings_mixins import SettingsMixin+from hi.apps.console.transient_view_manager import TransientViewManagerfrom hi.apps.monitor.status_display_manager import StatusDisplayManagerfrom hi.apps.security.security_mixins import SecurityMixinfrom hi.apps.weather.weather_mixins import WeatherMixin+from hi.testing.dev_injection import DevInjectionManagerlogger = logging.getLogger(__name__)@@ -26,6 +29,11 @@ class StatusView( View, AlertMixin, SecurityMixin, SettingsMixin, WeatherMixin )CssClassUpdateMapAttr = 'cssClassUpdateMap'IdReplaceUpdateMapAttr = 'idReplaceUpdateMap'IdReplaceHashMapAttr = 'idReplaceHashMap'+ TransientViewSuggestionAttr = 'transientViewSuggestion'+ TransientViewUrlAttr = 'url'+ TransientViewDurationSecondsAttr = 'durationSeconds'+ TransientViewPriorityAttr = 'priority'+ TransientViewTriggerReasonAttr = 'triggerReason'def get( self, request, *args, **kwargs ):@@ -65,6 +73,10 @@ class StatusView( View, AlertMixin, SecurityMixin, SettingsMixin, WeatherMixin )id_replace_hash_map[id] = md5_hash.hexdigest()continue+ # Check for transient view suggestions+ transient_view_manager = TransientViewManager()+ suggestion = transient_view_manager.get_current_suggestion()+data = {self.ServerStartTimestampAttr: server_start_datetime.isoformat(),self.ServerTimestampAttr: server_datetime.isoformat(),@@ -73,6 +85,19 @@ class StatusView( View, AlertMixin, SecurityMixin, SettingsMixin, WeatherMixin )self.IdReplaceUpdateMapAttr: id_replace_map,self.IdReplaceHashMapAttr: id_replace_hash_map,}++ if suggestion:+ data[self.TransientViewSuggestionAttr] = {+ self.TransientViewUrlAttr: suggestion.url,+ self.TransientViewDurationSecondsAttr: suggestion.duration_seconds,+ self.TransientViewPriorityAttr: suggestion.priority,+ self.TransientViewTriggerReasonAttr: suggestion.trigger_reason+ }++ # Development testing injection point+ if settings.DEBUG and getattr(settings, 'DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE', False):+ DevInjectionManager.inject_override_if_available('transient_view', data, self.TransientViewSuggestionAttr)+return HttpResponse(json.dumps(data),content_type='application/json',diff --git a/src/hi/apps/attribute/tests/test_enums.py b/src/hi/apps/attribute/tests/test_enums.pyindex 12eca528..7b842b54 100644--- a/src/hi/apps/attribute/tests/test_enums.py+++ b/src/hi/apps/attribute/tests/test_enums.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.attribute.enums import AttributeType, AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/attribute/tests/test_models.py b/src/hi/apps/attribute/tests/test_models.pyindex e8ba3117..e19c2a7f 100644--- a/src/hi/apps/attribute/tests/test_models.py+++ b/src/hi/apps/attribute/tests/test_models.py@@ -6,7 +6,7 @@ from django.core.files.uploadedfile import SimpleUploadedFilefrom hi.apps.attribute.models import AttributeModelfrom hi.apps.attribute.enums import AttributeValueType, AttributeTypefrom hi.integrations.transient_models import IntegrationKey-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/attribute/tests/test_value_ranges.py b/src/hi/apps/attribute/tests/test_value_ranges.pyindex ad663ce7..823cc111 100644--- a/src/hi/apps/attribute/tests/test_value_ranges.py+++ b/src/hi/apps/attribute/tests/test_value_ranges.py@@ -2,7 +2,7 @@ import loggingfrom unittest.mock import patchfrom hi.apps.attribute.value_ranges import PredefinedValueRanges-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/audio/tests/test_audio_file.py b/src/hi/apps/audio/tests/test_audio_file.pyindex e7a1d5fa..476fa8bc 100644--- a/src/hi/apps/audio/tests/test_audio_file.py+++ b/src/hi/apps/audio/tests/test_audio_file.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.audio.audio_file import AudioFile-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/audio/tests/test_audio_manager.py b/src/hi/apps/audio/tests/test_audio_manager.pyindex b90d7a4d..35b003cd 100644--- a/src/hi/apps/audio/tests/test_audio_manager.py+++ b/src/hi/apps/audio/tests/test_audio_manager.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.audio.audio_manager import AudioManager-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/audio/tests/test_audio_signal.py b/src/hi/apps/audio/tests/test_audio_signal.pyindex d6e8a738..49ca872b 100644--- a/src/hi/apps/audio/tests/test_audio_signal.py+++ b/src/hi/apps/audio/tests/test_audio_signal.py@@ -3,7 +3,7 @@ import loggingfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.audio.settings import AudioSetting-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/audio/tests/test_console_audio.py b/src/hi/apps/audio/tests/test_console_audio.pyindex e6cc963a..7f11bbaf 100644--- a/src/hi/apps/audio/tests/test_console_audio.py+++ b/src/hi/apps/audio/tests/test_console_audio.py@@ -3,7 +3,7 @@ import loggingfrom hi.apps.audio.audio_manager import AudioManagerfrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.audio.settings import AudioSetting-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/audio/tests/test_integration.py b/src/hi/apps/audio/tests/test_integration.pyindex 1f1ac990..aa5551a2 100644--- a/src/hi/apps/audio/tests/test_integration.py+++ b/src/hi/apps/audio/tests/test_integration.py@@ -4,7 +4,7 @@ from hi.apps.alert.alarm import Alarm, AlarmSourceDetailsfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevel-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaseimport hi.apps.common.datetimeproxy as datetimeproxydiff --git a/src/hi/apps/audio/tests/test_tornado_audio.py b/src/hi/apps/audio/tests/test_tornado_audio.pyindex ea031814..9458d6d9 100644--- a/src/hi/apps/audio/tests/test_tornado_audio.py+++ b/src/hi/apps/audio/tests/test_tornado_audio.py@@ -5,7 +5,7 @@ from hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevelfrom hi.apps.weather.enums import WeatherEventType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaseimport hi.apps.common.datetimeproxy as datetimeproxydiff --git a/src/hi/apps/audio/tests/test_views.py b/src/hi/apps/audio/tests/test_views.pyindex 1b03cd4f..55fde1c9 100644--- a/src/hi/apps/audio/tests/test_views.py+++ b/src/hi/apps/audio/tests/test_views.py@@ -2,7 +2,7 @@ import loggingfrom django.urls import reverse-from hi.tests.view_test_base import DualModeViewTestCase+from hi.testing.view_test_base import DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/collection/edit/tests/test_views.py b/src/hi/apps/collection/edit/tests/test_views.pyindex f0c71669..9cfc8738 100644--- a/src/hi/apps/collection/edit/tests/test_views.py+++ b/src/hi/apps/collection/edit/tests/test_views.py@@ -9,7 +9,7 @@ from hi.apps.collection.models import Collection, CollectionPositionfrom hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewMode, ViewType-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/collection/tests/test_collection_manager.py b/src/hi/apps/collection/tests/test_collection_manager.pyindex 35371453..19d973db 100644--- a/src/hi/apps/collection/tests/test_collection_manager.py+++ b/src/hi/apps/collection/tests/test_collection_manager.py@@ -7,7 +7,7 @@ from hi.apps.collection.models import Collection, CollectionEntity, CollectionPofrom hi.apps.entity.models import Entityfrom hi.apps.entity.enums import EntityGroupTypefrom hi.apps.location.models import Location, LocationView-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/collection/tests/test_enums.py b/src/hi/apps/collection/tests/test_enums.pyindex f60588c3..5cd1fd2e 100644--- a/src/hi/apps/collection/tests/test_enums.py+++ b/src/hi/apps/collection/tests/test_enums.py@@ -2,7 +2,7 @@ import loggingfrom hi.apps.collection.enums import CollectionType, CollectionViewTypefrom hi.apps.collection.models import Collection-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/collection/tests/test_models.py b/src/hi/apps/collection/tests/test_models.pyindex 408d8dde..b0b92476 100644--- a/src/hi/apps/collection/tests/test_models.py+++ b/src/hi/apps/collection/tests/test_models.py@@ -6,7 +6,7 @@ from hi.apps.collection.enums import CollectionType, CollectionViewTypefrom hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ItemType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/collection/tests/test_views.py b/src/hi/apps/collection/tests/test_views.pyindex fc8f5560..3028c5f7 100644--- a/src/hi/apps/collection/tests/test_views.py+++ b/src/hi/apps/collection/tests/test_views.py@@ -8,7 +8,7 @@ from hi.apps.collection.models import Collectionfrom hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewType-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/config/tests/test_app_settings.py b/src/hi/apps/config/tests/test_app_settings.pyindex f20957a1..d7da298e 100644--- a/src/hi/apps/config/tests/test_app_settings.py+++ b/src/hi/apps/config/tests/test_app_settings.py@@ -4,7 +4,7 @@ from types import ModuleTypefrom hi.apps.config.app_settings import AppSettings, AppSettingDefinitionsfrom hi.apps.config.setting_enums import SettingEnum, SettingDefinitionfrom hi.apps.attribute.enums import AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/config/tests/test_integration.py b/src/hi/apps/config/tests/test_integration.pyindex 50eff3b4..6c0f602c 100644--- a/src/hi/apps/config/tests/test_integration.py+++ b/src/hi/apps/config/tests/test_integration.py@@ -6,7 +6,7 @@ from hi.apps.config.settings_manager import SettingsManagerfrom hi.apps.config.app_settings import AppSettingsfrom hi.apps.config.setting_enums import SettingEnum, SettingDefinitionfrom hi.apps.attribute.enums import AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/config/tests/test_models.py b/src/hi/apps/config/tests/test_models.pyindex 3212b028..8f67fe0a 100644--- a/src/hi/apps/config/tests/test_models.py+++ b/src/hi/apps/config/tests/test_models.py@@ -3,7 +3,7 @@ from django.db import IntegrityErrorfrom hi.apps.config.models import Subsystem, SubsystemAttributefrom hi.apps.attribute.enums import AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/config/tests/test_setting_enums.py b/src/hi/apps/config/tests/test_setting_enums.pyindex d9c4086f..407f81ed 100644--- a/src/hi/apps/config/tests/test_setting_enums.py+++ b/src/hi/apps/config/tests/test_setting_enums.py@@ -2,7 +2,7 @@ import loggingfrom hi.apps.config.setting_enums import SettingEnum, SettingDefinitionfrom hi.apps.attribute.enums import AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/config/tests/test_settings_manager.py b/src/hi/apps/config/tests/test_settings_manager.pyindex 4e812a0b..b1a062e9 100644--- a/src/hi/apps/config/tests/test_settings_manager.py+++ b/src/hi/apps/config/tests/test_settings_manager.py@@ -6,7 +6,7 @@ from hi.apps.config.models import Subsystem, SubsystemAttributefrom hi.apps.config.settings_manager import SettingsManagerfrom hi.apps.config.setting_enums import SettingEnum, SettingDefinitionfrom hi.apps.attribute.enums import AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/config/tests/test_views.py b/src/hi/apps/config/tests/test_views.pyindex df2e86aa..c4a21501 100644--- a/src/hi/apps/config/tests/test_views.py+++ b/src/hi/apps/config/tests/test_views.py@@ -6,7 +6,7 @@ from django.urls import reversefrom hi.apps.config.enums import ConfigPageTypefrom hi.apps.config.models import Subsystem, SubsystemAttributefrom hi.enums import ViewType, ViewMode-from hi.tests.view_test_base import DualModeViewTestCase, SyncViewTestCase+from hi.testing.view_test_base import DualModeViewTestCase, SyncViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/console/console_helper.py b/src/hi/apps/console/console_helper.pyindex 1fa2806d..b961d026 100644--- a/src/hi/apps/console/console_helper.py+++ b/src/hi/apps/console/console_helper.py@@ -61,3 +61,9 @@ class ConsoleSettingsHelper( Singleton, SettingsMixin ):display_units_str = self.settings_manager().get_setting_value( ConsoleSetting.DISPLAY_UNITS )return DisplayUnits.from_name_safe( display_units_str )+ def get_auto_view_enabled( self ) -> bool:+ return self.settings_manager().get_setting_value( ConsoleSetting.AUTO_VIEW_ENABLED ) == 'true'++ def get_auto_view_duration( self ) -> int:+ return int( self.settings_manager().get_setting_value( ConsoleSetting.AUTO_VIEW_DURATION ) )+diff --git a/src/hi/apps/console/settings.py b/src/hi/apps/console/settings.pyindex 8ab27d4f..75906d45 100644--- a/src/hi/apps/console/settings.py+++ b/src/hi/apps/console/settings.py@@ -68,4 +68,22 @@ class ConsoleSetting( SettingEnum ):is_required = True,initial_value = '0.95',)+ AUTO_VIEW_ENABLED = SettingDefinition(+ label = 'Auto View Switching',+ description = 'Enable automatic view switching for alerts',+ value_type = AttributeValueType.BOOLEAN,+ value_range_str = '',+ is_editable = True,+ is_required = True,+ initial_value = 'true',+ )+ AUTO_VIEW_DURATION = SettingDefinition(+ label = 'Auto View Duration (seconds)',+ description = 'How long to show auto-switched view before reverting',+ value_type = AttributeValueType.INTEGER,+ value_range_str = '',+ is_editable = True,+ is_required = True,+ initial_value = '30',+ )diff --git a/src/hi/apps/console/tests/test_console_manager.py b/src/hi/apps/console/tests/test_console_manager.pyindex ba25becf..80005c1f 100644--- a/src/hi/apps/console/tests/test_console_manager.py+++ b/src/hi/apps/console/tests/test_console_manager.py@@ -4,7 +4,7 @@ from unittest.mock import Mock, patchfrom hi.apps.console.console_manager import ConsoleManagerfrom hi.apps.console.transient_models import VideoStreamEntityfrom hi.apps.entity.enums import EntityStateType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/console/tests/test_enums.py b/src/hi/apps/console/tests/test_enums.pyindex fac4d9ab..429124a3 100644--- a/src/hi/apps/console/tests/test_enums.py+++ b/src/hi/apps/console/tests/test_enums.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.console.enums import Theme, DisplayUnits-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/console/tests/test_transient_models.py b/src/hi/apps/console/tests/test_transient_models.pyindex 1aa64307..c3011c1e 100644--- a/src/hi/apps/console/tests/test_transient_models.py+++ b/src/hi/apps/console/tests/test_transient_models.py@@ -3,7 +3,7 @@ from unittest.mock import Mockfrom hi.apps.console.transient_models import VideoStreamEntityfrom hi.apps.entity.enums import EntityStateType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/console/tests/test_transient_view_manager.py b/src/hi/apps/console/tests/test_transient_view_manager.pynew file mode 100644index 00000000..b0f61a1d--- /dev/null+++ b/src/hi/apps/console/tests/test_transient_view_manager.py@@ -0,0 +1,330 @@+import logging+from unittest.mock import Mock, patch++from hi.apps.console.transient_view_manager import TransientViewManager+from hi.testing.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestTransientViewManager(BaseTestCase):++ def setUp(self):+ super().setUp()+ # Reset singleton state for each test+ TransientViewManager._instance = None+ self.manager = TransientViewManager()++ def tearDown(self):+ # Clear any suggestions between tests+ self.manager.clear_suggestion()+ # Reset singleton for next test+ TransientViewManager._instance = None+ super().tearDown()++ def test_transient_view_manager_singleton_behavior(self):+ """Test TransientViewManager singleton pattern - critical for system consistency."""+ manager1 = TransientViewManager()+ manager2 = TransientViewManager()++ self.assertIs(manager1, manager2)+ return++ def test_priority_based_replacement_business_logic(self):+ """Test priority-based suggestion replacement - critical business logic for alert prioritization."""+ # Simulate realistic scenario: motion detection followed by critical alarm++ # Low priority motion detection from secondary camera+ self.manager.suggest_view_change(+ url='/console/sensor/backyard/video',+ duration_seconds=30,+ priority=10, # Low priority+ trigger_reason='motion_detection_backyard'+ )++ initial_suggestion = self.manager.peek_current_suggestion()+ self.assertEqual(initial_suggestion.url, '/console/sensor/backyard/video')++ # High priority motion detection from front door (security concern)+ self.manager.suggest_view_change(+ url='/console/sensor/frontdoor/video',+ duration_seconds=45,+ priority=100, # High priority security event+ trigger_reason='motion_detection_entrance'+ )++ # Should replace with higher priority+ current_suggestion = self.manager.peek_current_suggestion()+ self.assertEqual(current_suggestion.url, '/console/sensor/frontdoor/video')+ self.assertEqual(current_suggestion.priority, 100)++ # Lower priority subsequent event should be ignored+ self.manager.suggest_view_change(+ url='/console/sensor/garage/video',+ duration_seconds=30,+ priority=50, # Medium priority, but lower than current+ trigger_reason='motion_detection_garage'+ )++ # Should still have high priority front door suggestion+ final_suggestion = self.manager.peek_current_suggestion()+ self.assertEqual(final_suggestion.url, '/console/sensor/frontdoor/video')+ self.assertEqual(final_suggestion.priority, 100)+ return++ def test_equal_priority_replacement_for_newer_events(self):+ """Test equal priority replacement - ensures newer events of same importance are shown."""+ # Realistic scenario: Multiple motion events of same priority+ # User should see the most recent one++ self.manager.suggest_view_change(+ url='/console/sensor/zone1/video',+ duration_seconds=30,+ priority=50,+ trigger_reason='motion_zone1'+ )++ # Same priority event from different zone+ self.manager.suggest_view_change(+ url='/console/sensor/zone2/video',+ duration_seconds=30,+ priority=50, # Same priority+ trigger_reason='motion_zone2'+ )++ # Should have the newer suggestion+ suggestion = self.manager.peek_current_suggestion()+ self.assertEqual(suggestion.url, '/console/sensor/zone2/video')+ self.assertEqual(suggestion.trigger_reason, 'motion_zone2')+ return++ def test_get_and_clear_pattern_for_api_consumption(self):+ """Test get_current_suggestion consumption pattern - critical for API endpoint behavior."""+ # This simulates how the API status endpoint consumes suggestions++ self.manager.suggest_view_change(+ url='/console/sensor/123/video',+ duration_seconds=30,+ priority=75,+ trigger_reason='motion_alarm'+ )++ # First API call gets the suggestion+ suggestion = self.manager.get_current_suggestion()+ self.assertIsNotNone(suggestion)+ self.assertEqual(suggestion.url, '/console/sensor/123/video')++ # Subsequent API calls should get None (suggestion consumed)+ next_suggestion = self.manager.get_current_suggestion()+ self.assertIsNone(next_suggestion)++ # This prevents the same suggestion from being sent multiple times+ self.assertFalse(self.manager.has_suggestion())+ return++ def test_consider_alert_with_auto_view_enabled(self):+ """Test TransientViewManager considers alerts when auto-view enabled - core business logic."""+ from django.utils import timezone+ from hi.apps.alert.alert import Alert+ from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel+ from hi.apps.entity.models import Entity, EntityState+ from hi.apps.entity.enums import EntityStateType+ from hi.apps.sense.models import Sensor++ # Create test data - entity with both motion and video stream sensors+ entity = Entity.objects.create(+ integration_id='test.camera.front_door',+ integration_name='test_integration',+ name='Front Door Camera',+ entity_type_str='camera'+ )++ # Create motion sensor state+ motion_state = EntityState.objects.create(+ entity=entity,+ entity_state_type_str=str(EntityStateType.MOVEMENT),+ name='motion'+ )+ motion_sensor = Sensor.objects.create(+ entity_state=motion_state,+ integration_id='test.motion.front_door',+ integration_name='test_integration',+ name='Motion Sensor'+ )++ # Create video stream sensor state on same entity+ video_state = EntityState.objects.create(+ entity=entity,+ entity_state_type_str=str(EntityStateType.VIDEO_STREAM),+ name='video_stream'+ )+ video_sensor = Sensor.objects.create(+ entity_state=video_state,+ integration_id='test.video.front_door',+ integration_name='test_integration',+ name='Video Stream'+ )++ # Create motion detection alert with motion sensor+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Front Door'},+ image_url=None,+ sensor_id=motion_sensor.id # Motion sensor that triggered the alarm+ )++ motion_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING,+ title='Motion detected at Front Door',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ alert = Alert(motion_alarm)++ # Mock settings to enable auto-view+ with patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:+ mock_helper = Mock()+ mock_helper.get_auto_view_enabled.return_value = True+ mock_helper.get_auto_view_duration.return_value = 30+ mock_helper_class.return_value = mock_helper++ # Mock URL generation at system boundary+ # Initially no suggestion+ self.assertFalse(self.manager.has_suggestion())++ # Consider alert for auto-view+ self.manager.consider_alert_for_auto_view(alert)++ # Should create suggestion with video sensor URL (not motion sensor)+ self.assertTrue(self.manager.has_suggestion())+ suggestion = self.manager.peek_current_suggestion()+ expected_url = f'/console/sensor/video-stream/{video_sensor.id}'+ self.assertEqual(suggestion.url, expected_url)+ self.assertEqual(suggestion.duration_seconds, 30)+ self.assertEqual(suggestion.priority, motion_alarm.alarm_level.priority)+ self.assertEqual(suggestion.trigger_reason, 'event_alert')++ def test_consider_alert_with_auto_view_disabled(self):+ """Test TransientViewManager ignores alerts when auto-view disabled - settings integration."""+ from django.utils import timezone+ from hi.apps.alert.alert import Alert+ from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel++ # Create motion detection alert+ source_details = AlarmSourceDetails(+ detail_attrs={},+ image_url=None,+ sensor_id='cam_123'+ )++ motion_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING,+ title='Motion detected',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ alert = Alert(motion_alarm)++ # Mock settings to disable auto-view+ with patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:+ mock_helper = Mock()+ mock_helper.get_auto_view_enabled.return_value = False+ mock_helper_class.return_value = mock_helper++ # Consider alert for auto-view+ self.manager.consider_alert_for_auto_view(alert)++ # Should not create suggestion when disabled+ self.assertFalse(self.manager.has_suggestion())++ def test_consider_non_motion_alert_ignored(self):+ """Test TransientViewManager handles alerts without camera view URLs - integration test."""+ from django.utils import timezone+ from hi.apps.alert.alert import Alert+ from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel++ # Create non-motion EVENT alarm+ source_details = AlarmSourceDetails(+ detail_attrs={},+ image_url=None,+ sensor_id='cam_123'+ )++ status_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='device_status', # Not motion-related+ alarm_level=AlarmLevel.INFO,+ title='Device status update',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ alert = Alert(status_alarm)++ # Mock settings to enable auto-view+ with patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:+ mock_helper = Mock()+ mock_helper.get_auto_view_enabled.return_value = True+ mock_helper_class.return_value = mock_helper++ # Consider alert for auto-view+ self.manager.consider_alert_for_auto_view(alert)++ # Should not create suggestion for non-motion events+ self.assertFalse(self.manager.has_suggestion())++ def test_consider_alert_without_view_url_ignored(self):+ """Test TransientViewManager ignores alerts without view URLs - integration with Alert model."""+ from django.utils import timezone+ from hi.apps.alert.alert import Alert+ from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel++ # Create motion alarm but without sensor_id (no view URL)+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Front Door'}, # No sensor_id+ image_url=None+ )++ motion_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING,+ title='Motion detected',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ alert = Alert(motion_alarm)++ # Mock settings to enable auto-view+ with patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:+ mock_helper = Mock()+ mock_helper.get_auto_view_enabled.return_value = True+ mock_helper_class.return_value = mock_helper++ # Consider alert for auto-view+ self.manager.consider_alert_for_auto_view(alert)++ # Should not create suggestion when no view URL available+ self.assertFalse(self.manager.has_suggestion())diff --git a/src/hi/apps/console/tests/test_view_url_utils.py b/src/hi/apps/console/tests/test_view_url_utils.pynew file mode 100644index 00000000..83be8618--- /dev/null+++ b/src/hi/apps/console/tests/test_view_url_utils.py@@ -0,0 +1,255 @@+import logging+from unittest.mock import patch++from django.utils import timezone++from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.console.view_url_utils import ViewUrlUtils+from hi.apps.entity.models import Entity, EntityState+from hi.apps.entity.enums import EntityStateType+from hi.apps.security.enums import SecurityLevel+from hi.apps.sense.models import Sensor+from hi.apps.sense.enums import SensorType+from hi.testing.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestViewUrlUtils(BaseTestCase):+ """Test ViewUrlUtils with proper database setup."""++ def setUp(self):+ """Set up test data with proper entity/sensor relationships."""+ super().setUp()++ # Create an entity (e.g., a camera)+ self.camera_entity = Entity.objects.create(+ name='Front Door Camera',+ entity_type_str='CAMERA'+ )++ # Create entity states for the camera+ self.motion_entity_state = EntityState.objects.create(+ entity=self.camera_entity,+ entity_state_type=EntityStateType.MOVEMENT,+ name='Motion Detection'+ )++ self.video_stream_entity_state = EntityState.objects.create(+ entity=self.camera_entity,+ entity_state_type=EntityStateType.VIDEO_STREAM,+ name='Video Stream'+ )++ # Create sensors+ self.motion_sensor = Sensor.objects.create(+ name='Motion Sensor',+ entity_state=self.motion_entity_state,+ sensor_type_str=str(SensorType.DEFAULT),+ integration_id='zm_motion_1',+ integration_name='zoneminder'+ )++ self.video_sensor = Sensor.objects.create(+ name='Video Stream Sensor',+ entity_state=self.video_stream_entity_state,+ sensor_type_str=str(SensorType.DEFAULT),+ integration_id='zm_video_1',+ integration_name='zoneminder'+ )++ def test_motion_sensor_with_video_stream_generates_url(self):+ """Test that a motion sensor on entity with video stream generates camera URL."""+ # Create alarm with motion sensor+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Front Door'},+ image_url=None,+ sensor_id=self.motion_sensor.id+ )++ alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING,+ title='Motion detected at Front Door',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)++ # Should return URL with video sensor ID (not motion sensor ID)+ self.assertEqual(view_url, f'/console/sensor/video-stream/{self.video_sensor.id}')++ def test_video_sensor_generates_url(self):+ """Test that a video stream sensor generates camera URL."""+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Front Door'},+ image_url=None,+ sensor_id=self.video_sensor.id+ )++ alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='video_issue',+ alarm_level=AlarmLevel.INFO,+ title='Video stream issue',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)++ # Should return the actual URL generated by Django's reverse()+ self.assertEqual(view_url, f'/console/sensor/video-stream/{self.video_sensor.id}')++ def test_sensor_without_video_stream_returns_none(self):+ """Test that sensor on entity without video stream returns None."""+ # Create entity without video stream+ thermostat_entity = Entity.objects.create(+ name='Living Room Thermostat',+ entity_type_str='THERMOSTAT'+ )++ temp_entity_state = EntityState.objects.create(+ entity=thermostat_entity,+ entity_state_type=EntityStateType.TEMPERATURE,+ name='Temperature Reading'+ )++ temp_sensor = Sensor.objects.create(+ name='Temperature Sensor',+ entity_state=temp_entity_state,+ sensor_type_str=str(SensorType.DEFAULT),+ integration_id='hass_temp_1',+ integration_name='homeassistant'+ )++ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Living Room'},+ image_url=None,+ sensor_id=temp_sensor.id+ )++ alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='temperature_alert',+ alarm_level=AlarmLevel.WARNING,+ title='High temperature',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)+ self.assertIsNone(view_url)++ def test_nonexistent_sensor_returns_none(self):+ """Test that non-existent sensor ID returns None."""+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Somewhere'},+ image_url=None,+ sensor_id='99999' # Non-existent sensor+ )++ alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='unknown',+ alarm_level=AlarmLevel.WARNING,+ title='Unknown alert',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)+ self.assertIsNone(view_url)++ def test_alarm_without_sensor_id_returns_none(self):+ """Test that alarm without sensor_id returns None."""+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Somewhere'},+ image_url=None,+ sensor_id=None+ )++ alarm = Alarm(+ alarm_source=AlarmSource.WEATHER,+ alarm_type='tornado_warning',+ alarm_level=AlarmLevel.CRITICAL,+ title='Tornado Warning',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=1800,+ timestamp=timezone.now()+ )++ view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)+ self.assertIsNone(view_url)++ def test_multiple_source_details_uses_first_valid_sensor(self):+ """Test that first valid sensor_id is used when multiple source details exist."""+ # First source detail without sensor_id+ source_details_1 = AlarmSourceDetails(+ detail_attrs={'location': 'Area A'},+ image_url=None,+ sensor_id=None+ )++ # Second source detail with sensor_id+ source_details_2 = AlarmSourceDetails(+ detail_attrs={'location': 'Area B'},+ image_url=None,+ sensor_id=self.motion_sensor.id+ )++ alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING,+ title='Motion detected',+ source_details_list=[source_details_1, source_details_2],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)++ # Should return URL with video sensor ID (not motion sensor ID)+ self.assertEqual(view_url, f'/console/sensor/video-stream/{self.video_sensor.id}')++ def test_url_generation_exception_handling(self):+ """Test graceful handling of URL generation failures."""+ source_details = AlarmSourceDetails(+ detail_attrs={'location': 'Front Door'},+ image_url=None,+ sensor_id=self.motion_sensor.id+ )++ alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='motion_detection',+ alarm_level=AlarmLevel.WARNING,+ title='Motion detected',+ source_details_list=[source_details],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=300,+ timestamp=timezone.now()+ )++ # Test with a broken URL pattern name to trigger exception handling+ with patch('hi.apps.console.view_url_utils.reverse') as mock_reverse:+ mock_reverse.side_effect = Exception("URL pattern not found")++ view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)++ # Test error handling behavior: should return None on failure+ self.assertIsNone(view_url)diff --git a/src/hi/apps/console/tests/test_views.py b/src/hi/apps/console/tests/test_views.pyindex 499854d2..8eade668 100644--- a/src/hi/apps/console/tests/test_views.py+++ b/src/hi/apps/console/tests/test_views.py@@ -8,7 +8,7 @@ from hi.apps.console.constants import ConsoleConstantsfrom hi.apps.sense.models import Sensorfrom hi.apps.sense.sensor_response_manager import SensorResponseManagerfrom hi.enums import ViewType-from hi.tests.view_test_base import DualModeViewTestCase, SyncViewTestCase+from hi.testing.view_test_base import DualModeViewTestCase, SyncViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/console/transient_models.py b/src/hi/apps/console/transient_models.pyindex 5bd90627..c6b0aa46 100644--- a/src/hi/apps/console/transient_models.py+++ b/src/hi/apps/console/transient_models.py@@ -1,4 +1,5 @@from dataclasses import dataclass+from datetime import datetimefrom typing import Optionalfrom hi.apps.entity.enums import EntityStateType@@ -29,3 +30,20 @@ class VideoStreamEntity:if entity_state.entity_state_type == EntityStateType.MOVEMENT:return entity_statereturn None+++@dataclass+class TransientViewSuggestion:+ """+ Data container for transient view change suggestions.+ Contains URL and metadata for automatic view switching.+ """+ url: str+ duration_seconds: int+ priority: int = 0+ trigger_reason: str = ""+ timestamp: Optional[datetime] = None++ def __post_init__(self):+ if self.timestamp is None:+ self.timestamp = datetime.now()diff --git a/src/hi/apps/console/transient_view_manager.py b/src/hi/apps/console/transient_view_manager.pynew file mode 100644index 00000000..a942c8f4--- /dev/null+++ b/src/hi/apps/console/transient_view_manager.py@@ -0,0 +1,158 @@+import logging+from typing import Optional++from hi.apps.common.singleton import Singleton++from .transient_models import TransientViewSuggestion+from .console_helper import ConsoleSettingsHelper++logger = logging.getLogger(__name__)+++class TransientViewManager(Singleton):+ """+ Singleton class managing view change suggestions from various modules.+ Stores current suggestion in memory with metadata and provides API for modules to suggest view changes.+ """++ def __init_singleton__(self):+ self._current_suggestion: Optional[TransientViewSuggestion] = None+ logger.debug("TransientViewManager initialized")++ def suggest_view_change(self, url: str, duration_seconds: int,+ priority: int = 0, trigger_reason: str = ""):+ """+ Register a suggestion for transient view change.++ Args:+ url: The URL to navigate to (must point to a view that subclasses HiGridView)+ duration_seconds: How long to show the view before reverting+ priority: Priority level (higher numbers = higher priority)+ trigger_reason: Description of what triggered this suggestion+ """+ suggestion = TransientViewSuggestion(+ url=url,+ duration_seconds=duration_seconds,+ priority=priority,+ trigger_reason=trigger_reason+ )++ # Only replace current suggestion if new one has higher priority+ # or if there's no current suggestion+ if (self._current_suggestion is None+ or suggestion.priority >= self._current_suggestion.priority):+ self._current_suggestion = suggestion+ logger.info(f"New transient view suggestion: {url} for {duration_seconds}s "+ f"(reason: {trigger_reason}, priority: {priority})")+ else:+ logger.debug(f"Ignoring lower priority suggestion: {url} "+ f"(priority {priority} vs current {self._current_suggestion.priority})")++ def get_current_suggestion(self) -> Optional[TransientViewSuggestion]:+ """+ Get and clear current suggestion.++ Returns:+ Current suggestion if one exists, None otherwise.+ The suggestion is cleared after being retrieved.+ """+ suggestion = self._current_suggestion+ if suggestion:+ logger.debug(f"Retrieving and clearing suggestion: {suggestion.url}")+ self._current_suggestion = None+ return suggestion++ def clear_suggestion(self):+ """Clear current suggestion without returning it."""+ if self._current_suggestion:+ logger.debug(f"Clearing suggestion: {self._current_suggestion.url}")+ self._current_suggestion = None++ def has_suggestion(self) -> bool:+ """Check if there's a current suggestion."""+ return self._current_suggestion is not None++ def peek_current_suggestion(self) -> Optional[TransientViewSuggestion]:+ """+ Get current suggestion without clearing it.++ Returns:+ Current suggestion if one exists, None otherwise.+ The suggestion is NOT cleared.+ """+ return self._current_suggestion++ def consider_alert_for_auto_view(self, alert):+ """+ Evaluate whether the given alert should trigger an auto-view suggestion.++ This is the main entry point for auto-view decision making.+ It encapsulates all the business logic about when and how to suggest+ view changes based on alerts.++ Args:+ alert: The Alert object to evaluate+ """+ # Check if auto-view is enabled in user settings+ if not self._is_auto_view_enabled():+ logger.debug("Auto-view is disabled in settings")+ return++ # Check if this alert should trigger auto-view+ if not self._should_alert_trigger_auto_view(alert):+ logger.debug(f"Alert {alert.signature} should not trigger auto-view")+ return++ # Try to get a view URL for this alert+ view_url = alert.get_view_url()+ if not view_url:+ logger.debug(f"No view URL available for alert {alert.signature}")+ return++ # Create the suggestion+ console_helper = ConsoleSettingsHelper()+ duration_seconds = console_helper.get_auto_view_duration()+ priority = alert.alert_priority # Use the alert's priority++ self.suggest_view_change(+ url=view_url,+ duration_seconds=duration_seconds,+ priority=priority,+ trigger_reason=f"{alert.alarm_source.name.lower()}_alert"+ )++ logger.info(f"Created auto-view suggestion for alert {alert.signature}")++ def _is_auto_view_enabled(self) -> bool:+ """Check if auto-view switching is enabled in console settings."""+ console_helper = ConsoleSettingsHelper()+ return console_helper.get_auto_view_enabled()++ def _should_alert_trigger_auto_view(self, alert) -> bool:+ """+ Determine if an alert should trigger auto-view suggestion.++ By design, any alert that reaches this point has already been filtered+ by the event subsystem according to user-defined rules. Therefore, we+ consider all alerts as candidates for auto-view switching, subject only+ to configuration settings and having a valid view URL.++ Args:+ alert: The Alert object to evaluate++ Returns:+ True if this alert should trigger auto-view, False otherwise+ """+ # All alerts that reach this point are considered valid for auto-view+ # The event subsystem has already done the filtering based on user rules+ # We just need to verify the alert has the necessary data++ first_alarm = alert.first_alarm+ if not first_alarm:+ logger.debug("Alert has no first_alarm, cannot trigger auto-view")+ return False++ # Any alert with proper alarm data can trigger auto-view+ # The actual view URL availability will be checked separately+ logger.debug(f"Alert {alert.signature} is eligible for auto-view")+ return Truediff --git a/src/hi/apps/console/view_url_utils.py b/src/hi/apps/console/view_url_utils.pynew file mode 100644index 00000000..7c649075--- /dev/null+++ b/src/hi/apps/console/view_url_utils.py@@ -0,0 +1,114 @@+import logging+from typing import Optional++from django.urls import reverse++from hi.apps.sense.models import Sensor+from hi.apps.entity.enums import EntityStateType++logger = logging.getLogger(__name__)+++class ViewUrlUtils:+ """+ Utility class for generating view URLs based on alarm/sensor data.++ This utility encapsulates the logic for determining what view should be shown+ for a given alarm, taking into account the sensor types, entity relationships,+ and available views in the system.+ """++ @staticmethod+ def get_view_url_for_alarm(alarm) -> Optional[str]:+ """+ Generate a view URL for the given alarm.++ This method examines the alarm's source details to find sensor information+ and determines the most appropriate view URL based on the sensor's+ associated entity state types.++ Args:+ alarm: The Alarm object to generate a view URL for++ Returns:+ A Django view URL string, or None if no appropriate view can be determined+ """+ # Look through all source details for sensor information+ for source_details in alarm.source_details_list:+ if source_details.sensor_id:+ view_url = ViewUrlUtils._get_view_url_for_sensor_id(source_details.sensor_id)+ if view_url:+ return view_url++ logger.debug(f"No view URL found for alarm: {alarm.alarm_type} from {alarm.alarm_source}")+ return None++ @staticmethod+ def _get_view_url_for_sensor_id(sensor_id: str) -> Optional[str]:+ """+ Generate a view URL for the given sensor ID.++ This method looks up the sensor and examines its entity state to determine+ what type of view is appropriate.++ Args:+ sensor_id: The ID of the sensor++ Returns:+ A Django view URL string, or None if no appropriate view found+ """+ try:+ # Look up the sensor+ sensor = Sensor.objects.select_related('entity_state').get(id=sensor_id)++ # Find the video stream sensor for this entity+ video_stream_sensor = ViewUrlUtils._get_video_stream_sensor(sensor)+ if video_stream_sensor:+ # Use the video stream sensor's ID, not the original sensor's ID+ return reverse('console_sensor_video_stream', kwargs={'sensor_id': video_stream_sensor.id})++ # Future: Add other view types based on entity state type+ # elif sensor.entity_state.entity_state_type == EntityStateType.WEATHER:+ # return reverse('console_weather_view', kwargs={'sensor_id': sensor_id})++ logger.debug(f"Sensor {sensor_id} ({sensor.entity_state.entity_state_type}) "+ f"does not have an associated view")+ return None++ except Sensor.DoesNotExist:+ logger.warning(f"Sensor {sensor_id} not found")+ return None+ except Exception as e:+ logger.warning(f"Could not generate view URL for sensor {sensor_id}: {e}")+ return None++ @staticmethod+ def _get_video_stream_sensor(sensor: Sensor) -> Optional[Sensor]:+ """+ Get the video stream sensor associated with the given sensor's entity.++ This finds the video stream sensor that belongs to the same entity+ as the given sensor (e.g., finding the video stream sensor when+ given a motion detection sensor from the same camera entity).++ Args:+ sensor: The Sensor object to check++ Returns:+ The video stream Sensor if one exists, None otherwise+ """+ # Get the entity this sensor belongs to+ entity = sensor.entity_state.entity++ # Look for video stream entity states on the same entity+ video_stream_states = entity.states.filter(+ entity_state_type_str=str(EntityStateType.VIDEO_STREAM)+ ).prefetch_related('sensors')++ # Return the first video stream sensor found+ for state in video_stream_states:+ sensors = state.sensors.all()+ if sensors:+ return sensors.first()++ return Nonediff --git a/src/hi/apps/control/tests/test_controller_history_manager.py b/src/hi/apps/control/tests/test_controller_history_manager.pyindex 46d0fe8b..5228e469 100644--- a/src/hi/apps/control/tests/test_controller_history_manager.py+++ b/src/hi/apps/control/tests/test_controller_history_manager.py@@ -3,7 +3,7 @@ import loggingfrom hi.apps.control.controller_history_manager import ControllerHistoryManagerfrom hi.apps.control.models import Controller, ControllerHistoryfrom hi.apps.entity.models import Entity, EntityState, EntityStateDelegation-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/control/tests/test_controller_manager.py b/src/hi/apps/control/tests/test_controller_manager.pyindex b6f0ef47..4fa155a8 100644--- a/src/hi/apps/control/tests/test_controller_manager.py+++ b/src/hi/apps/control/tests/test_controller_manager.py@@ -6,7 +6,7 @@ from hi.apps.control.controller_manager import ControllerManagerfrom hi.apps.control.models import Controllerfrom hi.apps.entity.models import Entity, EntityStatefrom hi.integrations.transient_models import IntegrationControlResult-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/control/tests/test_enums.py b/src/hi/apps/control/tests/test_enums.pyindex 6c3093a4..431907f4 100644--- a/src/hi/apps/control/tests/test_enums.py+++ b/src/hi/apps/control/tests/test_enums.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.control.enums import ControllerType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/control/tests/test_models.py b/src/hi/apps/control/tests/test_models.pyindex 1363c837..31446b16 100644--- a/src/hi/apps/control/tests/test_models.py+++ b/src/hi/apps/control/tests/test_models.py@@ -4,7 +4,7 @@ from django.db import IntegrityErrorfrom hi.apps.control.models import Controller, ControllerHistoryfrom hi.apps.control.enums import ControllerTypefrom hi.apps.entity.models import Entity, EntityState-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/control/tests/test_transient_models.py b/src/hi/apps/control/tests/test_transient_models.pyindex 73b1db6f..60fae8d1 100644--- a/src/hi/apps/control/tests/test_transient_models.py+++ b/src/hi/apps/control/tests/test_transient_models.py@@ -5,7 +5,7 @@ from hi.apps.control.transient_models import ControllerDatafrom hi.apps.control.models import Controllerfrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.sense.transient_models import SensorResponse-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/control/tests/test_views.py b/src/hi/apps/control/tests/test_views.pyindex 4b19260b..e22942ba 100644--- a/src/hi/apps/control/tests/test_views.py+++ b/src/hi/apps/control/tests/test_views.py@@ -9,7 +9,7 @@ from hi.apps.control.models import Controller, ControllerHistoryfrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.entity.enums import EntityStateType, EntityStateValuefrom hi.apps.monitor.status_display_manager import StatusDisplayManager-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/edit/tests/test_views.py b/src/hi/apps/edit/tests/test_views.pyindex a0ede168..dcab82be 100644--- a/src/hi/apps/edit/tests/test_views.py+++ b/src/hi/apps/edit/tests/test_views.py@@ -8,7 +8,7 @@ from hi.apps.control.models import Controllerfrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewMode, ViewType-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/entity/edit/tests/test_views.py b/src/hi/apps/entity/edit/tests/test_views.pyindex 2fc771e6..1d81dd94 100644--- a/src/hi/apps/entity/edit/tests/test_views.py+++ b/src/hi/apps/entity/edit/tests/test_views.py@@ -12,7 +12,7 @@ from hi.apps.entity.models import Entity, EntityPositionfrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewMode, ViewType-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/entity/tests/test_entity_manager.py b/src/hi/apps/entity/tests/test_entity_manager.pyindex 244a76a5..d1381cf6 100644--- a/src/hi/apps/entity/tests/test_entity_manager.py+++ b/src/hi/apps/entity/tests/test_entity_manager.py@@ -5,7 +5,7 @@ from unittest.mock import Mockfrom hi.apps.entity.entity_manager import EntityManagerfrom hi.apps.entity.models import Entity, EntityPath, EntityPositionfrom hi.apps.entity.enums import EntityGroupType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/entity/tests/test_enums.py b/src/hi/apps/entity/tests/test_enums.pyindex 585d4cee..8811fa17 100644--- a/src/hi/apps/entity/tests/test_enums.py+++ b/src/hi/apps/entity/tests/test_enums.py@@ -6,7 +6,7 @@ from hi.apps.entity.enums import (EntityStateValue,EntityGroupType,)-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.pyindex 456faebc..2eaac150 100644--- a/src/hi/apps/entity/tests/test_models.py+++ b/src/hi/apps/entity/tests/test_models.py@@ -5,7 +5,7 @@ from django.db import IntegrityErrorfrom hi.apps.entity.models import Entity, EntityAttribute, EntityStatefrom hi.apps.entity.enums import EntityType, EntityStateTypefrom hi.apps.attribute.enums import AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex cfc342af..38a92b16 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -9,7 +9,7 @@ from hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationViewfrom hi.apps.sense.sensor_history_manager import SensorHistoryManagerfrom hi.enums import ViewType-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/event/edit/tests/test_views.py b/src/hi/apps/event/edit/tests/test_views.pyindex 40422a98..d6f4cfb5 100644--- a/src/hi/apps/event/edit/tests/test_views.py+++ b/src/hi/apps/event/edit/tests/test_views.py@@ -6,7 +6,7 @@ from django.urls import reversefrom hi.apps.event.models import EventDefinitionfrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.control.models import Controller-from hi.tests.view_test_base import DualModeViewTestCase+from hi.testing.view_test_base import DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/event/tests/test_enums.py b/src/hi/apps/event/tests/test_enums.pyindex 413b55bc..0f899497 100644--- a/src/hi/apps/event/tests/test_enums.py+++ b/src/hi/apps/event/tests/test_enums.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.event.enums import EventType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.pyindex 1107d315..b30c8edb 100644--- a/src/hi/apps/event/tests/test_event_manager.py+++ b/src/hi/apps/event/tests/test_event_manager.py@@ -10,8 +10,8 @@ from hi.apps.entity.models import Entity, EntityStatefrom hi.apps.security.enums import SecurityLevelfrom hi.apps.sense.transient_models import SensorResponsefrom hi.integrations.transient_models import IntegrationKey-from hi.tests.base_test_case import BaseTestCase-from hi.tests.async_task_utils import AsyncTaskTestCase+from hi.testing.base_test_case import BaseTestCase+from hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.apps.event.enums import EventTypefrom hi.apps.event.event_manager import EventManagerdiff --git a/src/hi/apps/event/tests/test_models.py b/src/hi/apps/event/tests/test_models.pyindex f55474d1..7ee776e8 100644--- a/src/hi/apps/event/tests/test_models.py+++ b/src/hi/apps/event/tests/test_models.py@@ -6,7 +6,7 @@ from hi.apps.alert.enums import AlarmLevelfrom hi.apps.security.enums import SecurityLevelfrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.control.models import Controller-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/event/tests/test_views.py b/src/hi/apps/event/tests/test_views.pyindex 3bf2a2f0..87769d9b 100644--- a/src/hi/apps/event/tests/test_views.py+++ b/src/hi/apps/event/tests/test_views.py@@ -4,7 +4,7 @@ from django.urls import reversefrom hi.apps.config.enums import ConfigPageTypefrom hi.apps.event.models import EventDefinition, EventHistory-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/event/transient_models.py b/src/hi/apps/event/transient_models.pyindex d726ac6a..cb82e952 100644--- a/src/hi/apps/event/transient_models.py+++ b/src/hi/apps/event/transient_models.py@@ -46,6 +46,7 @@ class Event:source_details = AlarmSourceDetails(detail_attrs = sensor_response.detail_attrs,image_url = sensor_response.image_url,+ sensor_id = sensor_response.sensor.id if sensor_response.sensor else None,)source_details_list.append( source_details )continuediff --git a/src/hi/apps/location/edit/tests/test_views.py b/src/hi/apps/location/edit/tests/test_views.pyindex 47d4034f..74d5000d 100644--- a/src/hi/apps/location/edit/tests/test_views.py+++ b/src/hi/apps/location/edit/tests/test_views.py@@ -12,7 +12,7 @@ from hi.apps.entity.models import Entityfrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ItemType, ViewMode-from hi.tests.view_test_base import SyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/location/tests/test_enums.py b/src/hi/apps/location/tests/test_enums.pyindex c113fa6f..947f9eec 100644--- a/src/hi/apps/location/tests/test_enums.py+++ b/src/hi/apps/location/tests/test_enums.py@@ -2,7 +2,7 @@ import loggingfrom hi.apps.location.enums import LocationViewType, SvgItemType, SvgStyleNamefrom hi.apps.entity.enums import EntityStateType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/location/tests/test_models.py b/src/hi/apps/location/tests/test_models.pyindex b7892b8a..59531702 100644--- a/src/hi/apps/location/tests/test_models.py+++ b/src/hi/apps/location/tests/test_models.py@@ -5,7 +5,7 @@ from hi.apps.location.models import Location, LocationAttribute, LocationViewfrom hi.apps.common.svg_models import SvgViewBox, SvgItemPositionBoundsfrom hi.apps.attribute.enums import AttributeValueTypefrom hi.enums import ItemType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/location/tests/test_svg_item_factory.py b/src/hi/apps/location/tests/test_svg_item_factory.pyindex a2d23fc9..5aa4b86e 100644--- a/src/hi/apps/location/tests/test_svg_item_factory.py+++ b/src/hi/apps/location/tests/test_svg_item_factory.py@@ -9,7 +9,7 @@ from hi.apps.entity.enums import EntityTypefrom hi.apps.collection.models import Collectionfrom hi.apps.collection.enums import CollectionTypefrom hi.apps.common.svg_models import SvgIconItem, SvgPathItem-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/location/tests/test_transient_models.py b/src/hi/apps/location/tests/test_transient_models.pyindex fea81869..197b7e6b 100644--- a/src/hi/apps/location/tests/test_transient_models.py+++ b/src/hi/apps/location/tests/test_transient_models.py@@ -4,7 +4,7 @@ from hi.apps.location.transient_models import LocationEditData, LocationViewEditfrom hi.apps.location.models import Location, LocationView, LocationAttributefrom hi.apps.location.edit.forms import LocationEditForm, LocationViewEditFormfrom hi.apps.attribute.enums import AttributeValueType-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/location/tests/test_views.py b/src/hi/apps/location/tests/test_views.pyindex df46fb2a..fe7812bf 100644--- a/src/hi/apps/location/tests/test_views.py+++ b/src/hi/apps/location/tests/test_views.py@@ -8,7 +8,7 @@ from hi.apps.entity.models import Entityfrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewType-from hi.tests.view_test_base import SyncViewTestCase, AsyncViewTestCase, DualModeViewTestCase+from hi.testing.view_test_base import SyncViewTestCase, AsyncViewTestCase, DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/monitor/tests/test_monitor_manager.py b/src/hi/apps/monitor/tests/test_monitor_manager.pyindex df19e8f4..2724e541 100644--- a/src/hi/apps/monitor/tests/test_monitor_manager.py+++ b/src/hi/apps/monitor/tests/test_monitor_manager.py@@ -4,7 +4,7 @@ import threadingfrom unittest.mock import Mock, patch, MagicMockfrom django.test import override_settings-from hi.tests.async_task_utils import AsyncTaskTestCase+from hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.apps.monitor.monitor_manager import AppMonitorManagerfrom hi.apps.monitor.periodic_monitor import PeriodicMonitordiff --git a/src/hi/apps/monitor/tests/test_periodic_monitor.py b/src/hi/apps/monitor/tests/test_periodic_monitor.pyindex 9a1ade60..a2f585be 100644--- a/src/hi/apps/monitor/tests/test_periodic_monitor.py+++ b/src/hi/apps/monitor/tests/test_periodic_monitor.py@@ -1,7 +1,7 @@import asyncioimport logging-from hi.tests.async_task_utils import AsyncTaskTestCase+from hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.apps.monitor.periodic_monitor import PeriodicMonitorlogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.pyindex 76ac0bfd..2fdd778f 100644--- a/src/hi/apps/monitor/tests/test_status_display_data.py+++ b/src/hi/apps/monitor/tests/test_status_display_data.py@@ -8,7 +8,7 @@ from hi.apps.sense.transient_models import SensorResponsefrom hi.apps.monitor.status_display_data import StatusDisplayDatafrom hi.apps.monitor.transient_models import EntityStateStatusDatafrom hi.hi_styles import StatusStyle-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/monitor/tests/test_status_display_integration.py b/src/hi/apps/monitor/tests/test_status_display_integration.pyindex 6df67504..54c27d2c 100644--- a/src/hi/apps/monitor/tests/test_status_display_integration.py+++ b/src/hi/apps/monitor/tests/test_status_display_integration.py@@ -6,7 +6,7 @@ from hi.apps.sense.models import Sensorfrom hi.apps.sense.transient_models import SensorResponsefrom hi.apps.control.models import Controllerfrom hi.apps.monitor.status_display_manager import StatusDisplayManager-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/monitor/tests/test_status_display_manager.py b/src/hi/apps/monitor/tests/test_status_display_manager.pyindex d8da4cce..78a2c03a 100644--- a/src/hi/apps/monitor/tests/test_status_display_manager.py+++ b/src/hi/apps/monitor/tests/test_status_display_manager.py@@ -6,7 +6,7 @@ from hi.apps.sense.models import Sensorfrom hi.apps.sense.transient_models import SensorResponsefrom hi.apps.monitor.status_display_manager import StatusDisplayManagerfrom hi.apps.monitor.transient_models import EntityStateStatusData-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/monitor/tests/test_transient_models.py b/src/hi/apps/monitor/tests/test_transient_models.pyindex 8165b7fe..34741208 100644--- a/src/hi/apps/monitor/tests/test_transient_models.py+++ b/src/hi/apps/monitor/tests/test_transient_models.py@@ -6,7 +6,7 @@ from hi.apps.entity.models import Entity, EntityStatefrom hi.apps.sense.transient_models import SensorResponsefrom hi.apps.control.transient_models import ControllerDatafrom hi.apps.common.svg_models import SvgIconItem-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/notify/tests/test_email_sender.py b/src/hi/apps/notify/tests/test_email_sender.pyindex ae180e33..d50b24c3 100644--- a/src/hi/apps/notify/tests/test_email_sender.py+++ b/src/hi/apps/notify/tests/test_email_sender.py@@ -6,7 +6,7 @@ from django.test import override_settingsfrom hi.apps.notify.email_sender import EmailData, EmailSender, UnsubscribedEmailErrorfrom hi.apps.notify.models import UnsubscribedEmail-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/notify/tests/test_models.py b/src/hi/apps/notify/tests/test_models.pyindex 517ea026..8958a78c 100644--- a/src/hi/apps/notify/tests/test_models.py+++ b/src/hi/apps/notify/tests/test_models.py@@ -4,7 +4,7 @@ from django.db import IntegrityErrorfrom django.contrib.auth import get_user_modelfrom hi.apps.notify.models import UnsubscribedEmail-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaseUser = get_user_model()diff --git a/src/hi/apps/notify/tests/test_notification_manager.py b/src/hi/apps/notify/tests/test_notification_manager.pyindex 852d3a03..2ff42f37 100644--- a/src/hi/apps/notify/tests/test_notification_manager.py+++ b/src/hi/apps/notify/tests/test_notification_manager.py@@ -1,6 +1,6 @@import loggingfrom unittest.mock import AsyncMock, Mock, patch-from hi.tests.async_task_utils import AsyncTaskTestCase+from hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.apps.notify.notification_manager import NotificationManagerfrom hi.apps.notify.settings import NotifySetting@@ -18,7 +18,7 @@ class TestNotificationManager(AsyncManagerTestCase):def setUp(self):super().setUp()# Reset singleton state for each test- NotificationManager._instances = {}+ NotificationManager._instance = Noneself.manager = NotificationManager()def test_singleton_pattern_behavior(self):diff --git a/src/hi/apps/notify/tests/test_notification_queue.py b/src/hi/apps/notify/tests/test_notification_queue.pyindex c4f191aa..7c644d8c 100644--- a/src/hi/apps/notify/tests/test_notification_queue.py+++ b/src/hi/apps/notify/tests/test_notification_queue.py@@ -6,7 +6,7 @@ from datetime import datetimefrom hi.apps.notify.notification_queue import NotificationQueuefrom hi.apps.notify.transient_models import Notification, NotificationItem-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/notify/tests/test_views.py b/src/hi/apps/notify/tests/test_views.pyindex 6a9b3d2f..963357ca 100644--- a/src/hi/apps/notify/tests/test_views.py+++ b/src/hi/apps/notify/tests/test_views.py@@ -4,7 +4,7 @@ from unittest.mock import patchfrom django.urls import reversefrom hi.apps.notify.models import UnsubscribedEmail-from hi.tests.view_test_base import SyncViewTestCase+from hi.testing.view_test_base import SyncViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/notify/tests/ui/views.py b/src/hi/apps/notify/tests/ui/views.pyindex 0b8a4e33..234c4faa 100644--- a/src/hi/apps/notify/tests/ui/views.py+++ b/src/hi/apps/notify/tests/ui/views.py@@ -11,7 +11,7 @@ from hi.apps.notify.notify_mixins import NotificationMixinfrom hi.apps.notify.tests.synthetic_data import NotifySyntheticDatafrom hi.apps.notify.settings import NotifySetting-from hi.tests.ui.email_test_views import EmailTestViewView+from hi.testing.ui.email_test_views import EmailTestViewViewclass TestUiNotifyHomeView( View ):diff --git a/src/hi/apps/security/tests/test_enums.py b/src/hi/apps/security/tests/test_enums.pyindex 3c777037..8c3ea387 100644--- a/src/hi/apps/security/tests/test_enums.py+++ b/src/hi/apps/security/tests/test_enums.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.security.enums import SecurityLevel, SecurityState, SecurityStateAction-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/security/tests/test_security_manager.py b/src/hi/apps/security/tests/test_security_manager.pyindex eac2c6d0..b1517982 100644--- a/src/hi/apps/security/tests/test_security_manager.py+++ b/src/hi/apps/security/tests/test_security_manager.py@@ -10,7 +10,7 @@ from hi.apps.security.enums import SecurityLevel, SecurityState, SecurityStateAcfrom hi.apps.security.security_manager import SecurityManagerfrom hi.apps.security.transient_models import SecurityStatusDatafrom hi.constants import DIVID-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/security/tests/test_security_monitor.py b/src/hi/apps/security/tests/test_security_monitor.pyindex 4ce104f1..3730bc2b 100644--- a/src/hi/apps/security/tests/test_security_monitor.py+++ b/src/hi/apps/security/tests/test_security_monitor.py@@ -1,7 +1,7 @@import loggingfrom unittest.mock import Mock, patch, AsyncMock-from hi.tests.async_task_utils import AsyncTaskTestCase+from hi.testing.async_task_utils import AsyncTaskTestCaseimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.security.enums import SecurityStatediff --git a/src/hi/apps/security/tests/test_views.py b/src/hi/apps/security/tests/test_views.pyindex ab1645f1..40f03482 100644--- a/src/hi/apps/security/tests/test_views.py+++ b/src/hi/apps/security/tests/test_views.py@@ -3,7 +3,7 @@ import loggingfrom django.urls import reversefrom hi.apps.security.security_manager import SecurityManager-from hi.tests.view_test_base import SyncViewTestCase+from hi.testing.view_test_base import SyncViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/sense/tests/test_models.py b/src/hi/apps/sense/tests/test_models.pyindex b0c96b4e..c61c15c4 100644--- a/src/hi/apps/sense/tests/test_models.py+++ b/src/hi/apps/sense/tests/test_models.py@@ -9,7 +9,7 @@ from django.utils import timezonefrom hi.apps.sense.models import Sensor, SensorHistoryfrom hi.apps.sense.enums import SensorTypefrom hi.apps.entity.models import Entity, EntityState-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/sense/tests/test_sensor_history_manager.py b/src/hi/apps/sense/tests/test_sensor_history_manager.pyindex 104e1b6e..d55748c1 100644--- a/src/hi/apps/sense/tests/test_sensor_history_manager.py+++ b/src/hi/apps/sense/tests/test_sensor_history_manager.py@@ -4,7 +4,7 @@ from unittest.mock import patchfrom asgiref.sync import sync_to_asyncfrom django.utils import timezone-from hi.tests.async_task_utils import AsyncTaskTestCase+from hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.apps.entity.models import Entity, EntityState, EntityStateDelegationfrom hi.apps.sense.models import Sensor, SensorHistorydiff --git a/src/hi/apps/sense/tests/test_sensor_response.py b/src/hi/apps/sense/tests/test_sensor_response.pyindex 66ab9aaa..9b6f7b3f 100644--- a/src/hi/apps/sense/tests/test_sensor_response.py+++ b/src/hi/apps/sense/tests/test_sensor_response.py@@ -8,7 +8,7 @@ from hi.apps.entity.models import Entity, EntityStatefrom hi.apps.sense.models import Sensor, SensorHistoryfrom hi.apps.sense.transient_models import SensorResponsefrom hi.integrations.transient_models import IntegrationKey-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaseclass TestSensorResponse(BaseTestCase):diff --git a/src/hi/apps/sense/tests/test_sensor_response_manager.py b/src/hi/apps/sense/tests/test_sensor_response_manager.pyindex 6f0dcf3f..d9aada08 100644--- a/src/hi/apps/sense/tests/test_sensor_response_manager.py+++ b/src/hi/apps/sense/tests/test_sensor_response_manager.py@@ -1,7 +1,7 @@from datetime import datetimefrom unittest.mock import Mock, patchfrom django.utils import timezone-from hi.tests.async_task_utils import AsyncTaskTestCase+from hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.sense.models import Sensor, SensorHistorydiff --git a/src/hi/apps/sense/tests/test_views.py b/src/hi/apps/sense/tests/test_views.pyindex 021c04ec..0bac2770 100644--- a/src/hi/apps/sense/tests/test_views.py+++ b/src/hi/apps/sense/tests/test_views.py@@ -4,7 +4,7 @@ from django.urls import reversefrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.sense.models import Sensor, SensorHistory-from hi.tests.view_test_base import DualModeViewTestCase+from hi.testing.view_test_base import DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/user/tests/test_magic_code_generator.py b/src/hi/apps/user/tests/test_magic_code_generator.pyindex e644f868..67945d40 100644--- a/src/hi/apps/user/tests/test_magic_code_generator.py+++ b/src/hi/apps/user/tests/test_magic_code_generator.py@@ -2,7 +2,7 @@ import loggingfrom unittest.mock import Mock, patchfrom hi.apps.user.magic_code_generator import MagicCodeGenerator, MagicCodeStatus-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/user/tests/test_middleware.py b/src/hi/apps/user/tests/test_middleware.pyindex f72e33b0..0ac9ae83 100644--- a/src/hi/apps/user/tests/test_middleware.py+++ b/src/hi/apps/user/tests/test_middleware.py@@ -8,7 +8,7 @@ from django.test import RequestFactory, override_settingsfrom django.urls import ResolverMatchfrom hi.apps.user.middleware import AuthenticationMiddleware-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/user/tests/test_signin_manager.py b/src/hi/apps/user/tests/test_signin_manager.pyindex d8f63b48..361e9257 100644--- a/src/hi/apps/user/tests/test_signin_manager.py+++ b/src/hi/apps/user/tests/test_signin_manager.py@@ -6,7 +6,7 @@ from django.test import RequestFactoryfrom hi.apps.notify.email_sender import EmailDatafrom hi.apps.user.signin_manager import SigninManager-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/user/tests/test_transient_models.py b/src/hi/apps/user/tests/test_transient_models.pyindex 4e3ade79..84ef7bf8 100644--- a/src/hi/apps/user/tests/test_transient_models.py+++ b/src/hi/apps/user/tests/test_transient_models.py@@ -5,7 +5,7 @@ from custom.models import CustomUserfrom django.test import RequestFactoryfrom hi.apps.user.transient_models import UserAuthenticationData-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/user/tests/test_views.py b/src/hi/apps/user/tests/test_views.pyindex 7ec8c208..22d849ac 100644--- a/src/hi/apps/user/tests/test_views.py+++ b/src/hi/apps/user/tests/test_views.py@@ -8,7 +8,7 @@ from django.urls import reversefrom hi.apps.notify.email_sender import EmailSenderfrom hi.apps.user.magic_code_generator import MagicCodeStatus, MagicCodeGeneratorfrom hi.apps.user.signin_manager import SigninManager-from hi.tests.view_test_base import SyncViewTestCase+from hi.testing.view_test_base import SyncViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/user/tests/ui/views.py b/src/hi/apps/user/tests/ui/views.pyindex 37022b26..10196427 100644--- a/src/hi/apps/user/tests/ui/views.py+++ b/src/hi/apps/user/tests/ui/views.py@@ -9,7 +9,7 @@ from hi.apps.notify.email_sender import EmailSenderfrom hi.apps.user.signin_manager import SigninManagerfrom hi.apps.user.transient_models import UserAuthenticationData-from hi.tests.ui.email_test_views import EmailTestViewView+from hi.testing.ui.email_test_views import EmailTestViewViewclass TestUiUserHomeView( View ):diff --git a/src/hi/apps/weather/tests/test_aggregated_weather_data.py b/src/hi/apps/weather/tests/test_aggregated_weather_data.pyindex ce500a78..02094ded 100644--- a/src/hi/apps/weather/tests/test_aggregated_weather_data.py+++ b/src/hi/apps/weather/tests/test_aggregated_weather_data.py@@ -16,7 +16,7 @@ from hi.apps.weather.transient_models import ()from hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_enums.py b/src/hi/apps/weather/tests/test_enums.pyindex 3487afa1..451d793c 100644--- a/src/hi/apps/weather/tests/test_enums.py+++ b/src/hi/apps/weather/tests/test_enums.py@@ -15,7 +15,7 @@ from hi.apps.weather.enums import (WindDirection,)-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_interval_data_manager.py b/src/hi/apps/weather/tests/test_interval_data_manager.pyindex 97ab6974..b116d3e5 100644--- a/src/hi/apps/weather/tests/test_interval_data_manager.py+++ b/src/hi/apps/weather/tests/test_interval_data_manager.py@@ -14,7 +14,7 @@ from hi.apps.weather.transient_models import ()from hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_interval_data_manager_comprehensive.py b/src/hi/apps/weather/tests/test_interval_data_manager_comprehensive.pyindex cc3edc20..12e8bb11 100644--- a/src/hi/apps/weather/tests/test_interval_data_manager_comprehensive.py+++ b/src/hi/apps/weather/tests/test_interval_data_manager_comprehensive.py@@ -19,7 +19,7 @@ from hi.apps.weather.transient_models import ()from hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_interval_models.py b/src/hi/apps/weather/tests/test_interval_models.pyindex e45ff035..77bac3a5 100644--- a/src/hi/apps/weather/tests/test_interval_models.py+++ b/src/hi/apps/weather/tests/test_interval_models.py@@ -12,7 +12,7 @@ from hi.apps.weather.transient_models import ()from hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_nws.py b/src/hi/apps/weather/tests/test_nws.pyindex c47e0ccd..4be0fe51 100644--- a/src/hi/apps/weather/tests/test_nws.py+++ b/src/hi/apps/weather/tests/test_nws.py@@ -27,7 +27,7 @@ from hi.apps.weather.weather_sources.nws import NationalWeatherServicefrom hi.transient_models import GeographicLocationfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_openmeteo.py b/src/hi/apps/weather/tests/test_openmeteo.pyindex e984c168..eb07cc63 100644--- a/src/hi/apps/weather/tests/test_openmeteo.py+++ b/src/hi/apps/weather/tests/test_openmeteo.py@@ -14,7 +14,7 @@ from hi.apps.weather.transient_models import (from hi.transient_models import GeographicLocationfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_sunrise_sunset_org.py b/src/hi/apps/weather/tests/test_sunrise_sunset_org.pyindex 6fe607f5..09cd8c0b 100644--- a/src/hi/apps/weather/tests/test_sunrise_sunset_org.py+++ b/src/hi/apps/weather/tests/test_sunrise_sunset_org.py@@ -18,7 +18,7 @@ from hi.apps.weather.transient_models import (from hi.transient_models import GeographicLocationfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_transient_models.py b/src/hi/apps/weather/tests/test_transient_models.pyindex 243278ab..052af583 100644--- a/src/hi/apps/weather/tests/test_transient_models.py+++ b/src/hi/apps/weather/tests/test_transient_models.py@@ -33,7 +33,7 @@ from hi.apps.weather.enums import (from hi.transient_models import GeographicLocationfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_usno.py b/src/hi/apps/weather/tests/test_usno.pyindex 7f61df2d..00f1778f 100644--- a/src/hi/apps/weather/tests/test_usno.py+++ b/src/hi/apps/weather/tests/test_usno.py@@ -19,7 +19,7 @@ from hi.apps.weather.transient_models import (from hi.transient_models import GeographicLocationfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_views.py b/src/hi/apps/weather/tests/test_views.pyindex 20b49e6f..8f1abfb3 100644--- a/src/hi/apps/weather/tests/test_views.py+++ b/src/hi/apps/weather/tests/test_views.py@@ -3,7 +3,7 @@ import loggingfrom django.urls import reversefrom hi.apps.weather.weather_manager import WeatherManager-from hi.tests.view_test_base import DualModeViewTestCase+from hi.testing.view_test_base import DualModeViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py b/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.pyindex 53cf6347..309fb060 100644--- a/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py+++ b/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py@@ -18,7 +18,7 @@ from hi.apps.weather.enums import ()from hi.apps.weather.transient_models import WeatherAlertfrom hi.apps.weather.weather_alert_alarm_mapper import WeatherAlertAlarmMapper-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaseclass TestWeatherAlertAlarmMapper(BaseTestCase):diff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.pyindex 44992190..5c9ded66 100644--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py@@ -10,7 +10,7 @@ from hi.apps.weather.weather_sources.nws import NationalWeatherServicefrom hi.apps.weather.weather_manager import WeatherManagerfrom hi.transient_models import GeographicLocationfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaseclass TestWeatherAlertIntegration(BaseTestCase):diff --git a/src/hi/apps/weather/tests/test_weather_manager.py b/src/hi/apps/weather/tests/test_weather_manager.pyindex 5d6b6281..2d44ce3f 100644--- a/src/hi/apps/weather/tests/test_weather_manager.py+++ b/src/hi/apps/weather/tests/test_weather_manager.py@@ -28,7 +28,7 @@ from hi.apps.weather.enums import ()from hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCasefrom hi.apps.weather.tests.synthetic_data import WeatherSyntheticDatalogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.pyindex f4d550aa..771247d9 100644--- a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py+++ b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py@@ -15,7 +15,7 @@ from hi.apps.weather.transient_models import WeatherConditionsData, NumericDataPfrom hi.apps.weather.weather_data_source import WeatherDataSourcefrom hi.transient_models import GeographicLocationfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaseclass MockWeatherDataSource(WeatherDataSource):diff --git a/src/hi/apps/weather/tests/test_wmo_units.py b/src/hi/apps/weather/tests/test_wmo_units.pyindex 5a5201d8..1a54a9db 100644--- a/src/hi/apps/weather/tests/test_wmo_units.py+++ b/src/hi/apps/weather/tests/test_wmo_units.py@@ -3,7 +3,7 @@ import loggingfrom hi.apps.weather.wmo_units import WmoUnitsfrom hi.units import UnitQuantity-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 26164f93..5d5287ba 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -262,6 +262,7 @@ PIPELINE = {'js/svg-utils.js','js/watchdog.js','js/status.js',+ 'js/auto-view.js','js/edit.js','js/edit-dragdrop.js','js/svg-icon.js',@@ -355,3 +356,11 @@ SUPPRESS_SELECT_REQUEST_ENPOINTS_LOGGING = True# to turn them off with one setting.#SUPPRESS_MONITORS = False++# ====================+# Development Testing Injection Points+# (enabled/disabled in environment-specific settings)++# When enabled in DEBUG mode, allows injecting test data into API responses+# for frontend testing without changing backend state. Never enabled in production.+DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = Falsediff --git a/src/hi/settings/development.py b/src/hi/settings/development.pyindex 9adaf81b..44374fdd 100644--- a/src/hi/settings/development.py+++ b/src/hi/settings/development.py@@ -10,7 +10,7 @@ TEMPLATES[0]['OPTIONS'].update({#'string_if_invalid': 'INVALID_VARIABLE_%s',})-INSTALLED_APPS += [ 'hi.tests' ]+INSTALLED_APPS += [ 'hi.testing' ]STATIC_ROOT = '/tmp/hi/static'@@ -24,7 +24,7 @@ LOGGING = {#'filters': {'suppress_select_request_endpoints': {- '()': 'hi.tests.utils.log_filters.SuppressSelectRequestEndpointsFilter',+ '()': 'hi.testing.utils.log_filters.SuppressSelectRequestEndpointsFilter',},'suppress_pipeline_template_vars': {'()': 'hi.apps.common.log_filters.SuppressPipelineTemplateVarsFilter',@@ -67,7 +67,7 @@ LOGGING = {},'hi.apps.alert': {'handlers': ['console' ],- 'level': 'INFO',+ 'level': 'DEBUG','propagate': False,},'hi.apps.control': {@@ -75,6 +75,11 @@ LOGGING = {'level': 'INFO','propagate': False,},+ 'hi.apps.console': {+ 'handlers': ['console' ],+ 'level': 'DEBUG',+ 'propagate': False,+ },'hi.apps.notify': {'handlers': ['console' ],'level': 'INFO',@@ -107,7 +112,7 @@ LOGGING = {},'hi.services.hass': {'handlers': ['console' ],- 'level': 'DEBUG',+ 'level': 'INFO','propagate': False,},'hi.services.zoneminder': {@@ -136,3 +141,10 @@ BASE_URL_FOR_EMAIL_LINKS = 'http:/127.0.0.1:8411/'SUPPRESS_SELECT_REQUEST_ENPOINTS_LOGGING = TrueSUPPRESS_MONITORS = False++# ====================+# Development Testing Injection Points+# Enable/disable these here for frontend testing++# Allows injecting transient view data for testing auto-view functionality+DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False # Set to True to enablediff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex 8d68d6da..df3d6dc1 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -673,3 +673,56 @@ g[hover] {.btn-camera[status="idle"] {/* Default button styling - no changes needed */}++/* Auto-view indicator styling */+/* Auto-view transient state styling */+.auto-view-active {+ border: 3px solid var(--warning-color) !important;+ border-radius: 4px;+ box-shadow: 0 0 0 1px rgba(236, 165, 0, 0.3);+ transition: all 0.3s ease-in-out;+}++.auto-view-corner-badge {+ background-color: var(--warning-color);+ color: var(--on-warning-color);+ padding: 6px 12px;+ border-radius: 0;+ font-size: 12px;+ font-weight: 500;+ display: flex;+ align-items: center;+ gap: 4px;+ box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.15);+ width: auto;+ min-width: fit-content;+ backdrop-filter: blur(5px);+ pointer-events: none;+ border-top: 1px solid rgba(236, 165, 0, 0.3);+ border-left: 1px solid rgba(236, 165, 0, 0.3);+}++.auto-view-badge-icon {+ font-size: 14px;+ opacity: 0.9;+}++.auto-view-badge-text {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++/* Removed pulse animation as requested */++/* Responsive adjustments for smaller screens */+@media (max-width: 768px) {+ .auto-view-corner-badge {+ font-size: 11px;+ padding: 4px 8px;+ }++ .auto-view-badge-icon {+ font-size: 12px;+ }+}diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.jsindex 6fc991be..9ec12793 100644--- a/src/hi/static/js/antinode.js+++ b/src/hi/static/js/antinode.js@@ -1,144 +1,278 @@// Anti-Node - Less Javascript is Better-// For Server-side rendering for asynchronous interactions-//-// Copyright 2020 by POMDP, Inc. - All rights reserved--// ---------------// (Django) HOWTO-// ---------------//-// 1. Include jQuery and Bootstrap and cookie.js-// 2. Add this to bottom page JS loading items:+// Server-side rendering for asynchronous interactions+//+// Copyright 2020-2025 by POMDP, Inc. - All rights reserved++// ====================+// OVERVIEW+// ====================+// Anti-Node (AN) provides a comprehensive framework for handling asynchronous+// content loading and DOM manipulation without full page refreshes. It supports+// both declarative (HTML attributes) and programmatic (JavaScript API) usage.++// ====================+// PREREQUISITES+// ====================+// 1. jQuery (for AJAX and DOM manipulation)+// 2. Bootstrap (optional, for modal support)+// 3. js-cookie library (for CSRF token handling)+// 4. Include antinode.js after the above libraries:// <script src="{% static 'js/antinode.js' %}"></script>--//========================================-// jQuery asynchronous form submission--// For any anchor tag (<a>) or form tag (<form>), you can turn them into an-// asynchonous (aka, AJAX) request by adding the attribute:-//-// data-async="mnemonic-or-jquery-selector"-//-// Where the predefined, reserved mnemonics are:-//-// "modal" - render as a modal dialog-//-// Can also define data-mode with values:-//-// "replace" - to replace the target instead of inserting into it-//-// This javascript code will add events to those items to send them through-// then jQuery ajax requests and ensure that the returned content get-// rendered inside the DOM element matching then target id or selector.-//-// By default, the async content will be "inserted" into the matching-// selected and overwriting and of its existing contained HTML content-// (but it does not replace the matching node itself). If you want to-// completely replace the target node, then also add the attribute-// data-mode="replace" .-//-// This has special logic to handle Bootstrap modal dialogs as well so that-// if the target points to a (initially hidden) Bootstrap modal, it will-// also ensure that the modal gets shown.-//-// An extra feature is to handle page redirects in the case where the-// anchor or form might render async content or may need to redirect. In-// this case, if the returntin content is a JSON document with the attribute-// "location", it will assume this is a URL and will redirect the page-// (instead of inserting the content into the DOM).-//-// Another feature it provides is restoring scroll bar positions for-// content that is asynchronously refreshed. Use the 'preserve-scroll-bar'-// class on the scrollable element to be preserved.-//-// For form submissions with submit buttons, you can help prevent double-// submissions by adding the form property "debounce". Set this on the form-// HTML element, not the buttons.-//-// To support "onchange" submission for Select or checkbox elements, add-// the following attribute to the SELECT (and also add the-// data-async/data-mode attributes to the form)-//-// onchange-async="true"-//-// If you define the javascript function "handlePostAsyncUpdate()", this-// will be called after each async content update after all updated are-// handled.-//-// You can use the following attributes on a form/link with the data-async-// attribute. These allow you to show or hide content when the async-// submission/click is triggered.-//-// data-hide="{selector}" - jQuery selector for content to be hidden on submit/click-// data-show="{selector}" - jQuery selector for content to be shown on submit/click-//-// You will probably want an initial CSS rules of "display: none;" on the-// data-show elements.-//-// If you want a synchronously loaded page to display an initial modal afer-// page load, put the modal content in a DIV with the id-// "antinode-initial-modal".--// Version Support-//+// 5. (Optional) Set AN_VERSION variable before loading for version compatibility++// ====================+// DECLARATIVE USAGE (HTML Attributes)+// ====================+//+// Basic async loading:+// <a href="/path" data-async="#target-id">Load Content</a>+// <form action="/submit" data-async="#result-area">...</form>+//+// Attributes:+// data-async="{selector}" - jQuery selector for target element, or "modal" for new modal+// data-mode="insert" - (default) Replace inner HTML of target+// data-mode="replace" - Replace entire target element+// data-hide="{selector}" - Hide elements when triggered+// data-show="{selector}" - Show elements when triggered+// data-stay-in-modal - Don't auto-close modal on submission+// debounce - Prevent double form submission+// onchange-async="true" - Auto-submit form on select/checkbox change++// ====================+// PROGRAMMATIC API+// ====================+//+// AN.loadAsyncContent(config) - Load content into specific target+// config.url - URL to fetch+// config.target - Target selector or jQuery object (required)+// config.mode - 'insert' or 'replace' (default: 'insert')+// config.method - 'GET' or 'POST' (default: 'GET')+// config.data - Data for POST requests+// config.beforeSend - Callback: function(jqXHR, settings)+// config.success - Callback: function(data, status, xhr)+// config.error - Callback: function(xhr, ajaxOptions, thrownError)+//+// AN.get(url) - GET request, target determined by response+// AN.post(url, data) - POST request, target determined by response++// ====================+// SERVER RESPONSE FORMATS+// ====================+//+// 1. HTML Response:+// - Inserted directly into target element+//+// 2. JSON Response - supports multiple operations:+// {+// "location": "/redirect/url", // Redirect browser+// "refresh": true, // Refresh entire page+// "html": "<div>...</div>", // Content for main target+// "insert": {"id1": "...", ...}, // Replace inner HTML by ID+// "replace": {"id1": "...", ...}, // Replace entire elements by ID+// "append": {"id1": "...", ...}, // Append to elements by ID+// "setAttributes": {"id1": {...}}, // Set element attributes+// "modal": "<div>...</div>", // Create and show modal+// "pushUrl": "/new/url", // Update browser URL without reload+// "resetScrollbar": true // Reset to top of page+// }++// ====================+// SPECIAL FEATURES+// ====================+//+// Scroll Preservation:+// Add class "preserve-scroll-bar" to elements to maintain scroll position+//+// Loading Indicator:+// Automatic loading spinner overlay during async requests+//+// Modal Support:+// - Auto-display: Place content in #antinode-initial-modal+// - Dynamic modals: Use data-async="modal"+// - Handles overlapping show/hide transitions+//+// Version Compatibility:+// Adds X-AN-Version header to detect version mismatches (see VERSION SUPPORT below)+//+// Post-Update Hook:+// Define global function handlePostAsyncUpdate() to run after updates+//+// Extension Point:+// Call addAfterAsyncRenderFunction(func) to add custom post-render logic++// ====================+// ERROR HANDLING+// ====================+// - HTTP errors still process response content (useful for form validation)+// - Console errors logged for debugging+// - Malformed JSON falls back to HTML insertion++// ====================+// CSRF PROTECTION+// ====================+// Automatically adds Django CSRF token to POST requests using js-cookie++// ====================+// VERSION SUPPORT+// ====================// Asynchronous pages are susceptible to problems when the server-side-// software is updated. If the synchronously loaded CSS or JS files from+// software is updated. If the synchronously loaded CSS or JS files from// the previous version are used to try to render the asynchronously loaded-// HTML content from a newer version, there can be a mismatch. To help the-// server-side deal with this, this module will add a custom HTTP header to-// every asynchronous call with the version number. To enable this+// HTML content from a newer version, there can be a mismatch.+//+// To help the server-side deal with this, this module will add a custom HTTP+// header to every asynchronous call with the version number. To enable this// feature, you need to ensure that the javascript variable AN_VERSION is-// set to the current version somewhere before this module loads. When+// set to the current version somewhere before this module loads. When// that variable exists, this module will add the header "X-AN-Version"-// with the value of that variable. The server can use this to detect if-// that matches the currently running server version and take action if-// needed. A typical action is to render a dialog to force a-// synchronous refresh and ensure the latest version of the CSS and JS-// assets are loaded.+// with the value of that variable.+//+// The server can use this to detect if that matches the currently running+// server version and take action if needed. A typical action is to render+// a dialog to force a synchronous refresh and ensure the latest version+// of the CSS and JS assets are loaded.(function() {const AN = {- get: function( url ) {- $.ajax({- type: 'GET',- url: url,+ get: function( url ) {+ $.ajax({+ type: 'GET',+ url: url,- success: function(data, status, xhr) {- asyncUpdateData( null, null, data, xhr );- return false;- },- error: function (xhr, ajaxOptions, thrownError) {- let http_code = xhr.status;- let error_msg = thrownError;- asyncUpdateData( null, null, xhr.responseText, xhr );- return false;- }- });- },-- post: function( url, data ) {- $.ajax({- type: 'POST',- url: url,- data: data,- async: true,- cache: false,- contentType: 'application/x-www-form-urlencoded; charset=UTF-8',- processData: true,-- success: function(data, status, xhr) {- asyncUpdateData( null, null, data, xhr );- return false;- },- error: function (xhr, ajaxOptions, thrownError) {- let http_code = xhr.status;- let error_msg = thrownError;- asyncUpdateData( null, null, xhr.responseText, xhr );- return false;- }- });- }+ success: function(data, status, xhr) {+ asyncUpdateData( null, null, data, xhr );+ return false;+ },+ error: function (xhr, ajaxOptions, thrownError) {+ let http_code = xhr.status;+ let error_msg = thrownError;+ asyncUpdateData( null, null, xhr.responseText, xhr );+ return false;+ }+ });+ },++ post: function( url, data ) {+ $.ajax({+ type: 'POST',+ url: url,+ data: data,+ async: true,+ cache: false,+ contentType: 'application/x-www-form-urlencoded; charset=UTF-8',+ processData: true,++ success: function(data, status, xhr) {+ asyncUpdateData( null, null, data, xhr );+ return false;+ },+ error: function (xhr, ajaxOptions, thrownError) {+ let http_code = xhr.status;+ let error_msg = thrownError;+ asyncUpdateData( null, null, xhr.responseText, xhr );+ return false;+ }+ });+ },++ // New public API for programmatically loading content into a target element+ // This is designed for JavaScript-initiated DOM replacement requests where+ // both the URL and target are specified by the caller.+ //+ // Usage:+ // AN.loadAsyncContent({+ // url: '/some/path',+ // target: '#element-id', // or jQuery object+ // mode: 'insert', // optional: 'insert' (default) or 'replace'+ // method: 'GET', // optional: 'GET' (default) or 'POST'+ // data: {...}, // optional: data for POST requests+ // beforeSend: function(jqXHR, settings) {...}, // optional callback+ // success: function(data, status, xhr) {...}, // optional callback+ // error: function(xhr, ajaxOptions, thrownError) {...} // optional callback+ // });+ //+ loadAsyncContent: function( config ) {+ // Validate required parameters+ if ( !config || !config.url || !config.target ) {+ console.error('AN.loadAsyncContent requires config object with url and target');+ return;+ }++ // Get target element - support both selector strings and jQuery objects+ let $target = (typeof config.target === 'string')+ ? $(config.target)+ : config.target;++ // Validate target exists+ if ( !$target || $target.length === 0 ) {+ console.error('AN.loadAsyncContent: target element not found:', config.target);+ return;+ }++ // Set defaults for optional parameters+ let mode = config.mode || 'insert';+ let method = (config.method || 'GET').toUpperCase();+ let data = config.data || null;+ let async = config.async !== false; // default true+ let cache = config.cache !== false; // default true for GET++ // For POST requests, handle data serialization+ let processData = true;+ let contentType = 'application/x-www-form-urlencoded; charset=UTF-8';++ if ( method === 'POST' && data ) {+ // If data is already FormData, don't process it+ if ( data instanceof FormData ) {+ processData = false;+ contentType = false;+ cache = false;+ }+ }++ // Make the AJAX request+ $.ajax({+ type: method,+ url: config.url,+ data: data,+ async: async,+ cache: cache,+ contentType: contentType,+ processData: processData,++ beforeSend: function(jqXHR, ajaxSettings) {+ // Add version header if available+ if ( typeof AN_VERSION !== 'undefined' ) {+ jqXHR.setRequestHeader('X-AN-Version', AN_VERSION);+ }++ // Call custom beforeSend if provided+ if ( config.beforeSend && typeof config.beforeSend === 'function' ) {+ config.beforeSend(jqXHR, ajaxSettings);+ }+ },++ success: function(data, status, xhr) {+ // Use existing response handler with specified target and mode+ asyncUpdateData($target, mode, data, xhr);++ // Call custom success callback if provided+ if ( config.success && typeof config.success === 'function' ) {+ config.success(data, status, xhr);+ }+ },++ error: function(xhr, ajaxOptions, thrownError) {+ // Use existing error handler - still processes the response+ asyncUpdateData($target, mode, xhr.responseText, xhr);++ // Call custom error callback if provided+ if ( config.error && typeof config.error === 'function' ) {+ config.error(xhr, ajaxOptions, thrownError);+ }+ }+ });+ }}window.AN = AN;@@ -158,7 +292,7 @@ function asyncSubmitHandler(event) {function asyncSubmitHandlerHelper( $form ) {if ( $form.attr('debounce') ) {- $form.find('button').prop('disabled', true);+ $form.find('button').prop('disabled', true);}handleHideShowIfNeeded( $form );@@ -227,12 +361,12 @@ function asyncSubmitHandlerHelper( $form ) {contentType: contentType,processData: processData,- beforeSend: function (jqXHR, settings) {- if ( typeof AN_VERSION !== 'undefined' ) {- jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );- }- },-+ beforeSend: function (jqXHR, settings) {+ if ( typeof AN_VERSION !== 'undefined' ) {+ jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );+ }+ },+success: function(data, status, xhr) {asyncUpdateData( $target, $mode, data, xhr );return false;@@ -292,12 +426,12 @@ function asyncClickHandler(event) {type: 'GET',url: url,- beforeSend: function (jqXHR, settings) {- if ( typeof AN_VERSION !== 'undefined' ) {- jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );- }- },-+ beforeSend: function (jqXHR, settings) {+ if ( typeof AN_VERSION !== 'undefined' ) {+ jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );+ }+ },+success: function(data, status, xhr) {asyncUpdateData( $target, $mode, data, xhr );return false;@@ -334,12 +468,12 @@ function handleHideShowIfNeeded( $anchor ) {let hide_selector = $anchor.attr('data-hide');if ( hide_selector ) {- $(hide_selector).hide();+ $(hide_selector).hide();}let show_selector = $anchor.attr('data-show');if ( show_selector ) {- $(show_selector).show();+ $(show_selector).show();}};@@ -437,18 +571,18 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {// If they were different, we would have to check for both here.//if ( 'location' in json ) {- let url = json['location'];- this.document.location.href = url;- return;+ let url = json['location'];+ this.document.location.href = url;+ return;}// To allow the server to decide to refresh the page rather than// render async content.//if ( 'refresh' in json ) {- location.reload();- window.scrollTo(0, 0);- return;+ location.reload();+ window.scrollTo(0, 0);+ return;}// In a JSON response, the 'html' contains the "main" content that@@ -462,7 +596,7 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {$target.replaceWith( json['html'] );}else {- $target.empty();+ $target.empty();$target.html( json['html'] );}handleNewContentAdded( $target );@@ -486,7 +620,7 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {if ( 'insert' in json ) {for ( let htmlId in json['insert'] ) {let targetObj = $("#"+htmlId);- targetObj.empty();+ targetObj.empty();targetObj.html( json['insert'][htmlId] ).show();handleNewContentAdded( targetObj );}@@ -508,13 +642,13 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {//if ( 'setAttributes' in json ) {for ( let htmlId in json['setAttributes'] ) {- let targetObj = $("#"+htmlId);- let attrMap = json['setAttributes'][htmlId];+ let targetObj = $("#"+htmlId);+ let attrMap = json['setAttributes'][htmlId];for ( let attrName in attrMap ) {- let attrValue = attrMap[attrName];- targetObj.attr( attrName, attrValue );- handleNewContentAdded( targetObj );- }+ let attrValue = attrMap[attrName];+ targetObj.attr( attrName, attrValue );+ handleNewContentAdded( targetObj );+ }}}@@ -534,11 +668,11 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {}if ( 'resetScrollbar' in json ) {- window.scrollTo(0, 0);+ window.scrollTo(0, 0);}if ( typeof handlePostAsyncUpdate === "function") {- handlePostAsyncUpdate();+ handlePostAsyncUpdate();}};@@ -723,11 +857,11 @@ function asyncRedirect( $target, $mode, url ) {type: 'GET',url: url,- beforeSend: function (jqXHR, settings) {- if ( typeof AN_VERSION !== 'undefined' ) {- jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );- }- },+ beforeSend: function (jqXHR, settings) {+ if ( typeof AN_VERSION !== 'undefined' ) {+ jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );+ }+ },success: function(data, status, xhr) {asyncUpdateData( $target, $mode, data, xhr );},@@ -831,7 +965,7 @@ jQuery(function($) {let initial_modal_content = $('#antinode-initial-modal');if ( initial_modal_content.length > 0 ) {- let targetObj = getNewModal();+ let targetObj = getNewModal();targetObj.append( initial_modal_content )showModal( targetObj );}@@ -842,13 +976,13 @@ jQuery(function($) {$.ajaxSuppressLoader = false;$(document)- .ajaxStart(function () {- if ( ! $.ajaxSuppressLoader ) {- $('#antinode-loader').show();- }- })- .ajaxStop(function () {+ .ajaxStart(function () {+ if ( ! $.ajaxSuppressLoader ) {+ $('#antinode-loader').show();+ }+ })+ .ajaxStop(function () {$('#antinode-loader').hide();- });+ });})();diff --git a/src/hi/static/js/auto-view.js b/src/hi/static/js/auto-view.jsnew file mode 100644index 00000000..2030a604--- /dev/null+++ b/src/hi/static/js/auto-view.js@@ -0,0 +1,358 @@+(function() {+ window.Hi = window.Hi || {};++ const AutoView = {+ // Configuration constants+ IDLE_TIMEOUT_SECONDS: 60,++ // State tracking+ lastInteractionTime: Date.now(),+ isTransientView: false,+ revertTimer: null,+ originalContent: null,+ originalUrl: null,+ transientUrls: [],++ init: function() {+ this.attachInteractionListeners();+ if (Hi.DEBUG) {+ console.log('AutoView initialized');+ }+ },++ // User interaction tracking+ attachInteractionListeners: function() {+ // Note: excludes mousemove for performance reasons+ const events = ['mousedown', 'keydown', 'touchstart', 'click'];++ // Throttle interaction recording to prevent excessive calls+ const throttledRecordInteraction = this.throttle(() => {+ this.recordInteraction();+ }, 100); // Max once per 100ms++ events.forEach(event => {+ // Use passive listeners where possible for better performance+ const options = this.isPassiveEventSupported() &&+ (event === 'touchstart') ? { passive: true } : false;++ document.addEventListener(event, throttledRecordInteraction, options);+ });+ },++ recordInteraction: function() {+ this.lastInteractionTime = Date.now();++ // If we're in a transient view and user interacts, make it permanent+ if (this.isTransientView) {+ this.makeTransientViewPermanent();+ }+ },++ // Helper method to check if passive events are supported+ isPassiveEventSupported: function() {+ if (this._passiveSupported !== undefined) {+ return this._passiveSupported;+ }++ this._passiveSupported = false;+ try {+ const options = {+ get passive() {+ this._passiveSupported = true;+ return false;+ }+ };+ window.addEventListener('test', null, options);+ window.removeEventListener('test', null, options);+ } catch (err) {+ this._passiveSupported = false;+ }++ return this._passiveSupported;+ },++ // Throttle function to limit how often a function can be called+ throttle: function(func, delay) {+ let timeoutId;+ let lastExecTime = 0;++ return function(...args) {+ const currentTime = Date.now();++ if (currentTime - lastExecTime > delay) {+ func.apply(this, args);+ lastExecTime = currentTime;+ } else {+ clearTimeout(timeoutId);+ timeoutId = setTimeout(() => {+ func.apply(this, args);+ lastExecTime = Date.now();+ }, delay - (currentTime - lastExecTime));+ }+ };+ },++ // ===== AUTO-VIEW DECISION LOGIC =====+ handleTransientViewSuggestion: function(suggestion) {+ if (!this.shouldAutoSwitch(suggestion)) {+ return;+ }++ // If already in transient view, switch to new suggestion and reset timer+ if (this.isTransientView) {+ this.clearRevertTimer();+ this.hideTransientViewIndicator();+ }++ this.navigateToTransientView(suggestion);+ },++ shouldAutoSwitch: function(suggestion) {+ const idleTime = Date.now() - this.lastInteractionTime;+ const idleTimeSeconds = idleTime / 1000;++ if (idleTimeSeconds < this.IDLE_TIMEOUT_SECONDS) {+ if (Hi.DEBUG) {+ console.log(`User not idle enough: ${idleTimeSeconds}s < ${this.IDLE_TIMEOUT_SECONDS}s required`);+ }+ return false;+ }++ return true;+ },++ // ===== VIEW MANAGEMENT =====+ navigateToTransientView: function(suggestion) {+ const url = suggestion.url;+ const durationSeconds = suggestion.durationSeconds;++ if (Hi.DEBUG) {+ console.log(`Auto-switching to: ${url} for ${durationSeconds}s (reason: ${suggestion.triggerReason})`);+ }++ // Store current content and URL for potential revert+ if (!this.isTransientView) {+ this.originalContent = $(Hi.MAIN_AREA_SELECTOR).html();+ this.originalUrl = window.location.href;+ this.transientUrls = []; // Reset the list for new transient session+ }++ // Track this URL as it will be pushed by antinode.js+ this.transientUrls.push(url);++ this.isTransientView = true;++ // Load content asynchronously using antinode pattern+ this.loadContentAsync(url);++ // Set revert timer+ this.revertTimer = setTimeout(() => {+ this.revertToOriginalView();+ }, durationSeconds * 1000);++ // Show visual indicator+ this.showTransientViewIndicator(suggestion.triggerReason);+ },++ loadContentAsync: function(url) {+ // Use the new public API from antinode.js for loading async content+ // This feature requires antinode.js to be loaded+ if (!window.AN || !window.AN.loadAsyncContent) {+ console.error('Auto-view requires antinode.js with loadAsyncContent method');+ return;+ }++ window.AN.loadAsyncContent({+ url: url,+ target: Hi.MAIN_AREA_SELECTOR,+ mode: 'insert', // Replace inner content, not the element itself+ error: (xhr, ajaxOptions, thrownError) => {+ console.error(`Auto-view content loading error [${xhr.status}]: ${thrownError}`);+ // Revert on error+ this.revertToOriginalView();+ }+ });+ },++ revertToOriginalView: function() {+ if (!this.isTransientView || !this.originalContent) {+ return;+ }++ if (Hi.DEBUG) {+ console.log(`Reverting to original view and URL: ${this.originalUrl}`);+ }++ // Restore original content directly+ // Note: We can't use AN.loadAsyncContent here since we have HTML content, not a URL+ // We just do direct DOM manipulation since this is reverting to cached content+ const $target = $(Hi.MAIN_AREA_SELECTOR);+ $target.html(this.originalContent);++ // Restore original URL using proper history semantics+ // Since antinode.js pushed the transient URL, we should pop it back off the stack+ this.restoreOriginalUrl();++ // Note: antinode's handleNewContentAdded is internal and handles autofocus/modals+ // Since we're restoring previous content, those behaviors aren't needed here++ this.resetTransientState();+ },++ restoreOriginalUrl: function() {+ if (!this.originalUrl) {+ if (Hi.DEBUG) {+ console.log('No original URL stored, skipping URL restoration');+ }+ return;+ }++ if (Hi.DEBUG) {+ console.log(`Restoring original URL: ${this.originalUrl}, Transient URLs to pop: [${this.transientUrls.join(', ')}]`);+ }++ // Pop all transient URLs with sanity checking+ while (this.transientUrls.length > 0) {+ const expectedUrl = this.transientUrls.pop();+ if (!this.popTransientUrlIfMatches(expectedUrl)) {+ break; // Stop popping and use fallback+ }+ }++ // Final verification: ensure we're on the original URL+ const finalUrl = window.location.href;+ if (finalUrl !== this.originalUrl) {+ if (Hi.DEBUG) {+ console.warn(`Final URL ${finalUrl} doesn't match original ${this.originalUrl}. Using replaceState to enforce invariant.`);+ }+ // Enforce the invariant: original URL must be on top when done+ window.history.replaceState({}, '', this.originalUrl);+ } else {+ if (Hi.DEBUG) {+ console.log(`Successfully restored original URL: ${finalUrl}`);+ }+ }++ // Clear the transient URL list+ this.transientUrls = [];+ },++ makeTransientViewPermanent: function() {+ if (Hi.DEBUG) {+ console.log('Making transient view permanent due to user interaction');+ }++ this.resetTransientState();+ },++ // ===== VISUAL INDICATORS =====+ showTransientViewIndicator: function(reason) {+ // Remove any existing indicator+ this.hideTransientViewIndicator();++ // Add border/frame effect to main content area+ const $mainContent = $(Hi.MAIN_AREA_SELECTOR);+ $mainContent.addClass('auto-view-active');++ // Create corner badge with reason and subtle animation+ const indicator = $(`+ <div id="auto-view-indicator" class="auto-view-corner-badge">+ <div class="auto-view-badge-icon">π</div>+ <div class="auto-view-badge-text">Auto-view: ${this.formatReason(reason)}</div>+ </div>+ `);++ // Portal approach: append to body and calculate position+ $('body').append(indicator);+ this.positionCornerBadge();++ // Reposition on window resize+ $(window).on('resize.auto-view', () => {+ this.positionCornerBadge();+ });+ },++ hideTransientViewIndicator: function() {+ $('#auto-view-indicator').remove();+ $(Hi.MAIN_AREA_SELECTOR).removeClass('auto-view-active');+ $(window).off('resize.auto-view');+ },++ positionCornerBadge: function() {+ const $indicator = $('#auto-view-indicator');+ const $mainContent = $(Hi.MAIN_AREA_SELECTOR);++ if ($indicator.length && $mainContent.length) {+ const mainRect = $mainContent[0].getBoundingClientRect();++ // Position in bottom-right corner of main content area, flush to boundary+ $indicator.css({+ position: 'fixed',+ bottom: $(window).height() - mainRect.bottom,+ right: $(window).width() - mainRect.right,+ maxWidth: mainRect.width,+ zIndex: 9999+ });+ }+ },++ formatReason: function(reason) {+ // Convert technical reasons to user-friendly text+ const reasonMap = {+ 'motion_alert': 'Motion Detected',+ 'security_alert': 'Security Alert',+ 'camera_alert': 'Camera Alert',+ 'sensor_alert': 'Sensor Alert'+ };++ return reasonMap[reason] || reason.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());+ },++ // ===== HELPER METHODS =====+ clearRevertTimer: function() {+ if (this.revertTimer) {+ clearTimeout(this.revertTimer);+ this.revertTimer = null;+ }+ },++ resetTransientState: function() {+ this.clearRevertTimer();+ this.isTransientView = false;+ this.hideTransientViewIndicator();+ this.originalContent = null;+ this.originalUrl = null;+ this.transientUrls = [];+ },++ popTransientUrlIfMatches: function(expectedUrl) {+ const currentUrl = window.location.href;++ if (currentUrl === expectedUrl) {+ if (Hi.DEBUG) {+ console.log(`Popping expected transient URL: ${expectedUrl}`);+ }+ try {+ window.history.back();+ return true;+ } catch (error) {+ console.warn(`Failed to pop URL ${expectedUrl}:`, error);+ return false;+ }+ } else {+ if (Hi.DEBUG) {+ console.warn(`URL mismatch. Expected: ${expectedUrl}, Current: ${currentUrl}. Stopping history manipulation.`);+ }+ return false;+ }+ }+ };++ window.Hi.autoView = AutoView;++ // Initialize when page loads+ window.addEventListener('load', function() {+ AutoView.init();+ });++})();diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.jsindex e1906c57..7ee19e70 100644--- a/src/hi/static/js/main.js+++ b/src/hi/static/js/main.js@@ -5,6 +5,7 @@DEBUG: true,DEBUG_AUDIO: false, // Enable diagnostic background audio testingisEditMode: ( gHiViewMode == 'edit' ), // Set by server to keep front-end in sync with back-end+ MAIN_AREA_SELECTOR: '#hi-main-content',LOCATION_VIEW_AREA_SELECTOR: '#hi-location-view-main',LOCATION_VIEW_SVG_CLASS: 'hi-location-view-svg',LOCATION_VIEW_SVG_SELECTOR: '.hi-location-view-svg',diff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.jsindex e6b8bd7b..00d9b317 100644--- a/src/hi/static/js/status.js+++ b/src/hi/static/js/status.js@@ -33,6 +33,11 @@const CssClassUpdateMapAttr = 'cssClassUpdateMap';const IdReplaceUpdateMapAttr = 'idReplaceUpdateMap';const IdReplaceHashMapAttr = 'idReplaceHashMap';+ const TransientViewSuggestionAttr = 'transientViewSuggestion';+ const TransientViewUrlAttr = 'url';+ const TransientViewDurationSecondsAttr = 'durationSeconds';+ const TransientViewPriorityAttr = 'priority';+ const TransientViewTriggerReasonAttr = 'triggerReason';const AlertStatusDataAttr = 'alertData';const AlertBannerContainerSelector = '#hi-alert-banner-container';@@ -137,6 +142,9 @@if ( CssClassUpdateMapAttr in respObj ) {handleCssClassUpdates( respObj[CssClassUpdateMapAttr] );}+ if ( TransientViewSuggestionAttr in respObj ) {+ handleTransientViewSuggestion( respObj[TransientViewSuggestionAttr] );+ }}function doServerStartTimeCheck( respObj ) {@@ -275,4 +283,27 @@Hi.audio.startAudibleSignal( Hi.audio.INFO_SIGNAL_NAME );}+ function handleTransientViewSuggestion( suggestionData ) {+ if ( Hi.DEBUG ) { console.log('Transient View Suggestion: ', JSON.stringify(suggestionData) ); }++ if ( ! suggestionData ) {+ return;+ }++ // Build suggestion object using constants+ const suggestion = {+ url: suggestionData[TransientViewUrlAttr],+ durationSeconds: suggestionData[TransientViewDurationSecondsAttr],+ priority: suggestionData[TransientViewPriorityAttr],+ triggerReason: suggestionData[TransientViewTriggerReasonAttr]+ };++ // Delegate to the auto-view module+ if ( Hi.autoView && Hi.autoView.handleTransientViewSuggestion ) {+ Hi.autoView.handleTransientViewSuggestion( suggestion );+ } else {+ console.warn('Auto-view module not available');+ }+ }+})();diff --git a/src/hi/tests/ui/__init__.py b/src/hi/testing/__init__.pysimilarity index 100%rename from src/hi/tests/ui/__init__.pyrename to src/hi/testing/__init__.pydiff --git a/src/hi/testing/apps.py b/src/hi/testing/apps.pynew file mode 100644index 00000000..03ec224b--- /dev/null+++ b/src/hi/testing/apps.py@@ -0,0 +1,7 @@+from django.apps import AppConfig+++class TestingConfig(AppConfig):+ default_auto_field = 'django.db.models.BigAutoField'+ name = 'hi.testing'+ verbose_name = 'Testing Utilities'diff --git a/src/hi/tests/async_task_utils.py b/src/hi/testing/async_task_utils.pysimilarity index 100%rename from src/hi/tests/async_task_utils.pyrename to src/hi/testing/async_task_utils.pydiff --git a/src/hi/tests/base_test_case.py b/src/hi/testing/base_test_case.pysimilarity index 100%rename from src/hi/tests/base_test_case.pyrename to src/hi/testing/base_test_case.pydiff --git a/src/hi/testing/dev_injection.py b/src/hi/testing/dev_injection.pynew file mode 100644index 00000000..1d6eaeb7--- /dev/null+++ b/src/hi/testing/dev_injection.py@@ -0,0 +1,211 @@+import os+import json+import logging+from django.conf import settings+from django.core.cache import cache++logger = logging.getLogger(__name__)+++class DevInjectionManager:+ """+ External data injection for development testing.++ THEORY OF OPERATION:+ Injects test data into API responses for frontend testing without modifying+ backend state or triggering Django auto-reload. Requires DEBUG=True and+ specific DEBUG_FORCE_* flags enabled.++ USAGE:+ # Inject test data+ python manage.py dev_inject transient_view '{"url":"/test","durationSeconds":10}'++ # Options: --persistent, --cache, --list, --clear++ ADDING NEW INJECTION POINTS:+ 1. Add DEBUG_FORCE_<NAME>_OVERRIDE = False to settings/base.py and development.py+ 2. Add get_<name>_override() and inject_<name>() methods to this class+ 3. Update inject_override_if_available() method+ 4. Add single line check to target view:+ if settings.DEBUG and getattr(settings, 'DEBUG_FORCE_<NAME>_OVERRIDE', False):+ DevInjectionManager.inject_override_if_available('<name>', data, 'key')+ 5. Update management command with new injection type+ """++ CACHE_PREFIX = 'dev_inject_'+ DATA_DIR = '/tmp/hi_dev_overrides'++ @classmethod+ def _ensure_data_dir(cls):+ """Create data directory if it doesn't exist."""+ if not os.path.exists(cls.DATA_DIR):+ os.makedirs(cls.DATA_DIR, exist_ok=True)++ @classmethod+ def _get_file_path(cls, key):+ """Get file path for given injection key."""+ cls._ensure_data_dir()+ return os.path.join(cls.DATA_DIR, f"{key}.json")++ @classmethod+ def get_transient_view_override(cls):+ """+ Get transient view override data if force flag is enabled.+ Returns None if not enabled or no data available.+ """+ if not (settings.DEBUG+ and getattr(settings, 'DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE', False)):+ return None++ # Check cache first (for one-time use)+ cache_key = f"{cls.CACHE_PREFIX}transient_view"+ cached_data = cache.get(cache_key)+ if cached_data:+ if cached_data.get('one_time', True):+ cache.delete(cache_key)+ if settings.DEBUG:+ logger.info("DevInjection: Used one-time transient view override from cache")+ else:+ if settings.DEBUG:+ logger.info("DevInjection: Used persistent transient view override from cache")+ return cached_data['data']++ # Check file (for persistent or file-based overrides)+ file_path = cls._get_file_path('transient_view')+ if os.path.exists(file_path):+ try:+ with open(file_path, 'r') as f:+ file_data = json.load(f)++ payload = file_data.get('payload')+ if file_data.get('one_time', True):+ os.remove(file_path) # One-time use+ if settings.DEBUG:+ logger.info("DevInjection: Used one-time transient view override from file")+ else:+ if settings.DEBUG:+ logger.info("DevInjection: Used persistent transient view override from file")++ return payload++ except (json.JSONDecodeError, IOError) as e:+ if settings.DEBUG:+ logger.warning(f"DevInjection: Error reading transient view override file: {e}")+ # Clean up bad file+ try:+ os.remove(file_path)+ except OSError:+ pass++ return None++ @classmethod+ def inject_transient_view(cls, payload, one_time=True, use_cache=False):+ """+ Inject transient view data externally.++ Args:+ payload (dict): The transient view data to inject+ one_time (bool): Whether this should be consumed once or persist+ use_cache (bool): Whether to use cache (faster) or file (survives restarts)++ Returns:+ bool: True if injection was set up successfully+ """+ if not settings.DEBUG:+ if settings.DEBUG:+ logger.warning("DevInjection: Attempted injection in non-DEBUG mode")+ return False++ data = {'data': payload, 'one_time': one_time}++ if use_cache:+ cache_key = f"{cls.CACHE_PREFIX}transient_view"+ timeout = 300 if one_time else None # 5 min timeout for one-time, none for persistent+ cache.set(cache_key, data, timeout=timeout)+ if settings.DEBUG:+ logger.info(f"DevInjection: Set transient view override in cache (one_time={one_time})")+ else:+ file_data = {'payload': payload, 'one_time': one_time}+ file_path = cls._get_file_path('transient_view')+ try:+ with open(file_path, 'w') as f:+ json.dump(file_data, f, indent=2)+ if settings.DEBUG:+ logger.info(f"DevInjection: Set transient view override in file (one_time={one_time})")+ except IOError as e:+ if settings.DEBUG:+ logger.error(f"DevInjection: Failed to write override file: {e}")+ return False++ return True++ @classmethod+ def inject_override_if_available(cls, override_type, data_dict, key):+ """+ Single utility method for all injection points.+ This is the method called from the main code with your single-line pattern.++ Args:+ override_type (str): Type of override ('transient_view', etc.)+ data_dict (dict): The response dictionary to modify+ key (str): The key in data_dict to override+ """+ override_data = None++ if override_type == 'transient_view':+ override_data = cls.get_transient_view_override()+ # Future: Add other override types here+ # elif override_type == 'alert_status':+ # override_data = cls.get_alert_status_override()++ if override_data:+ data_dict[key] = override_data+ if settings.DEBUG:+ logger.info(f"DevInjection: Applied {override_type} override to response")++ @classmethod+ def clear_all_overrides(cls):+ """Clear all cached and file-based overrides."""+ if not settings.DEBUG:+ return False++ # Clear cache+ cache_keys = [f"{cls.CACHE_PREFIX}transient_view"]+ for key in cache_keys:+ cache.delete(key)++ # Clear files+ if os.path.exists(cls.DATA_DIR):+ try:+ for filename in os.listdir(cls.DATA_DIR):+ if filename.endswith('.json'):+ os.remove(os.path.join(cls.DATA_DIR, filename))+ if settings.DEBUG:+ logger.info("DevInjection: Cleared all overrides")+ return True+ except OSError as e:+ if settings.DEBUG:+ logger.error(f"DevInjection: Error clearing overrides: {e}")++ return False++ @classmethod+ def list_active_overrides(cls):+ """List all currently active overrides for debugging."""+ if not settings.DEBUG:+ return {}++ active = {}++ # Check cache+ cache_key = f"{cls.CACHE_PREFIX}transient_view"+ if cache.get(cache_key):+ active['transient_view_cache'] = True++ # Check files+ file_path = cls._get_file_path('transient_view')+ if os.path.exists(file_path):+ active['transient_view_file'] = True++ return activediff --git a/src/hi/tests/utils/__init__.py b/src/hi/testing/management/__init__.pysimilarity index 100%rename from src/hi/tests/utils/__init__.pyrename to src/hi/testing/management/__init__.pydiff --git a/src/hi/testing/management/commands/__init__.py b/src/hi/testing/management/commands/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/testing/management/commands/dev_inject.py b/src/hi/testing/management/commands/dev_inject.pynew file mode 100644index 00000000..fa9de031--- /dev/null+++ b/src/hi/testing/management/commands/dev_inject.py@@ -0,0 +1,99 @@+import json+from django.core.management.base import BaseCommand, CommandError+from hi.testing.dev_injection import DevInjectionManager+++class Command(BaseCommand):+ help = 'Inject test data into API responses for frontend development testing'++ def add_arguments(self, parser):+ parser.add_argument(+ 'injection_type',+ choices=['transient_view'],+ help='Type of data to inject'+ )+ parser.add_argument(+ 'data',+ help='JSON data to inject'+ )+ parser.add_argument(+ '--persistent',+ action='store_true',+ help='Use persistent injection instead of one-time (default: one-time)'+ )+ parser.add_argument(+ '--cache',+ action='store_true',+ help='Use cache storage instead of file storage (default: file)'+ )+ parser.add_argument(+ '--clear',+ action='store_true',+ help='Clear all existing overrides instead of injecting'+ )+ parser.add_argument(+ '--list',+ action='store_true',+ help='List all active overrides'+ )++ def handle(self, *args, **options):+ # Handle special actions first+ if options['list']:+ active = DevInjectionManager.list_active_overrides()+ if active:+ self.stdout.write(self.style.SUCCESS("Active overrides:"))+ for key, value in active.items():+ self.stdout.write(f" {key}: {value}")+ else:+ self.stdout.write("No active overrides")+ return++ if options['clear']:+ success = DevInjectionManager.clear_all_overrides()+ if success:+ self.stdout.write(self.style.SUCCESS("Cleared all overrides"))+ else:+ self.stdout.write(self.style.ERROR("Failed to clear overrides (not in DEBUG mode?)"))+ return++ # Parse and validate JSON data+ try:+ data = json.loads(options['data'])+ except json.JSONDecodeError as e:+ raise CommandError(f"Invalid JSON data: {e}")++ # Inject based on type+ injection_type = options['injection_type']+ one_time = not options['persistent']+ use_cache = options['cache']++ if injection_type == 'transient_view':+ # Validate transient view data structure+ required_keys = ['url']++ for key in required_keys:+ if key not in data:+ raise CommandError(f"Missing required key '{key}' in transient view data")++ success = DevInjectionManager.inject_transient_view(+ data, one_time=one_time, use_cache=use_cache+ )+ else:+ raise CommandError(f"Unknown injection type: {injection_type}")++ if success:+ storage_type = "cache" if use_cache else "file"+ persistence = "one-time" if one_time else "persistent"+ self.stdout.write(+ self.style.SUCCESS(+ f"Injected {injection_type} data ({persistence}, {storage_type})"+ )+ )+ else:+ self.stdout.write(+ self.style.ERROR(+ "Injection failed - check that DEBUG mode is enabled and "+ "DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE is True in settings"+ )+ )diff --git a/src/hi/testing/templates/testing/pages/testing_home.html b/src/hi/testing/templates/testing/pages/testing_home.htmlnew file mode 100644index 00000000..d2bf2c1c--- /dev/null+++ b/src/hi/testing/templates/testing/pages/testing_home.html@@ -0,0 +1,13 @@+{% extends "pages/base.html" %}+{% block head_title %}HI: Testing Home Page{% endblock %}++{% block content %}+<div class="container-fluid m-4">++ <h2 class="text-info">Testing Home</h2>++ <ul>+ <li><a href='{% url 'testing_ui_home' %}'>UI Testing</a></li>+ </ul>+</div>+{% endblock %}diff --git a/src/hi/tests/templates/tests/ui/email_preview.html b/src/hi/testing/templates/testing/ui/modals/email_preview.htmlsimilarity index 100%rename from src/hi/tests/templates/tests/ui/email_preview.htmlrename to src/hi/testing/templates/testing/ui/modals/email_preview.htmldiff --git a/src/hi/templates/tests/ui/home.html b/src/hi/testing/templates/testing/ui/pages/testing_ui_home.htmlsimilarity index 100%rename from src/hi/templates/tests/ui/home.htmlrename to src/hi/testing/templates/testing/ui/pages/testing_ui_home.htmldiff --git a/src/hi/testing/ui/__init__.py b/src/hi/testing/ui/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/tests/ui/email_test_views.py b/src/hi/testing/ui/email_test_views.pysimilarity index 96%rename from src/hi/tests/ui/email_test_views.pyrename to src/hi/testing/ui/email_test_views.pyindex f5fcdeec..f0872594 100644--- a/src/hi/tests/ui/email_test_views.py+++ b/src/hi/testing/ui/email_test_views.py@@ -56,4 +56,4 @@ class EmailTestViewView( View ):'body_html_template': body_html_template,'body_html': escaped_email_html,})- return render( request, 'tests/ui/email_preview.html', context )+ return render( request, 'testing/ui/modals/email_preview.html', context )diff --git a/src/hi/tests/ui/urls.py b/src/hi/testing/ui/urls.pysimilarity index 94%rename from src/hi/tests/ui/urls.pyrename to src/hi/testing/ui/urls.pyindex 8b5be56b..0b9d1b17 100644--- a/src/hi/tests/ui/urls.py+++ b/src/hi/testing/ui/urls.py@@ -22,7 +22,7 @@ def get_tests_ui_urls():urlpatterns = [re_path( r'^$',views.TestingHomeView.as_view(),- name='testing_home'),+ name='testing_ui_home'),]urlpatterns += get_tests_ui_urls()diff --git a/src/hi/tests/ui/views.py b/src/hi/testing/ui/views.pysimilarity index 92%rename from src/hi/tests/ui/views.pyrename to src/hi/testing/ui/views.pyindex 9d00ce08..881495d0 100644--- a/src/hi/tests/ui/views.py+++ b/src/hi/testing/ui/views.py@@ -31,4 +31,4 @@ class TestingHomeView( View ):context = {'app_url_list': app_url_list,}- return render(request, 'tests/ui/home.html', context )+ return render(request, 'testing/ui/pages/testing_ui_home.html', context )diff --git a/src/hi/testing/urls.py b/src/hi/testing/urls.pynew file mode 100644index 00000000..0121f7ba--- /dev/null+++ b/src/hi/testing/urls.py@@ -0,0 +1,15 @@+from django.urls import include, re_path++from . import views+++urlpatterns = [++ re_path( r'^$',+ views.TestingHomeView.as_view(),+ name='testing_home'),++ re_path( r'^ui/', include('hi.testing.ui.urls' )),++]+diff --git a/src/hi/testing/utils/__init__.py b/src/hi/testing/utils/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/tests/utils/log_filters.py b/src/hi/testing/utils/log_filters.pysimilarity index 100%rename from src/hi/tests/utils/log_filters.pyrename to src/hi/testing/utils/log_filters.pydiff --git a/src/hi/tests/view_test_base.py b/src/hi/testing/view_test_base.pysimilarity index 99%rename from src/hi/tests/view_test_base.pyrename to src/hi/testing/view_test_base.pyindex d2ec4589..f58707ea 100644--- a/src/hi/tests/view_test_base.py+++ b/src/hi/testing/view_test_base.py@@ -5,7 +5,7 @@ from django.contrib.auth import get_user_modelfrom django.http import HttpResponsefrom django.test import Client-from hi.tests.base_test_case import BaseTestCase+from hi.testing.base_test_case import BaseTestCasefrom hi.enums import ViewType, ViewModefrom hi.apps.location.models import LocationViewfrom hi.apps.collection.models import Collectiondiff --git a/src/hi/testing/views.py b/src/hi/testing/views.pynew file mode 100644index 00000000..d0e07a88--- /dev/null+++ b/src/hi/testing/views.py@@ -0,0 +1,8 @@+from django.shortcuts import render+from django.views.generic import View+++class TestingHomeView( View ):++ def get(self, request, *args, **kwargs):+ return render( request, 'testing/pages/testing_home.html' )diff --git a/src/hi/tests/test_views.py b/src/hi/tests/test_views.pyindex 9109a230..5009f25b 100644--- a/src/hi/tests/test_views.py+++ b/src/hi/tests/test_views.py@@ -5,7 +5,7 @@ from django.urls import reversefrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewMode, ViewType-from hi.tests.view_test_base import SyncViewTestCase+from hi.testing.view_test_base import SyncViewTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/urls.py b/src/hi/urls.pyindex dbe804eb..e8621287 100644--- a/src/hi/urls.py+++ b/src/hi/urls.py@@ -63,5 +63,5 @@ handler404 = 'hi.views.custom_404_handler'if settings.DEBUG:urlpatterns += [- re_path( r'^tests/ui/', include('hi.tests.ui.urls' )),+ re_path( r'^testing', include('hi.testing.urls' )),]