Home Information - Your home, your data, organized.
Python
Complete the three initial EntityStatusPanel implementations (#340)
Tony C4a7d6d950701
diff --git a/.claude/commands/pickup.md b/.claude/commands/pickup.mdindex e74f668b..d174d044 100644--- a/.claude/commands/pickup.md+++ b/.claude/commands/pickup.md@@ -14,7 +14,24 @@ This command does NOT write code, commit, or push implementation changes. For ba1. **Load context.** Read `docs/CLAUDE.md` for development philosophy and standards. Use TodoWrite to track pickup steps.-2. **Read the issue.** Run `gh issue view $0 --comments`. Understand requirements, context, and any prior design decisions in the thread.+2. **Read the issue body AND every comment.** Comments often carry decisive design refinements; never plan from the body alone.++ Use a JSON projection so the GitHub Projects-classic deprecation warning (which makes `gh issue view --comments` exit non-zero on some repos) cannot mask comment retrieval:++ ```bash+ gh issue view $0 --json title,body,state,labels,assignees,comments+ ```++ If the JSON command itself fails for any reason, fall back to fetching body and comments as two separate calls and confirm BOTH succeeded before proceeding:++ ```bash+ gh issue view $0 --json title,body,state,labels,assignees+ gh api repos/{owner}/{repo}/issues/$0/comments+ ```++ Do not substitute `gh api repos/.../issues/$0` alone — that endpoint returns only the body, not the comments thread, and silently produces an incomplete picture.++ Before moving to step 3, verify the comments array was retrieved (it may legitimately be empty; an empty array is OK, a missing field is not). If any comment is present, read it in full and treat its content as authoritative alongside the body.3. **Safety check.** Run `git status`; abort if the working tree is not clean.diff --git a/docs/dev/frontend/entity-display-overview.md b/docs/dev/frontend/entity-display-overview.mdindex ba9bf3b7..71952ec4 100644--- a/docs/dev/frontend/entity-display-overview.md+++ b/docs/dev/frontend/entity-display-overview.md@@ -35,10 +35,10 @@ The same polling pipeline drives four visually distinct surfaces. Each surface h|---|---|---|| **LocationView SVG icons** | The map view's `<g>` icon elements per positioned entity | [`entity-visual-configuration.md`](entity-visual-configuration.md) || **LocationView SVG paths** | The map view's `<path>` elements per area-based entity | [`entity-visual-configuration.md`](entity-visual-configuration.md) |-| **Entity status modal** | Body of the per-entity status dialog | [`entity-status-panels.md`](entity-status-panels.md) |-| **Collection cards** | Per-entity cards in the list and grid layouts of a collection view | [`entity-status-panels.md`](entity-status-panels.md) |+| **Entity status modal** | Body of the per-entity status dialog | [`entity-state-panels.md`](entity-state-panels.md) |+| **Collection cards** | Per-entity cards in the list and grid layouts of a collection view | [`entity-state-panels.md`](entity-state-panels.md) |-The modal and collection-card surfaces share an `EntityStatusPanel` dispatch: a panel for a given `EntityType` provides up to three templates (`modal.html` / `list.html` / `grid.html`), with a framework fallback supplying a flat state list when no per-type panel exists.+The modal and collection-card surfaces share an `EntityStatePanel` dispatch: a panel for a given `EntityType` provides up to three templates (`modal.html` / `list.html` / `grid.html`), with a framework fallback supplying a flat state list when no per-type panel exists.## The polling contract is the connective tissue@@ -62,7 +62,7 @@ The full grammar, the server payload shape, and the rules about which declaratioBy task:- **Adding visual support for a new `EntityType` on the map** (icon or path) — [`entity-visual-configuration.md`](entity-visual-configuration.md).-- **Authoring a custom panel for a new `EntityType`** (modal / list / grid bodies) — [`entity-status-panels.md`](entity-status-panels.md).+- **Authoring a custom panel for a new `EntityType`** (modal / list / grid bodies) — [`entity-state-panels.md`](entity-state-panels.md).- **Modifying the polling-update mechanism**, the wire format, the color palette, or the per-element declaration grammar — [`entity-status-display.md`](entity-status-display.md).By component:diff --git a/docs/dev/frontend/entity-state-panels.md b/docs/dev/frontend/entity-state-panels.mdnew file mode 100644index 00000000..49b4e19b--- /dev/null+++ b/docs/dev/frontend/entity-state-panels.md@@ -0,0 +1,240 @@+# Entity State Panels++EntityStatePanels render the body of the entity status modal and of the per-entity cards inside collections. The framework dispatches per-`EntityType`, picking from one or more **panel declarations** that target that type. Each panel can present its entity in whatever form best fits — a flat state list, a graphical dial, a video frame, etc. — while the surrounding modal / card chrome stays uniform.++This document covers authoring a new panel.++**Related docs:**+- [`entity-display-overview.md`](entity-display-overview.md) — high-level architecture and how panels fit alongside the other display surfaces.+- [`entity-status-display.md`](entity-status-display.md) — the polling-update contract that panel templates and panel JS plug into.++## Concepts++A panel is a Python declaration plus a bundle of templates and static assets:++- The **declaration** (an `EntityStatePanel` instance constructed in `panel.py`) names the panel, the `EntityType` it claims, the `DisplayContext`s it handles, its priority, and the `EntityStateRole`s it requires and optionally uses.+- The **template** renders the panel body. Templates are context-agnostic: panels that need to look meaningfully different across display contexts should split into separate declarations, not branch inside a single template.+- The **static** assets — CSS and optional JS — handle visual styling and any custom polling-time behavior.++**EntityType is user-adjustable and is decoupled from an entity's actual `EntityStateRole` set.** A user can mark any entity as `THERMOSTAT` regardless of which states it happens to expose. The framework therefore selects panels by the intersection of `(EntityType, DisplayContext, EntityStateRoles present)` and provides framework-level behavior when no panel matches.++A single `EntityType` may have multiple panel declarations, distinguished by their required-role sets and their display contexts. This is the recommended way to express layout variants (single setpoint vs dual setpoint, modal-vs-grid divergence, etc.) — separate panels rather than conditional templates.++When no panel matches, the framework falls back to a flat state list. The fallback is itself a registered panel — see `state_panels/fallback/`.++## Anatomy++```+src/hi/apps/entity/state_panels/<name>/+ panel.py # required: one or more EntityStatePanel instances at module scope++src/hi/apps/entity/templates/entity/state_panels/<name>/+ <author-chosen>.html # the template(s) named by panel.py++src/hi/static/state_panels/<name>/+ <author-chosen>.css # optional+ <author-chosen>.js # optional, registers JS handlers+```++`<name>` is the panel's unique identifier and also the directory name. It is not tied to `EntityType.name` — multiple panels per type share the type but have distinct names (e.g. `thermostat_dual_setpoint`, `thermostat_single_setpoint`).++There is no enforced template filename. The declaration names the template explicitly; convention is to keep it under `entity/state_panels/<name>/`. Whether one panel uses one template across all its declared contexts, or different panels use different templates per context, is the author's call expressed through the declaration set.++## Panel declaration++Each panel is an [`EntityStatePanel`](../../../src/hi/apps/entity/state_panel_base.py) dataclass instance with the following fields:++| Field | Required | Meaning |+|---|---|---|+| `name` | yes | Unique identifier across all panels. By convention matches the directory name under `state_panels/`. |+| `display_contexts` | yes | Set of `DisplayContext` members this panel handles. No implicit inheritance: declaring `{DisplayContext.MODAL}` does not make the panel apply elsewhere. |+| `priority` | yes | Lower checked first; alphabetical `name` is a stable tiebreaker. |+| `template_name` | yes | Template path (e.g. `entity/state_panels/thermostat_single_setpoint/panel.html`). |+| `entity_type` | optional | The `EntityType` this panel claims. `None` (the default) marks a framework fallback panel: matched only after no type-specific panel matches. |+| `required_roles` | optional | Conjunctive. Panel is selected only when every role is present on the entity. Once selected, the template may assume every required role is in `state_status_data_by_role`. Defaults to empty. |+| `optional_roles` | optional | Roles the panel knows about and will display when present. Templates use `{% if %}` only for these. Defaults to empty. |+| `role_data_template_aliases` | optional | `Dict[str, EntityStateRole]` mapping template-context variable names to declared roles. The dispatcher resolves each alias against the entity's by-role map so templates can use `{{ current_data.entity_state.id }}` directly instead of chaining `{% with %}` blocks. Absent optional roles resolve to `None`. Aliased roles must be in `required_roles ∪ optional_roles`. Recommended for panels with 5+ named roles; smaller panels can read the by-role dict directly. Defaults to empty. |++`required_roles` and `optional_roles` must be disjoint. Together they form the panel's **declared** role set; any `EntityStateRole` on the entity outside this set is an **extra** (see "Display contexts and extras" below).++Worked example:++```python+# src/hi/apps/entity/state_panels/thermostat_single_setpoint/panel.py+from hi.apps.entity.enums import DisplayContext, EntityStateRole, EntityType+from hi.apps.entity.state_panel_base import EntityStatePanel+++panel = EntityStatePanel(+ name = 'thermostat_single_setpoint',+ entity_type = EntityType.THERMOSTAT,+ display_contexts = { DisplayContext.MODAL, DisplayContext.LIST, DisplayContext.GRID },+ priority = 20,+ required_roles = {+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ EntityStateRole.HVAC_ACTION,+ },+ optional_roles = {+ EntityStateRole.HVAC_MODE,+ EntityStateRole.FAN_MODE,+ EntityStateRole.PRESET_MODE,+ EntityStateRole.HUMIDITY,+ },+ template_name = 'entity/state_panels/thermostat_single_setpoint/panel.html',+)+```++At app-ready time, [`state_panel_registry.py`](../../../src/hi/apps/entity/state_panel_registry.py) imports each `state_panels/<name>/panel.py` and registers every `EntityStatePanel` instance at module scope. A module may declare one panel (typical) or multiple (siblings sharing CSS/JS or a templates directory).++For the resolution algorithm the framework uses to choose among matching declarations, read [`state_panel_dispatch.py`](../../../src/hi/apps/entity/state_panel_dispatch.py) directly.++## Display contract++Every `EntityStateRole` declared in `required_roles` or `optional_roles` is the panel's promise to the user: the panel must display the state (or its control) for any declared role that is present. If the panel does not show a role, it must not be in the declaration. Required-role guarantees let the template skip the `{% if %}` guard; optional-role presence is checked with `{% if %}`.++Extras — roles on the entity outside the panel's declared set — are framework-owned. The panel template does not see them.++## Display contexts and extras++| `DisplayContext` | Extras behavior |+|---|---|+| `MODAL` | Framework auto-appends an expandable **"Other states"** section below the panel chrome whenever extras exist. Renders each extra row using the existing fallback `state_row.html`. |+| `LIST` | Framework ignores extras silently. |+| `GRID` | Framework ignores extras silently. |++This produces a framework-level invariant for the modal context: **every `EntityState` on an entity is reachable in the modal view, always.** Either the active panel handles it (declared role) or the framework surfaces it (extra). Authors cannot opt out — the contract belongs to the user.++Grid and list are compact-by-intent; extras are intentionally invisible there to keep card layouts tight. Users who want to see every state open the modal.++## Template authoring++Panel templates render inside the wrapper's chrome. They must not duplicate the entity name, integration logo, or type label that the wrapper already supplies.++When a panel template runs, the parent context plus the entity's display projection are flattened together, so the following names are top-level:++| Name | What it is |+|---|---|+| `entity` | The `Entity` model instance. |+| `entity_status_data` | The `EntityDisplayData` wrapper. |+| `state_status_data_list` | Ordered list of `EntityStateDisplayData` for the entity's states (sorted per `ENTITY_STATUS_VIEW_ORDERING`). |+| `state_status_data_by_role` | Dict keyed by lowercase `EntityStateRole.name`. **Every required role is guaranteed present in this dict** for the selected panel. |+| `entity_for_video` | The `Entity` whose video stream this panel should embed, or `None`. |+| `display_only_svg_icon_item` | The framework `SvgIconItem` for the entity's type icon, or `None`. |+| `display_category` | `EntityDisplayCategory` enum value for layout hints (`HAS_VIDEO` / `HAS_STATE` / `PLAIN`). |++Source of truth: `EntityDisplayData.to_template_context()` in [`display_data.py`](../../../src/hi/apps/monitor/display_data.py).++Two ways to reach a specific role's data from a template:++**A — direct lookup (fine for 1–4 roles per template).** Bind a single `{% with %}`:++```django+{% with current_data=state_status_data_by_role.thermostat_current_temperature %}+ <span data-state-id="{{ current_data.entity_state.id }}"+ data-display-text>{{ current_data.display.text }}</span>+{% endwith %}+```++Note: Django's `{% with %}` tag does not parse across newlines — keep the whole tag on one line, including any multi-key form.++**B — `role_data_template_aliases` (recommended for 5+ roles).** Declare the aliases in `panel.py` and access them as top-level template variables:++```python+# panel.py+panel = EntityStatePanel(+ ...+ role_data_template_aliases = {+ 'current_data': EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ 'target_data': EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ ...+ },+)+```++```django+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# current_data, target_data, ... #}+<span data-state-id="{{ current_data.entity_state.id }}"+ data-display-text>{{ current_data.display.text }}</span>+{% if fan_data %}<!-- render fan controls -->{% endif %}+```++Required-role aliases are guaranteed non-`None` when the panel is selected. Optional-role aliases resolve to `None` when the role isn't present on the entity; guard with `{% if %}`. Templates that use aliases should include a top-of-file comment listing the aliases so readers don't have to bounce to `panel.py` to know the variable origins.++For the live-update declaration grammar, server payload shape, and the icon-vs-path asymmetry, see [`entity-status-display.md`](entity-status-display.md). Authoring a panel template is mostly a matter of (1) pulling the right state via `state_status_data_by_role` or `state_status_data_list`, and (2) tagging the elements that should refresh.++### Recent state-value history++`EntityStateDisplayData` exposes `recent_state_value_summary` — a display-ready view of the cached `SensorResponse` list (up to 5 entries, newest-first, already deduplicated by value change in `SensorResponseManager`). Each entry's `display_label` flows through the same `ConsoleConverterHelper` pipeline as `latest_display_label`, so history rows render in the user's preferred unit without per-template conversion.++Shape:++```python+summary.latest # StateValueEntry | None (entries[0])+summary.penultimate # StateValueEntry | None (entries[1])+summary.entries # list[StateValueEntry] (newest-first, up to 5)++# StateValueEntry: display_label: str, timestamp: datetime+```++Template idiom:++```django+{% if recent_state_value_summary and recent_state_value_summary.penultimate %}+ <div class="last-event">+ Triggered {{ recent_state_value_summary.penultimate.timestamp|naturaltime }}+ </div>+{% endif %}+```++The summary is `None` when the cache is empty (fresh install, cache cleared, sensor never reported). Panels should treat that as "nothing to show" rather than as an error — the framework makes no completeness claim and does not query the `SensorHistory` DB. The summary is also **not** included in the polling-update payload: panels see it only at server-side render. Status-attribute decay (`status="recent"` / `"past"`) continues to refresh live; "X minutes ago" detail does not tick second-by-second. Templates that want timestamp detail should gate it by status decay so an aged-out event doesn't keep advertising itself indefinitely.++## JS extensions++Most panels need no JavaScript — declarative HTML attributes and CSS rules carry all the live-update work. When more is needed (e.g., re-positioning an SVG marker from a numeric magnitude), register a handler with `Hi.statePanels`:++- **`Hi.statePanels.registerUpdate(handler)`** — fires after each polling apply pass, receiving the full status map keyed by state id. Use this for refresh-time work the declarative contract can't express.+- **`Hi.statePanels.registerInit(handler)`** — fires on initial page load *and* after every async content insertion (entity status modal opens, collection refreshes). Use this to position elements from server-rendered data. Handlers must be idempotent — they re-scan the document on each call.++API source: [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js).++### Keeping render-time and update-time in sync++Templates render initial values into HTML — often as `data-*` attributes on the same elements that opt into the polling contract. The polling-update apply pass then refreshes those values on each tick. When a panel does *further* derivation from those values — for example, computing an SVG marker angle from a numeric magnitude carried in `data-temp-value` — that derivation must run in both places: once via `registerInit` against the server-rendered initial value, and again via `registerUpdate` for every subsequent tick. Both hooks should call the same routine so the initial frame and every later frame stay consistent.++This is why derivations live in JS, not in a parallel Python helper: a Python implementation would only run at render time, leaving update-time to do the same math separately and drift.++## Debug++Append `?debug_panel=1` to any view that renders an entity status panel to see the dispatch trace inline (and in the DEBUG log).++## Walkthrough: adding a panel++1. Pick a `<name>` unique across all panels (typically `<entity_type>_<variant>` if variants are anticipated, or just `<entity_type>` for a single panel).+2. Create `src/hi/apps/entity/state_panels/<name>/panel.py` that constructs an `EntityStatePanel` at module scope. Set `display_contexts`, `priority`, `required_roles`, `optional_roles`, `template_name`, and `entity_type` (omit `entity_type` only if the panel is a framework fallback).+3. Create the template at the path named by `template_name`.+4. Fetch required-role states via `state_status_data_by_role.<role_name>` (lowercase `EntityStateRole.name`) — no `{% if %}` needed. Guard optional-role access with `{% if %}`.+5. Tag refreshable elements per the polling-update contract (see [`entity-status-display.md`](entity-status-display.md)).+6. Drop panel-private CSS and JS in `src/hi/static/state_panels/<name>/` if needed.+7. Register any panel JS handlers via `Hi.statePanels.registerInit` / `registerUpdate`.+8. Verify in the simulator: open the entity status modal, change values on the simulator side, watch the panel refresh; open a collection containing the entity and check the list and grid contexts. If the panel doesn't render where expected, hit the URL with `?debug_panel=1` and check the resolution trace.++## Exemplars++Read the existing panels when starting a new one — copy from the closest match.++- **[`fallback/`](../../../src/hi/apps/entity/templates/entity/state_panels/fallback/)** — universal flat state list. Authors needing the standard rendering can include `fallback/state_list.html` directly.+- **[`smoke_detector/`](../../../src/hi/apps/entity/templates/entity/state_panels/smoke_detector/)** — CSS-only panel. Status-attribute-driven variants switch icon and label visibility without any JS.+- **[`thermostat_*`](../../../src/hi/apps/entity/templates/entity/state_panels/)** — multi-declaration thermostat family. Role-keyed state lookups, custom CSS, init + update JS hooks for an SVG dial.+- **[`camera/`](../../../src/hi/apps/entity/templates/entity/state_panels/camera/)** — embeds the live view alongside camera controls.++## Pitfalls++- **`data-svg-style` is for single-element styling.** Don't put it on a multi-element SVG `<g>` icon — children inherit the pushed `fill`/`stroke` attributes and lose their differentiated styling. Use `data-status` and CSS branching instead. See [`entity-status-display.md`](entity-status-display.md#icon-vs-path-update-shape) for the full rationale.+- **Init handlers must be idempotent.** `registerInit` fires on both initial DOM-ready and every async content insertion. Handlers re-scan the document each time; applying state to already-initialized elements must be safe.+- **Don't duplicate chrome.** The modal wrapper supplies the type icon, entity name, integration logo, and type label in its subheader. The collection-card wrappers supply the entity-name title and (when applicable) the video stream. Panel bodies render below this chrome and should not repeat any of it.+- **Don't render extras inside the panel.** The modal context auto-appends an "Other states" section for any role outside the panel's declared set. Panels that try to render unknown states inside their own chrome will duplicate them.+- **Declare what you display, display what you declare.** If a role appears in `required_roles` or `optional_roles`, the template must render it (subject to `{% if %}` for optionals). If a role is rendered but not declared, the framework will still treat it as an "extra" and may surface it twice in modal.+- **Don't branch a template by `DisplayContext`.** If the panel needs context-specific layout, split into separate declarations with their own templates rather than `{% if context == ... %}` inside one file.+- **Shared partials live where they were first authored.** The flat state list and per-state row templates live under `state_panels/fallback/` (where they were born). Other panels that want the same list reference them from that path; there's no separate "shared" namespace.diff --git a/docs/dev/frontend/entity-status-display.md b/docs/dev/frontend/entity-status-display.mdindex fea1b0f1..d01a4135 100644--- a/docs/dev/frontend/entity-status-display.md+++ b/docs/dev/frontend/entity-status-display.md@@ -2,12 +2,14 @@Reference for the polling-update contract that connects backend state to live DOM. Covers the server payload shape, the per-element declaration grammar, the status-value vocabulary, the color palette, and the icon-vs-path asymmetry.-If you're new to entity display, start with [`entity-display-overview.md`](entity-display-overview.md). For consuming the contract from authoring contexts, see [`entity-status-panels.md`](entity-status-panels.md) (panel authoring) and [`entity-visual-configuration.md`](entity-visual-configuration.md) (SVG asset authoring).+If you're new to entity display, start with [`entity-display-overview.md`](entity-display-overview.md). For consuming the contract from authoring contexts, see [`entity-state-panels.md`](entity-state-panels.md) (panel authoring) and [`entity-visual-configuration.md`](entity-visual-configuration.md) (SVG asset authoring).## The flow in one paragraphOn every `/api/status` poll, [`StatusDisplayManager`](../../../src/hi/apps/monitor/status_display_manager.py) builds an `entityStateStatusMap` keyed by `EntityState.id` (as a string). The JS dispatcher in [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js) walks every DOM element carrying `data-state-id="<id>"`, looks up the row for that state, and writes whatever subset the element opted into via declaration attributes. No descendant traversal, no class-as-join — each element opts in directly.+The set of state ids in the map can grow or shrink between polls (e.g., an entity gains or loses an `EntityState`). Elements whose id is missing from the current map are left untouched on this tick; ids that newly appear are picked up on the next tick by any element that opts in. Custom `registerUpdate` handlers should follow the same shape — look up by id, no-op when the entry is absent.+## Server payload shapePer-state row, built by [`EntityStateDisplayData.to_polling_update_dict`](../../../src/hi/apps/monitor/display_data.py):@@ -118,7 +120,7 @@ See [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js)## Related documentation- [Architecture overview](entity-display-overview.md)-- [Panel authoring](entity-status-panels.md)+- [Panel authoring](entity-state-panels.md)- [SVG asset authoring](entity-visual-configuration.md)- [Style guidelines](style-guidelines.md)- [Template conventions](template-conventions.md)diff --git a/docs/dev/frontend/entity-status-panels.md b/docs/dev/frontend/entity-status-panels.mddeleted file mode 100644index e2ee4c76..00000000--- a/docs/dev/frontend/entity-status-panels.md+++ /dev/null@@ -1,107 +0,0 @@-# Entity Status Panels--EntityStatusPanels render the body of the entity status modal and of the per-entity cards inside collections. The framework dispatches per-`EntityType`, so each panel can present its entity in whatever form best fits — a flat state list, a graphical dial, a video frame, etc. — while the surrounding modal / card chrome stays uniform.--This document covers authoring a new panel.--**Related docs:**-- [`entity-display-overview.md`](entity-display-overview.md) — high-level architecture and how panels fit alongside the other display surfaces.-- [`entity-status-display.md`](entity-status-display.md) — the polling-update contract that panel templates and panel JS plug into.--## Overview--A panel is a self-contained bundle of templates, CSS, and JavaScript scoped to one `EntityType` and rendered in one of three **display contexts**:--| Context | Where it renders | Wrapper template |-|---|---|---|-| `modal` | The entity status modal body | `entity/templates/entity/modals/entity_status.html` |-| `list` | A collection's list-card layout | `collection/templates/collection/panes/entity_card_list.html` |-| `grid` | A collection's grid-card layout | `collection/templates/collection/panes/entity_card_grid.html` |--The wrapper renders its own identifying chrome (entity name, integration logo, type label). The panel body fills the area below and must not duplicate that chrome.--When an entity type has no panel of its own, the framework falls back to a flat state list. The fallback is itself a registered panel — see `entity/state_panels/fallback/`.--## Anatomy--```-src/hi/apps/entity/templates/entity/state_panels/<type>/- modal.html # required- list.html # optional, falls back per context chain- grid.html # optional, falls back per context chain--src/hi/static/state_panels/<type>/- <type>.css # optional- <type>.js # optional, registers JS handlers-```--`<type>` is the `EntityType.name.lower()` value (e.g. `thermostat`, `smoke_detector`).--**Template resolution chain** (see [`state_panel_dispatch.py`](../../../src/hi/apps/entity/state_panel_dispatch.py)):--1. `state_panels/<type>/<context>.html` — context-specific.-2. `state_panels/<type>/modal.html` — panel default, used for any unprovided context.-3. `state_panels/fallback/<context>.html` — framework fallback.--So `modal.html` is the only required file per panel: a panel that wants to render the same body in all three contexts just provides that one template.--## Template authoring--The dispatch template tag `{% render_entity_status_panel %}` is invoked by the wrapper. By the time a panel template runs, the parent context plus the entity's display projection are flattened together, so the following names are top-level:--| Name | What it is |-|---|---|-| `entity` | The `Entity` model instance. |-| `entity_status_data` | The `EntityDisplayData` wrapper. |-| `state_status_data_list` | Ordered list of `EntityStateDisplayData` for the entity's states (sorted per `ENTITY_STATUS_VIEW_ORDERING`). |-| `state_status_data_by_role` | Dict keyed by lowercase `EntityStateRole.name`. Use this to pull a specific state by role. |-| `entity_for_video` | The `Entity` whose video stream this panel should embed, or `None`. |-| `display_only_svg_icon_item` | The framework `SvgIconItem` for the entity's type icon, or `None`. |-| `display_category` | `EntityDisplayCategory` enum value for layout hints (`HAS_VIDEO` / `HAS_STATE` / `PLAIN`). |--Source of truth: `EntityDisplayData.to_template_context()` in [`display_data.py`](../../../src/hi/apps/monitor/display_data.py).--### Live updates via the polling contract--Elements inside a panel get live updates by carrying `data-state-id="<entity_state.id>"` plus one or more declaration attributes. Example: a span whose text mirrors the current temperature:--```html-<span data-state-id="{{ state_status_data_by_role.thermostat_current_temperature.entity_state.id }}"- data-display-text>72.0°F</span>-```--For the full declaration grammar, server payload shape, and the icon-vs-path asymmetry, see [`entity-status-display.md`](entity-status-display.md). Authoring a panel template is mostly a matter of (1) pulling the right state via `state_status_data_by_role` or `state_status_data_list`, and (2) tagging the elements that should refresh.--## JS extensions--Most panels need no JavaScript — declarative HTML attributes and CSS rules carry all the live-update work. When more is needed (e.g., re-positioning an SVG marker from a numeric magnitude), register a handler with `Hi.statePanels`:--- **`Hi.statePanels.registerUpdate(handler)`** — fires after each polling apply pass, receiving the full status map keyed by state id. Use this for refresh-time work the declarative contract can't express.-- **`Hi.statePanels.registerInit(handler)`** — fires on initial page load *and* after every async content insertion (entity status modal opens, collection refreshes). Use this to position elements from server-rendered data. Handlers must be idempotent — they re-scan the document on each call.--API source: [`entity_state_status.js`](../../../src/hi/static/js/entity_state_status.js). Reference panel: [`state_panels/thermostat/thermostat.js`](../../../src/hi/static/state_panels/thermostat/thermostat.js) uses both hooks for its SVG dial.--## Walkthrough: adding a panel for a new `EntityType`--1. Create `src/hi/apps/entity/templates/entity/state_panels/<type>/modal.html`. Add `list.html` / `grid.html` only if those contexts need a different layout.-2. Fetch specific states by role with `state_status_data_by_role.<role_name>` (lowercase `EntityStateRole.name`), or iterate `state_status_data_list` for the ordered set. The `{% panel_state entity "role_name" %}` tag returns just the `EntityState` model if that's what you need.-3. Tag refreshable elements per the polling-update contract. Server-rendered initial values stay; the dispatcher rewrites them each tick.-4. Drop panel-private CSS and JS in `src/hi/static/state_panels/<type>/` if needed.-5. Register any panel JS handlers via `Hi.statePanels.registerInit` / `registerUpdate`.-6. Verify in the simulator: open the entity status modal, change values on the simulator side, watch the panel refresh; open a collection containing the entity and check the list and grid contexts.--## Exemplars--Read the existing panels when starting a new one — copy from the closest match.--- **[`fallback/`](../../../src/hi/apps/entity/templates/entity/state_panels/fallback/)** — universal flat state list. Authors needing the standard rendering can include `fallback/state_list.html` directly.-- **[`smoke_detector/`](../../../src/hi/apps/entity/templates/entity/state_panels/smoke_detector/)** — CSS-only panel. Status-attribute-driven variants switch icon and label visibility without any JS.-- **[`thermostat/`](../../../src/hi/apps/entity/templates/entity/state_panels/thermostat/)** — full kit. Role-keyed state lookups, custom CSS, init + update JS hooks for an SVG dial.-- **[`camera/`](../../../src/hi/apps/entity/templates/entity/state_panels/camera/)** — embeds the shared flat state list partial alongside a video stream, demonstrating panel composition with framework partials.--## Pitfalls--- **`data-svg-style` is for single-element styling.** Don't put it on a multi-element SVG `<g>` icon — children inherit the pushed `fill`/`stroke` attributes and lose their differentiated styling. Use `data-status` and CSS branching instead. See [`entity-status-display.md`](entity-status-display.md#icon-vs-path-update-shape) for the full rationale.-- **Init handlers must be idempotent.** `registerInit` fires on both initial DOM-ready and every async content insertion. Handlers re-scan the document each time; applying state to already-initialized elements must be safe.-- **Don't duplicate chrome.** The modal wrapper supplies the type icon, entity name, integration logo, and type label in its subheader. The collection-card wrappers supply the entity-name title and (when applicable) the video stream. Panel bodies render below this chrome and should not repeat any of it.-- **Shared partials live where they were first authored.** The flat state list and per-state row templates live under `state_panels/fallback/` (where they were born). Other panels that want the same list reference them from that path; there's no separate "shared" namespace.diff --git a/docs/dev/frontend/entity-visual-configuration.md b/docs/dev/frontend/entity-visual-configuration.mdindex a0ba9f7e..d75b51d5 100644--- a/docs/dev/frontend/entity-visual-configuration.md+++ b/docs/dev/frontend/entity-visual-configuration.md@@ -81,7 +81,7 @@ For the existing palette of `StatusStyle` instances and the status-value vocabul- Icon renders at the expected position, scale, and rotation.- Status changes update the visual (color tint, drop-shadow glow, etc.) within one polling cycle.- Click target covers the whole icon (the `hi-entity-bg` rectangle).-5. Open a collection containing the entity and verify the cards render reasonably; for entity types with custom panel needs see [`entity-status-panels.md`](entity-status-panels.md).+5. Open a collection containing the entity and verify the cards render reasonably; for entity types with custom panel needs see [`entity-state-panels.md`](entity-state-panels.md).## Simulator integration (optional)@@ -91,6 +91,6 @@ If the new entity type should be exercisable from the simulator, add it to `SimE- [Architecture overview](entity-display-overview.md)- [Polling-update contract](entity-status-display.md)-- [Panel authoring](entity-status-panels.md)+- [Panel authoring](entity-state-panels.md)- [Icon system](icon-system.md)- [Style guidelines](style-guidelines.md)diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.pyindex 90020a9e..8eea55e1 100644--- a/src/hi/apps/collection/collection_manager.py+++ b/src/hi/apps/collection/collection_manager.py@@ -6,8 +6,9 @@ from django.http import HttpRequestfrom hi.apps.collection.edit.forms import CollectionPositionFormfrom hi.apps.common.singleton import Singleton-from hi.apps.entity.enums import EntityGroupType+from hi.apps.entity.enums import DisplayContext, EntityGroupTypefrom hi.apps.entity.models import Entity+from hi.apps.entity.state_panel_dispatch import StatePanelDispatcherfrom hi.apps.location.models import Location, LocationViewfrom hi.apps.location.svg_item_factory import SvgItemFactoryfrom hi.apps.monitor.display_data import EntityDisplayData@@ -68,13 +69,20 @@ class CollectionManager(Singleton):entity_status_data_list = StatusDisplayManager().get_entity_status_data_list(entities = entity_list,)- entity_display_data_list = [- EntityDisplayData( entity_status_data = d )- for d in entity_status_data_list+ display_context = (+ DisplayContext.GRID if collection.collection_view_type.is_grid+ else DisplayContext.LIST+ )+ state_panel_data_list = [+ StatePanelDispatcher.build_state_panel_data(+ EntityDisplayData( entity_status_data = status_data ),+ display_context,+ )+ for status_data in entity_status_data_list]return CollectionData(- collection = collection,- entity_status_data_list = entity_display_data_list,+ collection = collection,+ state_panel_data_list = state_panel_data_list,)def create_collection( self, name : str ) -> Collection:diff --git a/src/hi/apps/collection/enums.py b/src/hi/apps/collection/enums.pyindex 8c3b37e2..fe918159 100644--- a/src/hi/apps/collection/enums.py+++ b/src/hi/apps/collection/enums.py@@ -33,9 +33,11 @@ class CollectionViewType(LabeledEnum):GRID = ( 'Grid', '' )LIST = ( 'List', '' )+ @propertydef is_grid(self):return self == CollectionViewType.GRID+ @propertydef is_list(self):return self == CollectionViewType.LISTdiff --git a/src/hi/apps/collection/templates/collection/panes/collection_view.html b/src/hi/apps/collection/templates/collection/panes/collection_view.htmlindex 16bc5833..9b857414 100644--- a/src/hi/apps/collection/templates/collection/panes/collection_view.html+++ b/src/hi/apps/collection/templates/collection/panes/collection_view.html@@ -3,11 +3,11 @@{% if collection.collection_view_type.is_grid %}<div class="collection-grid {{ collection_grid_css_class }}">- {% for entity_status_data in entity_status_data_list %}- <div id="{{ entity_status_data.entity.html_id }}"- class="entity-item {{ entity_status_data.display_category.css_class }} {% if request.view_parameters.is_editing %}draggable{% endif %}"+ {% for state_panel_data in state_panel_data_list %}+ <div id="{{ state_panel_data.entity.html_id }}"+ class="entity-item {{ state_panel_data.display_category.css_class }} {% if request.view_parameters.is_editing %}draggable{% endif %}"{% if request.view_parameters.is_editing %}draggable="true"{% endif %} >- {% include "collection/panes/entity_card_grid.html" with entity_status_data=entity_status_data %}+ {% include "collection/panes/entity_card_grid.html" with state_panel_data=state_panel_data %}</div>{% endfor %}</div>@@ -15,18 +15,18 @@{% else %}<div class="collection-list">- {% for entity_status_data in entity_status_data_list %}- <div id="{{ entity_status_data.entity.html_id }}"- class="entity-row {{ entity_status_data.display_category.css_class }} {% if request.view_parameters.is_editing %}draggable{% endif %}"+ {% for state_panel_data in state_panel_data_list %}+ <div id="{{ state_panel_data.entity.html_id }}"+ class="entity-row {{ state_panel_data.display_category.css_class }} {% if request.view_parameters.is_editing %}draggable{% endif %}"{% if request.view_parameters.is_editing %}draggable="true"{% endif %} >- {% include "collection/panes/entity_card_list.html" with entity_status_data=entity_status_data %}+ {% include "collection/panes/entity_card_list.html" with state_panel_data=state_panel_data %}</div>{% endfor %}</div>{% endif %}- {% if not entity_status_data_list %}+ {% if not state_panel_data_list %}<div class="alert alert-info text-center w-100"><div class="h4">No items in collection.</div>{% if not request.view_parameters.is_editing %}diff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.htmlindex 8a2a708d..6395bc9a 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html@@ -1,13 +1,13 @@{% load state_panel_tags %}<div class="card h-100"><div class="card-body p-3">- {% include "collection/panes/entity_card_title.html" with entity_status_data=entity_status_data %}+ {% include "collection/panes/entity_card_title.html" with entity_status_data=state_panel_data.entity_display_data %}{% if collection.collection_type.is_cameras %}<div>- {% include "console/panes/entity_live_view_w_link.html" with entity=entity_status_data.entity %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=state_panel_data.entity %}</div>{% else %}- {% render_entity_status_panel entity_status_data "grid" %}+ {% include_panel state_panel_data %}{% endif %}</div></div>diff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html b/src/hi/apps/collection/templates/collection/panes/entity_card_list.htmlindex e2d6a6a1..1b7c0198 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_list.html@@ -3,15 +3,15 @@<div class="card-body"><div class="d-flex"><div class="entity-title-section flex-shrink-0">- {% include "collection/panes/entity_card_title.html" with entity_status_data=entity_status_data %}+ {% include "collection/panes/entity_card_title.html" with entity_status_data=state_panel_data.entity_display_data %}</div>{% if collection.collection_type.is_cameras %}<div>- {% include "console/panes/entity_live_view_w_link.html" with entity=entity_status_data.entity %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=state_panel_data.entity %}</div>{% else %}<div class="entity-content-section flex-grow-1 ml-3">- {% render_entity_status_panel entity_status_data "list" %}+ {% include_panel state_panel_data %}</div>{% endif %}</div>diff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_title.html b/src/hi/apps/collection/templates/collection/panes/entity_card_title.htmlindex 7ac49992..a7b3c6ad 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_card_title.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_title.html@@ -1,6 +1,10 @@{% with entity=entity_status_data.entity %}-<a href="{% if request.view_parameters.is_editing %}{% url 'entity_edit_mode' entity_id=entity_status_data.entity.id %}{% else %}{% url 'entity_edit' entity_id=entity_status_data.entity.id %}{% endif %}"- data-async="true">+{# Collection cards show only a subset of state (per the state panel #}+{# declaration); the full status modal mirrors what LocationView #}+{# clicks open. Edit-mode clicks fall through to the per-entity #}+{# inline edit view as before. #}+<a href="{% if request.view_parameters.is_editing %}{% url 'entity_edit_mode' entity_id=entity_status_data.entity.id %}{% else %}{% url 'entity_status' entity_id=entity_status_data.entity.id %}{% endif %}"+ data-async="{% if request.view_parameters.is_editing %}true{% else %}modal{% endif %}"><div class="d-flex justify-content-start"><div class="display-only-svg-icon pr-2">diff --git a/src/hi/apps/collection/tests/test_collection_manager.py b/src/hi/apps/collection/tests/test_collection_manager.pyindex c997524b..384ae131 100644--- a/src/hi/apps/collection/tests/test_collection_manager.py+++ b/src/hi/apps/collection/tests/test_collection_manager.py@@ -35,18 +35,18 @@ class TestCollectionManagerIntegration(BaseTestCase):# Verify collection data structureself.assertEqual(collection_data.collection, collection)- self.assertEqual(len(collection_data.entity_status_data_list), 2)-+ self.assertEqual(len(collection_data.state_panel_data_list), 2)+# Verify entities are ordered correctly- entity_names = [esd.entity.name for esd in collection_data.entity_status_data_list]+ entity_names = [panel_data.entity.name for panel_data in collection_data.state_panel_data_list]self.assertEqual(entity_names, ['Security Camera', 'Porch Light'])-- # Verify each entity has status data and SVG icon- for entity_status_data in collection_data.entity_status_data_list:- self.assertIsNotNone(entity_status_data.entity)- self.assertIsNotNone(entity_status_data.display_only_svg_icon_item)++ # Verify each card has the expected entity-derived fields+ for state_panel_data in collection_data.state_panel_data_list:+ self.assertIsNotNone(state_panel_data.entity)+ self.assertIsNotNone(state_panel_data.display_only_svg_icon_item)# SVG icon should be configured for display- self.assertIsNotNone(entity_status_data.display_only_svg_icon_item.template_name)+ self.assertIsNotNone(state_panel_data.display_only_svg_icon_item.template_name)def test_entity_collection_group_organization_by_type(self):"""Test create_entity_collection_group_list organization - groups entities by type."""@@ -645,12 +645,12 @@ class TestCollectionManager(BaseTestCase):# Verify basic context contains collection and entity listself.assertIn('collection', context)- self.assertIn('entity_status_data_list', context)+ self.assertIn('state_panel_data_list', context)self.assertEqual(context['collection'], collection)- self.assertEqual(len(context['entity_status_data_list']), 4)+ self.assertEqual(len(context['state_panel_data_list']), 4)- # Verify entity_status_data_list contains proper EntityStatusData objects- entity_names = [esd.entity.name for esd in context['entity_status_data_list']]+ # Verify state_panel_data_list contains the expected entities+ entity_names = [panel_data.entity.name for panel_data in context['state_panel_data_list']]expected_names = ['Info Display', 'Security Camera', 'Smart Switch', 'PTZ Camera']self.assertEqual(entity_names, expected_names)diff --git a/src/hi/apps/collection/tests/test_enums.py b/src/hi/apps/collection/tests/test_enums.pyindex 5cd1fd2e..e4f648bc 100644--- a/src/hi/apps/collection/tests/test_enums.py+++ b/src/hi/apps/collection/tests/test_enums.py@@ -43,18 +43,18 @@ class TestCollectionViewType(BaseTestCase):)# GRID type should enable grid-specific UI features- self.assertTrue(grid_collection.collection_view_type.is_grid())- self.assertFalse(grid_collection.collection_view_type.is_list())+ self.assertTrue(grid_collection.collection_view_type.is_grid)+ self.assertFalse(grid_collection.collection_view_type.is_list)# LIST type should enable list-specific UI features- self.assertFalse(list_collection.collection_view_type.is_grid())- self.assertTrue(list_collection.collection_view_type.is_list())+ self.assertFalse(list_collection.collection_view_type.is_grid)+ self.assertTrue(list_collection.collection_view_type.is_list)# Verify view types persist correctly in databasegrid_collection.refresh_from_db()list_collection.refresh_from_db()- self.assertTrue(grid_collection.collection_view_type.is_grid())- self.assertTrue(list_collection.collection_view_type.is_list())+ self.assertTrue(grid_collection.collection_view_type.is_grid)+ self.assertTrue(list_collection.collection_view_type.is_list)def test_all_collection_view_types_support_required_ui_modes(self):"""Test CollectionViewType completeness - ensures UI can handle all types."""@@ -63,8 +63,8 @@ class TestCollectionViewType(BaseTestCase):ambiguous_types = []for view_type in CollectionViewType:- is_grid = view_type.is_grid()- is_list = view_type.is_list()+ is_grid = view_type.is_grid+ is_list = view_type.is_list# Each type must be exactly one classificationif not (is_grid or is_list):@@ -79,8 +79,8 @@ class TestCollectionViewType(BaseTestCase):f"View types with ambiguous classification: {ambiguous_types}")# Verify we have both grid and list types available- grid_types = [vt for vt in CollectionViewType if vt.is_grid()]- list_types = [vt for vt in CollectionViewType if vt.is_list()]+ grid_types = [vt for vt in CollectionViewType if vt.is_grid]+ list_types = [vt for vt in CollectionViewType if vt.is_list]self.assertGreater(len(grid_types), 0, "No grid view types available")self.assertGreater(len(list_types), 0, "No list view types available")diff --git a/src/hi/apps/collection/transient_models.py b/src/hi/apps/collection/transient_models.pyindex 8e993f45..5e58738a 100644--- a/src/hi/apps/collection/transient_models.py+++ b/src/hi/apps/collection/transient_models.py@@ -4,7 +4,7 @@ from typing import Listfrom hi.apps.collection.edit.forms import CollectionEditForm, CollectionPositionFormfrom hi.apps.entity.enums import EntityGroupTypefrom hi.apps.entity.models import Entity-from hi.apps.monitor.display_data import EntityDisplayData+from hi.apps.entity.state_panel_dispatch import EntityStatePanelDatafrom .models import Collection@@ -12,29 +12,29 @@ from .models import Collection@dataclassclass CollectionData:- collection : Collection- entity_status_data_list : List[ EntityDisplayData ]-+ collection : Collection+ state_panel_data_list : List[ EntityStatePanelData ]+def to_template_context(self):return {'collection': self.collection,- 'entity_status_data_list': self.entity_status_data_list,+ 'state_panel_data_list': self.state_panel_data_list,'collection_grid_css_class': self.grid_css_class,- 'entity_count': len(self.entity_status_data_list),+ 'entity_count': len(self.state_panel_data_list),}@propertydef grid_css_class(self):if self.collection.collection_type.is_cameras:- return 'grid-2-items'- entity_count = len(self.entity_status_data_list)+ return 'grid-2-items'+ entity_count = len(self.state_panel_data_list)if entity_count >= 3:return 'grid-3-plus-items'if entity_count == 2:return 'grid-2-items'return 'grid-1-item'--++@dataclassclass CollectionViewItem:@@ -62,7 +62,7 @@ class EntityCollectionGroup:collection : Collectionentity_group_type : EntityGroupTypeitem_list : List[EntityCollectionItem] = field( default_factory = list )-+@dataclassclass CollectionEditModeData:diff --git a/src/hi/apps/entity/apps.py b/src/hi/apps/entity/apps.pyindex 7679e85f..eb80e794 100644--- a/src/hi/apps/entity/apps.py+++ b/src/hi/apps/entity/apps.py@@ -4,3 +4,8 @@ from django.apps import AppConfigclass DeviceConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "hi.apps.entity"++ def ready(self):+ from hi.apps.entity.state_panel_registry import EntityStatePanelRegistry+ EntityStatePanelRegistry().discover()+ returndiff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex 53144358..aee4f6e4 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -346,6 +346,14 @@ class EntityStateRole(LabeledEnum):return cls.DISCRETE+class DisplayContext(LabeledEnum):+ """For views/templates that depend on where they are being displayed."""++ MODAL = ( 'Modal', '' )+ LIST = ( 'List' , '' )+ GRID = ( 'Grid' , '' )++class EntityStateType(LabeledEnum):# General typesdiff --git a/src/hi/apps/entity/state_panel_base.py b/src/hi/apps/entity/state_panel_base.pynew file mode 100644index 00000000..ef0ff010--- /dev/null+++ b/src/hi/apps/entity/state_panel_base.py@@ -0,0 +1,72 @@+"""+Authoring guidance: ``docs/dev/frontend/entity-state-panels.md``.+"""++from dataclasses import dataclass, field+from typing import Dict, Optional, Set++from hi.apps.entity.enums import DisplayContext, EntityStateRole, EntityType+++@dataclass+class EntityStatePanel:++ name : str+ display_contexts : Set[ DisplayContext ]+ priority : int # Priority 1 higher than priority 2+ template_name : str++ entity_type : Optional[ EntityType ] = None # If 'None' then used as fallback+ required_roles : Set[ EntityStateRole ] = field( default_factory = set )+ optional_roles : Set[ EntityStateRole ] = field( default_factory = set )+ # Each entry binds a template-context variable name (key) to one of+ # the panel's declared EntityStateRoles. The dispatcher resolves+ # these against ``state_status_data_by_role`` at render time so the+ # template can use ``{{ current_data.entity_state.id }}`` directly+ # instead of chaining ``{% with %}`` blocks. Aliases must reference+ # roles in ``required_roles | optional_roles``; absent optional+ # roles resolve to ``None``.+ role_data_template_aliases : Dict[ str, EntityStateRole ] = field( default_factory = dict )++ def __post_init__( self ):+ prefix = f'EntityStatePanel({self.name!r})'+ if not self.name or not isinstance( self.name, str ):+ raise TypeError( f'{prefix}: name must be a non-empty str' )+ if not self.template_name or not isinstance( self.template_name, str ):+ raise TypeError( f'{prefix}: template_name must be a non-empty str' )+ if not self.display_contexts:+ raise TypeError(+ f'{prefix}: display_contexts must be a non-empty Set[ DisplayContext ]'+ )+ for ctx in self.display_contexts:+ if not isinstance( ctx, DisplayContext ):+ raise TypeError(+ f'{prefix}: display_contexts entries must be '+ f'DisplayContext members; got {ctx!r}'+ )+ if not isinstance( self.priority, int ):+ raise TypeError( f'{prefix}: priority must be an int' )+ if self.entity_type is not None and not isinstance( self.entity_type, EntityType ):+ raise TypeError(+ f'{prefix}: entity_type must be an EntityType member or None'+ )+ overlap = self.required_roles & self.optional_roles+ if overlap:+ names = ', '.join( sorted( r.name for r in overlap ) )+ raise TypeError(+ f'{prefix}: required_roles and optional_roles must be disjoint; '+ f'overlap: {names}'+ )+ declared = self.required_roles | self.optional_roles+ for alias, role in self.role_data_template_aliases.items():+ if not isinstance( role, EntityStateRole ):+ raise TypeError(+ f'{prefix}: role_data_template_aliases[{alias!r}] must be an '+ f'EntityStateRole member; got {role!r}'+ )+ if role not in declared:+ raise TypeError(+ f'{prefix}: role_data_template_aliases[{alias!r}] -> {role.name} '+ f'is not in required_roles or optional_roles'+ )+ returndiff --git a/src/hi/apps/entity/state_panel_dispatch.py b/src/hi/apps/entity/state_panel_dispatch.pyindex bf2d62df..a9c22e0e 100644--- a/src/hi/apps/entity/state_panel_dispatch.py+++ b/src/hi/apps/entity/state_panel_dispatch.py@@ -1,69 +1,200 @@-"""Template-path resolution for EntityStatusPanel rendering.--A panel is a self-contained bundle of templates, CSS, and (optionally)-JS that defines how an entity of a particular EntityType is rendered-in one of three display contexts: the EntityStatusView modal body, the-collection list card, and the collection grid card.--``modal.html`` is the panel's required default template. ``list.html``-and ``grid.html`` are optional per-context overrides. The framework-provides fallback templates for any entity type that has no panel."""--from typing import List--from django.template import Template-from django.template.exceptions import TemplateDoesNotExist-from django.template.loader import get_template--from hi.apps.entity.enums import EntityType---SUPPORTED_DISPLAY_CONTEXTS = ( 'modal', 'list', 'grid' )--# Per-context framework fallback used when the entity's type has no-# panel directory. All three are framework-provided and guaranteed-# to exist.-FRAMEWORK_FALLBACK_TEMPLATES = {- 'modal': 'entity/state_panels/fallback/modal.html',- 'list': 'entity/state_panels/fallback/list.html',- 'grid': 'entity/state_panels/fallback/grid.html',-}---def resolve_panel_template(- entity_type : EntityType,- display_context_name : str,-) -> Template:- """Return the first existing template for the (entity_type,- display_context) pair along the three-step resolution chain:-- 1. Panel's context-specific template (``<type>/<context>.html``).- 2. Panel's required default template (``<type>/modal.html``).- 3. Framework fallback for the context (always exists)."""+import logging+from dataclasses import dataclass, field+from typing import Any, Dict, List, Set++from hi.apps.entity.enums import DisplayContext, EntityStateRole, EntityType+from hi.apps.entity.state_panel_base import EntityStatePanel+from hi.apps.entity.state_panel_registry import EntityStatePanelRegistry+from hi.apps.monitor.display_data import EntityDisplayData, EntityStateDisplayData+++logger = logging.getLogger( __name__ )+++@dataclass+class PanelResolution:+ panel : EntityStatePanel+ extras : Set[ EntityStateRole ] = field( default_factory = set )+ trace : List[ str ] = field( default_factory = list )+++@dataclass+class EntityStatePanelData:+ """An entity prepared for rendering through the panel framework in a+ specific display context. Produced by+ ``StatePanelDispatcher.build_state_panel_data``; consumed identically+ by both the entity status modal and the collection card wrappers.++ ``panel_context`` carries the panel-template variables (filtered to+ declared roles for typed panels, unfiltered for fallback panels).+ ``extras_state_data_list`` is the framework-managed projection of+ roles outside the panel's declared set; the modal extras section+ renders it."""++ entity_display_data : EntityDisplayData+ panel_template : str+ panel_context : Dict[ str, Any ]+ extras_state_data_list : List[ EntityStateDisplayData ] = field( default_factory = list )+ trace : List[ str ] = field( default_factory = list )++ # Forwarded for template ergonomics — templates read+ # ``state_panel_data.entity`` etc. without descending through+ # ``entity_display_data``.+ @property+ def entity(self):+ return self.entity_display_data.entity++ @property+ def display_category(self):+ return self.entity_display_data.display_category++ @property+ def display_only_svg_icon_item(self):+ return self.entity_display_data.display_only_svg_icon_item++ @property+ def entity_for_video(self):+ return self.entity_display_data.entity_for_video+++class StatePanelDispatcher:++ @classmethod+ def build_state_panel_data(+ cls,+ entity_display_data : EntityDisplayData,+ display_context : DisplayContext,+ debug : bool = False,+ ) -> EntityStatePanelData:+ resolution = cls.resolve_panel_for(+ entity_display_data, display_context, debug = debug,+ )+ panel = resolution.panel++ if panel.entity_type is None:+ # Fallback panels see every state; nothing is "extras."+ state_list = entity_display_data.state_status_data_list+ by_role = entity_display_data.state_status_data_by_role+ extras_list : List[ EntityStateDisplayData ] = []+ else:+ declared = panel.required_roles | panel.optional_roles+ state_list, by_role = entity_display_data.filter_to_roles( declared )+ extras_list = [+ d for d in entity_display_data.state_status_data_list+ if d.entity_state.entity_state_role in resolution.extras+ ]++ panel_context : Dict[ str, Any ] = {+ 'entity' : entity_display_data.entity,+ 'entity_status_data' : entity_display_data,+ 'state_status_data_list' : state_list,+ 'state_status_data_by_role' : by_role,+ 'entity_for_video' : entity_display_data.entity_for_video,+ 'display_only_svg_icon_item' : entity_display_data.display_only_svg_icon_item,+ 'display_category' : entity_display_data.display_category,+ }+ # Resolve the panel's declared role-data template aliases against+ # the (filtered) by-role map. Absent optional roles resolve to+ # ``None`` so templates can ``{% if alias %}``-guard them.+ for alias, role in panel.role_data_template_aliases.items():+ panel_context[ alias ] = by_role.get( role.name.lower() )+ return EntityStatePanelData(+ entity_display_data = entity_display_data,+ panel_template = panel.template_name,+ panel_context = panel_context,+ extras_state_data_list = extras_list,+ trace = resolution.trace,+ )- if display_context_name not in SUPPORTED_DISPLAY_CONTEXTS:- raise ValueError(- f'Unsupported display context: {display_context_name!r}. '- f'Expected one of {SUPPORTED_DISPLAY_CONTEXTS}.'+ @classmethod+ def resolve_panel_for(+ cls,+ entity_display_data : EntityDisplayData,+ display_context : DisplayContext,+ debug : bool = False,+ ) -> PanelResolution:+ return cls.resolve_panel(+ entity_type = entity_display_data.entity.entity_type,+ display_context = display_context,+ present_roles = entity_display_data.present_roles,+ debug = debug,)- type_lower = entity_type.name.lower()- for candidate in _candidate_paths( type_lower, display_context_name ):- try:- return get_template( candidate )- except TemplateDoesNotExist:- continue-- raise TemplateDoesNotExist(- f'No panel template found for entity_type={entity_type.name} '- f'context={display_context_name}; framework fallback at '- f'{FRAMEWORK_FALLBACK_TEMPLATES[display_context_name]} is missing.'- )---def _candidate_paths( type_lower : str, display_context_name : str ) -> List[ str ]:- return [- f'entity/state_panels/{type_lower}/{display_context_name}.html',- f'entity/state_panels/{type_lower}/modal.html',- FRAMEWORK_FALLBACK_TEMPLATES[ display_context_name ],- ]+ @classmethod+ def resolve_panel(+ cls,+ entity_type : EntityType,+ display_context : DisplayContext,+ present_roles : Set[ EntityStateRole ],+ debug : bool = False,+ ) -> PanelResolution:+ """Choose the panel for ``(entity_type, display_context, present_roles)``.+ Type-specific panels win over fallback panels; among either group,+ lower ``priority`` wins, with ``name`` as the alphabetical tiebreaker.+ Raises ``RuntimeError`` if no fallback panel covers the context.++ The trace is only built when ``debug`` is True or DEBUG-level+ logging is enabled — the production hot path (one dispatch per+ collection card) skips the trace string formatting entirely."""++ want_trace = debug or logger.isEnabledFor( logging.DEBUG )+ all_panels = EntityStatePanelRegistry().all_panels()+ trace : List[ str ] = []+ if want_trace:+ trace.append(+ f'entity_type={entity_type.name} '+ f'display_context={display_context.name} '+ f'present_roles=[{",".join(sorted(r.name for r in present_roles))}]'+ )++ typed = sorted(+ (+ p for p in all_panels+ if p.entity_type == entity_type+ and display_context in p.display_contexts+ and p.required_roles.issubset( present_roles )+ ),+ key = lambda p: ( p.priority, p.name ),+ )+ if typed:+ chosen = typed[ 0 ]+ if want_trace:+ trace.append(+ 'typed candidates: '+ + ', '.join( f'{p.name}#{p.priority}' for p in typed )+ + f' -> {chosen.name}'+ )+ return cls._build_resolution( chosen, present_roles, trace, want_trace )++ fallbacks = sorted(+ (+ p for p in all_panels+ if p.entity_type is None+ and display_context in p.display_contexts+ ),+ key = lambda p: ( p.priority, p.name ),+ )+ if not fallbacks:+ if want_trace:+ trace.append( f'no fallback registered for {display_context.name}' )+ raise RuntimeError(+ f'No fallback panel registered for display_context={display_context.name}'+ )+ chosen = fallbacks[ 0 ]+ if want_trace:+ trace.append(+ 'fallback candidates: '+ + ', '.join( f'{p.name}#{p.priority}' for p in fallbacks )+ + f' -> {chosen.name}'+ )+ return cls._build_resolution( chosen, present_roles, trace, want_trace )++ @classmethod+ def _build_resolution( cls, panel, present_roles, trace, want_trace ):+ extras = present_roles - ( panel.required_roles | panel.optional_roles )+ if want_trace and extras:+ trace.append( 'extras: ' + ','.join( sorted( r.name for r in extras ) ) )+ resolution = PanelResolution( panel = panel, extras = extras, trace = trace )+ if want_trace and trace:+ logger.debug( 'Panel resolution:\n ' + '\n '.join( trace ) )+ return resolutiondiff --git a/src/hi/apps/entity/state_panel_registry.py b/src/hi/apps/entity/state_panel_registry.pynew file mode 100644index 00000000..a7394fbf--- /dev/null+++ b/src/hi/apps/entity/state_panel_registry.py@@ -0,0 +1,86 @@+import importlib+import logging+import pkgutil+from threading import Lock+from typing import Dict, List, Optional++from hi.apps.common.singleton import Singleton++from hi.apps.entity.state_panel_base import EntityStatePanel+++logger = logging.getLogger( __name__ )+++class EntityStatePanelRegistry( Singleton ):++ def __init_singleton__( self ):+ self._panels : Dict[ str, EntityStatePanel ] = {}+ self._lock = Lock()+ self._discovered = False+ return++ def register( self, panel : EntityStatePanel ) -> None:+ with self._lock:+ existing = self._panels.get( panel.name )+ if existing is not None and existing is not panel:+ raise RuntimeError( f'Duplicate panel name: {panel.name!r}' )+ self._panels[ panel.name ] = panel+ return++ def discover( self ) -> None:+ """Import each ``state_panels/<name>/panel.py`` and register every+ ``EntityStatePanel`` instance found at module scope. Idempotent.+ Per-module failures are logged and skipped rather than aborting+ app startup, so one malformed panel doesn't poison the registry."""+ with self._lock:+ if self._discovered:+ return+ try:+ from hi.apps.entity import state_panels as panels_pkg+ except ImportError:+ with self._lock:+ self._discovered = True+ return+ for module_info in pkgutil.iter_modules( panels_pkg.__path__ ):+ if not module_info.ispkg:+ continue+ module_path = f'{panels_pkg.__name__}.{module_info.name}.panel'+ try:+ module = importlib.import_module( module_path )+ found = [+ value for value in vars( module ).values()+ if isinstance( value, EntityStatePanel )+ ]+ if not found:+ logger.warning(+ f'{module_path}: no EntityStatePanel instance at module scope'+ )+ continue+ for panel in found:+ self.register( panel )+ continue+ except Exception:+ logger.exception( f'Skipping {module_path}: discovery error' )+ continue+ continue+ with self._lock:+ self._discovered = True+ return++ def all_panels( self ) -> List[ EntityStatePanel ]:+ return list( self._panels.values() )++ def get_by_name( self, name : str ) -> Optional[ EntityStatePanel ]:+ return self._panels.get( name )++ def snapshot_for_tests( self ):+ with self._lock:+ return ( dict( self._panels ), self._discovered )++ def restore_for_tests( self, snapshot ) -> None:+ panels, discovered = snapshot+ with self._lock:+ self._panels = dict( panels )+ self._discovered = discovered+ returndiff --git a/src/hi/apps/entity/state_panels/__init__.py b/src/hi/apps/entity/state_panels/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/entity/state_panels/camera/__init__.py b/src/hi/apps/entity/state_panels/camera/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/entity/state_panels/camera/panel.py b/src/hi/apps/entity/state_panels/camera/panel.pynew file mode 100644index 00000000..40448676--- /dev/null+++ b/src/hi/apps/entity/state_panels/camera/panel.py@@ -0,0 +1,42 @@+from hi.apps.entity.enums import DisplayContext, EntityStateRole, EntityType+from hi.apps.entity.state_panel_base import EntityStatePanel+++_OPTIONAL_ROLES = {+ EntityStateRole.MOVEMENT,+}++_ROLE_DATA_TEMPLATE_ALIASES = {+ 'motion_data': EntityStateRole.MOVEMENT,+}+++modal_panel = EntityStatePanel(+ name = 'camera_modal',+ entity_type = EntityType.CAMERA,+ display_contexts = { DisplayContext.MODAL },+ priority = 100,+ template_name = 'entity/state_panels/camera/modal.html',+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)++list_panel = EntityStatePanel(+ name = 'camera_list',+ entity_type = EntityType.CAMERA,+ display_contexts = { DisplayContext.LIST },+ priority = 100,+ template_name = 'entity/state_panels/camera/list.html',+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)++grid_panel = EntityStatePanel(+ name = 'camera_grid',+ entity_type = EntityType.CAMERA,+ display_contexts = { DisplayContext.GRID },+ priority = 100,+ template_name = 'entity/state_panels/camera/grid.html',+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)diff --git a/src/hi/apps/entity/state_panels/fallback/__init__.py b/src/hi/apps/entity/state_panels/fallback/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/entity/state_panels/fallback/panel.py b/src/hi/apps/entity/state_panels/fallback/panel.pynew file mode 100644index 00000000..596cf8f4--- /dev/null+++ b/src/hi/apps/entity/state_panels/fallback/panel.py@@ -0,0 +1,27 @@+from hi.apps.entity.enums import DisplayContext+from hi.apps.entity.state_panel_base import EntityStatePanel+++modal_panel = EntityStatePanel(+ name = 'fallback_modal',+ entity_type = None,+ display_contexts = { DisplayContext.MODAL },+ priority = 1000,+ template_name = 'entity/state_panels/fallback/modal.html',+)++list_panel = EntityStatePanel(+ name = 'fallback_list',+ entity_type = None,+ display_contexts = { DisplayContext.LIST },+ priority = 1000,+ template_name = 'entity/state_panels/fallback/list.html',+)++grid_panel = EntityStatePanel(+ name = 'fallback_grid',+ entity_type = None,+ display_contexts = { DisplayContext.GRID },+ priority = 1000,+ template_name = 'entity/state_panels/fallback/grid.html',+)diff --git a/src/hi/apps/entity/state_panels/smoke_detector/__init__.py b/src/hi/apps/entity/state_panels/smoke_detector/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/entity/state_panels/smoke_detector/panel.py b/src/hi/apps/entity/state_panels/smoke_detector/panel.pynew file mode 100644index 00000000..4959c373--- /dev/null+++ b/src/hi/apps/entity/state_panels/smoke_detector/panel.py@@ -0,0 +1,50 @@+from hi.apps.entity.enums import DisplayContext, EntityStateRole, EntityType+from hi.apps.entity.state_panel_base import EntityStatePanel+++_REQUIRED_ROLES = {+ EntityStateRole.SMOKE,+}++_OPTIONAL_ROLES = {+ EntityStateRole.BATTERY_LEVEL,+}++_ROLE_DATA_TEMPLATE_ALIASES = {+ 'smoke_data': EntityStateRole.SMOKE,+ 'battery_data': EntityStateRole.BATTERY_LEVEL,+}+++modal_panel = EntityStatePanel(+ name = 'smoke_detector_modal',+ entity_type = EntityType.SMOKE_DETECTOR,+ display_contexts = { DisplayContext.MODAL },+ priority = 100,+ template_name = 'entity/state_panels/smoke_detector/modal.html',+ required_roles = _REQUIRED_ROLES,+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)++list_panel = EntityStatePanel(+ name = 'smoke_detector_list',+ entity_type = EntityType.SMOKE_DETECTOR,+ display_contexts = { DisplayContext.LIST },+ priority = 100,+ template_name = 'entity/state_panels/smoke_detector/list.html',+ required_roles = _REQUIRED_ROLES,+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)++grid_panel = EntityStatePanel(+ name = 'smoke_detector_grid',+ entity_type = EntityType.SMOKE_DETECTOR,+ display_contexts = { DisplayContext.GRID },+ priority = 100,+ template_name = 'entity/state_panels/smoke_detector/grid.html',+ required_roles = _REQUIRED_ROLES,+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)diff --git a/src/hi/apps/entity/state_panels/thermostat/__init__.py b/src/hi/apps/entity/state_panels/thermostat/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/entity/state_panels/thermostat/panel.py b/src/hi/apps/entity/state_panels/thermostat/panel.pynew file mode 100644index 00000000..78c61b1f--- /dev/null+++ b/src/hi/apps/entity/state_panels/thermostat/panel.py@@ -0,0 +1,67 @@+from hi.apps.entity.enums import DisplayContext, EntityStateRole, EntityType+from hi.apps.entity.state_panel_base import EntityStatePanel+++_REQUIRED_ROLES = {+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+}++_OPTIONAL_ROLES = {+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,+ EntityStateRole.HVAC_ACTION,+ EntityStateRole.HVAC_MODE,+ EntityStateRole.FAN_MODE,+ EntityStateRole.PRESET_MODE,+ EntityStateRole.HUMIDITY,+}++# Template variables exposed to the panel templates. Each entry binds a+# template variable name to a declared EntityStateRole; the dispatcher+# resolves these against the per-entity by-role map at render time.+_ROLE_DATA_TEMPLATE_ALIASES = {+ 'current_data': EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ 'target_data': EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE,+ 'low_data': EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_LOW,+ 'high_data': EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE_HIGH,+ 'action_data': EntityStateRole.HVAC_ACTION,+ 'mode_data': EntityStateRole.HVAC_MODE,+ 'fan_data': EntityStateRole.FAN_MODE,+ 'preset_data': EntityStateRole.PRESET_MODE,+ 'humidity_data': EntityStateRole.HUMIDITY,+}+++modal_panel = EntityStatePanel(+ name = 'thermostat_modal',+ entity_type = EntityType.THERMOSTAT,+ display_contexts = { DisplayContext.MODAL },+ priority = 100,+ template_name = 'entity/state_panels/thermostat/modal.html',+ required_roles = _REQUIRED_ROLES,+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)++list_panel = EntityStatePanel(+ name = 'thermostat_list',+ entity_type = EntityType.THERMOSTAT,+ display_contexts = { DisplayContext.LIST },+ priority = 100,+ template_name = 'entity/state_panels/thermostat/list.html',+ required_roles = _REQUIRED_ROLES,+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)++grid_panel = EntityStatePanel(+ name = 'thermostat_grid',+ entity_type = EntityType.THERMOSTAT,+ display_contexts = { DisplayContext.GRID },+ priority = 100,+ template_name = 'entity/state_panels/thermostat/grid.html',+ required_roles = _REQUIRED_ROLES,+ optional_roles = _OPTIONAL_ROLES,+ role_data_template_aliases = _ROLE_DATA_TEMPLATE_ALIASES,+)diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status.html b/src/hi/apps/entity/templates/entity/modals/entity_status.htmlindex 1f33be63..5c2180f0 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html@@ -8,7 +8,7 @@{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}{% block title_text %}-{{ entity.name }}+{{ state_panel_data.entity.name }}{% endblock %}{# Framework-level subheader: entity type icon + label on the left, #}@@ -16,11 +16,12 @@{# right. Panels render their body below without repeating any of #}{# this identifying chrome. #}{% block subheader %}+{% with entity=state_panel_data.entity icon_item=state_panel_data.display_only_svg_icon_item %}<div class="hi-entity-status-subheader d-flex align-items-center px-3 py-1 border-bottom"><div class="hi-entity-status-subheader__left d-flex align-items-center">- {% if display_only_svg_icon_item %}+ {% if icon_item %}<span class="hi-entity-status-subheader__type-icon mr-2">- {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=display_only_svg_icon_item %}+ {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=icon_item %}</span>{% endif %}<small class="text-muted text-uppercase">{{ entity.entity_type.label }}</small>@@ -38,16 +39,25 @@<small class="text-muted text-uppercase">Status</small></div></div>+{% endwith %}{% endblock %}{% block body %}-{% integration_health_banner entity.integration_id "Values shown may be stale; controls may not respond." %}-{% render_entity_status_panel entity_status_data "modal" %}+{% integration_health_banner state_panel_data.entity.integration_id "Values shown may be stale; controls may not respond." %}+{% include_panel state_panel_data %}+{% if state_panel_data.extras_state_data_list %}+{% include "entity/state_panels/extras_section.html" with extras_state_data_list=state_panel_data.extras_state_data_list %}+{% endif %}+{% if panel_trace %}<!--+Panel dispatch trace:+{% for line in panel_trace %} {{ line }}+{% endfor %}-->+{% endif %}{% endblock %}{% block action_left %}<a class="btn btn-primary"- href="{% url 'entity_edit' entity_id=entity.id %}"+ href="{% url 'entity_edit' entity_id=state_panel_data.entity.id %}"data-async="modal">{% icon "edit" size="sm" css_class="hi-icon-left" %}EDIT</a>@@ -55,7 +65,7 @@{% block action_center %}<a class="btn btn-primary"- href="{% url 'entity_history' entity_id=entity.id %}"+ href="{% url 'entity_history' entity_id=state_panel_data.entity.id %}"data-async="modal">{% icon "history" size="sm" css_class="hi-icon-left" %}HISTORY</a>diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html b/src/hi/apps/entity/templates/entity/state_panels/camera/grid.htmlindex fb121f0b..6332517b 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html@@ -1,5 +1,5 @@-{# Camera EntityStatusPanel — collection grid card context. Video fills #}-{# the cell with a name overlay along the bottom. #}+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# motion_data (optional). #}<div class="hi-state-panel-camera hi-state-panel-camera--grid"><div class="stream">@@ -8,6 +8,9 @@{% else %}<div class="stream-unavailable">Offline</div>{% endif %}+ {% if motion_data %}+ {% include "entity/state_panels/camera/motion_chip.html" %}+ {% endif %}</div><div class="grid-overlay">diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/list.html b/src/hi/apps/entity/templates/entity/state_panels/camera/list.htmlindex 78733754..d16a911a 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/list.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/list.html@@ -1,4 +1,5 @@-{# Camera EntityStatusPanel — collection list card context. #}+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# motion_data (optional). #}<div class="hi-state-panel-camera hi-state-panel-camera--list"><div class="stream">@@ -7,6 +8,9 @@{% else %}<div class="stream-unavailable">Offline</div>{% endif %}+ {% if motion_data %}+ {% include "entity/state_panels/camera/motion_chip.html" %}+ {% endif %}</div><div class="list-meta">diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.htmlindex 4b7ffaf8..82474afd 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html@@ -1,9 +1,11 @@-{# Camera EntityStatusPanel — modal context. #}-{# Reuses the existing video-stream wrapper for the live frame and the #}-{# existing per-state row list for any controllers/sensors the camera #}-{# entity exposes (e.g., ZoneMinder Function dropdown, connectivity #}-{# sensors). No new JS — the video stream rendering and click-through to #}-{# the full-page video pane all go through the established machinery. #}+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# motion_data (optional). #}+{# #}+{# Stream rendering goes through the standard live-view template so #}+{# the panel inherits its offline placeholder, click-through, and #}+{# polling-driven snapshot refresh. Anything beyond the stream (and #}+{# the optional motion chip) flows into the framework extras section #}+{# beneath the panel body. #}<div class="hi-state-panel-camera hi-state-panel-camera--modal"><div class="stream">@@ -12,12 +14,9 @@{% else %}<div class="stream-unavailable">Live view not available</div>{% endif %}+ {% if motion_data %}+ {% include "entity/state_panels/camera/motion_chip.html" %}+ {% endif %}</div>- {% if state_status_data_list %}- <div class="states">- {% include "entity/state_panels/fallback/state_list.html" with entity_state_status_data_list=state_status_data_list %}- </div>- {% endif %}-</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/motion_chip.html b/src/hi/apps/entity/templates/entity/state_panels/camera/motion_chip.htmlnew file mode 100644index 00000000..10c9a1a5--- /dev/null+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/motion_chip.html@@ -0,0 +1,13 @@+{# Motion chip overlaid on the camera stream. ``motion_data`` is #}+{# the MOVEMENT role's display data (passed via the camera panel's #}+{# role_data_template_aliases). CSS rules keyed on the chip's #}+{# ``status`` attribute drive the decay-aware coloring. #}+<div class="motion-chip"+ data-state-id="{{ motion_data.entity_state.id }}"+ data-status+ status="{{ motion_data.svg_status_style.status_value }}"+ title="Motion">+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">+ <path d="M13.49 5.48c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM9.89 19.38l1-4.4 2.1 2v6h2v-7.5l-2.1-2 .6-3c1.3 1.5 3.3 2.5 5.5 2.5v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.4-.6-1-1-1.7-1-.3 0-.5.1-.8.1l-5.2 2.2v4.7h2v-3.4l1.8-.7-1.6 8.1-4.9-1-.4 2 7 1.4z"/>+ </svg>+</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/extras_section.html b/src/hi/apps/entity/templates/entity/state_panels/extras_section.htmlnew file mode 100644index 00000000..203c373d--- /dev/null+++ b/src/hi/apps/entity/templates/entity/state_panels/extras_section.html@@ -0,0 +1,13 @@+{# Framework-managed extras section for the modal context. Renders #}+{# every EntityStateRole on the entity that is outside the active #}+{# panel's declared (required + optional) set, inline (no heading, #}+{# no collapsible wrapper) — the modal-context invariant is that #}+{# every EntityState is reachable, and "state" is not user-facing #}+{# nomenclature, so a section label adds nothing. #}+<div class="hi-state-panel-extras mt-3">+ {% for entity_state_status_data in extras_state_data_list %}+ <div class="my-2">+ {% include "entity/state_panels/fallback/state_row.html" with entity_state_status_data=entity_state_status_data %}+ </div>+ {% endfor %}+</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/fallback/state_row.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/state_row.htmlindex 9719235f..1244f96d 100644--- a/src/hi/apps/entity/templates/entity/state_panels/fallback/state_row.html+++ b/src/hi/apps/entity/templates/entity/state_panels/fallback/state_row.html@@ -1,5 +1,4 @@{% load icons %}-{% with sensor_response=entity_state_status_data.latest_sensor_response %}<div class="card"><div class="card-body">{% if entity_state_status_data.controller_data_list %}@@ -16,7 +15,6 @@{% else %}<div class="alert alert-info">{{ entity_state_status_data.entity_state.short_name }}: no sensors or controllers defined.</div>{% endif %}-+</div></div>-{% endwith %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/badge.html b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/badge.htmlnew file mode 100644index 00000000..8f7c5b37--- /dev/null+++ b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/badge.html@@ -0,0 +1,17 @@+{# 4-state decay badge for the smoke detector. CSS rules keyed on #}+{# the surrounding panel root's ``status`` attribute pick which #}+{# icon variant is visible. #}+<div class="badge">+ <svg class="icon icon--idle" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">+ <path d="M12 2L4 5v6c0 5 3.5 9.5 8 11 4.5-1.5 8-6 8-11V5l-8-3zm-1.3 14.3l-3.7-3.7 1.4-1.4 2.3 2.3 5.3-5.3 1.4 1.4-6.7 6.7z"/>+ </svg>+ <svg class="icon icon--active" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">+ <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>+ </svg>+ <svg class="icon icon--recent" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>+ </svg>+ <svg class="icon icon--past" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>+ </svg>+</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/grid.html b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/grid.htmlindex dc6d3062..cfcaaba7 100644--- a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/grid.html+++ b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/grid.html@@ -1,32 +1,24 @@-{% with smoke_data=state_status_data_by_role.smoke battery_data=state_status_data_by_role.battery_level %}-+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# smoke_data, battery_data. #}<div class="hi-state-panel-smoke_detector hi-state-panel-smoke_detector--grid"- {% if smoke_data %}data-state-id="{{ smoke_data.entity_state.id }}" data-status status="{{ smoke_data.latest_sensor_value }}"{% endif %}>+ data-state-id="{{ smoke_data.entity_state.id }}"+ data-status+ status="{{ smoke_data.svg_status_style.status_value }}">- {% if smoke_data %}- <div class="badge">- <svg class="icon icon--clear" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2L4 5v6c0 5 3.5 9.5 8 11 4.5-1.5 8-6 8-11V5l-8-3zm-1.3 14.3l-3.7-3.7 1.4-1.4 2.3 2.3 5.3-5.3 1.4 1.4-6.7 6.7z"/>- </svg>- <svg class="icon icon--alarm" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>- </svg>- <svg class="icon icon--recent" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>- </svg>- <svg class="icon icon--past" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>- </svg>- </div>+ {% include "entity/state_panels/smoke_detector/badge.html" %}- <div class="status-line">- <span class="status-label status-label--clear">Clear</span>- <span class="status-label status-label--alarm">Smoke Detected</span>- </div>- {% endif %}+ <div class="status-label status-label--idle">All Clear</div>+ <div class="status-label status-label--active">Smoke!</div>+ <div class="status-label status-label--recent">Recent</div>+ <div class="status-label status-label--past">Past</div><div class="entity-name">{{ entity.name }}</div>-</div>+ {% if battery_data %}+ <div class="low-battery-warning"+ data-state-id="{{ battery_data.entity_state.id }}"+ data-status+ status="{{ battery_data.svg_status_style.status_value }}">Low Battery</div>+ {% endif %}-{% endwith %}+</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/list.html b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/list.htmlindex 7f285bc5..893e3d3e 100644--- a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/list.html+++ b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/list.html@@ -1,40 +1,31 @@-{% with smoke_data=state_status_data_by_role.smoke battery_data=state_status_data_by_role.battery_level %}-+{% load humanize tz %}+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# smoke_data, battery_data. #}<div class="hi-state-panel-smoke_detector hi-state-panel-smoke_detector--list"- {% if smoke_data %}data-state-id="{{ smoke_data.entity_state.id }}" data-status status="{{ smoke_data.latest_sensor_value }}"{% endif %}>+ data-state-id="{{ smoke_data.entity_state.id }}"+ data-status+ status="{{ smoke_data.svg_status_style.status_value }}">- {% if smoke_data %}- <div class="badge">- <svg class="icon icon--clear" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2L4 5v6c0 5 3.5 9.5 8 11 4.5-1.5 8-6 8-11V5l-8-3zm-1.3 14.3l-3.7-3.7 1.4-1.4 2.3 2.3 5.3-5.3 1.4 1.4-6.7 6.7z"/>- </svg>- <svg class="icon icon--alarm" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>- </svg>- <svg class="icon icon--recent" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>- </svg>- <svg class="icon icon--past" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>- </svg>- </div>- {% endif %}+ {% include "entity/state_panels/smoke_detector/badge.html" %}<div class="list-meta"><div class="entity-name">{{ entity.name }}</div>- <div class="status-line">- <span class="status-label status-label--clear">Clear</span>- <span class="status-label status-label--alarm">Smoke Detected</span>- </div>+ <div class="status-label status-label--idle">All Clear</div>+ <div class="status-label status-label--active">Smoke Detected</div>+ <div class="status-label status-label--recent">Recently Cleared</div>+ <div class="status-label status-label--past">Past Alarm</div>+ {% with summary=smoke_data.recent_state_value_summary %}{% if summary.penultimate %}+ <div class="last-event">Triggered {{ summary.penultimate.timestamp|localtime|naturaltime }}</div>+ {% endif %}{% endwith %}</div>{% if battery_data %}<div class="aux-bits"><span data-state-id="{{ battery_data.entity_state.id }}"- data-display-text>{{ battery_data.latest_display_label }}</span>+ data-display-text+ data-status+ status="{{ battery_data.svg_status_style.status_value }}">{{ battery_data.latest_display_label }}</span></div>{% endif %}</div>--{% endwith %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/modal.html b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/modal.htmlindex c7a88a19..5d21fd74 100644--- a/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/modal.html+++ b/src/hi/apps/entity/templates/entity/state_panels/smoke_detector/modal.html@@ -1,33 +1,26 @@-{% with smoke_data=state_status_data_by_role.smoke battery_data=state_status_data_by_role.battery_level %}--{# The ``status`` attribute carries the smoke state's value for CSS #}-{# variant switching. Initial render uses the raw sensor value #}-{# (``smoke_clear`` / ``smoke_detected``); polling overwrites with #}-{# the decay-aware value (``idle`` / ``active`` / ``recent`` / #}-{# ``past``). CSS handles both vocabularies. #}+{% load humanize tz %}+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# smoke_data, battery_data. #}+{# #}+{# The panel root's ``status`` attribute holds the decay-aware token #}+{# (``active`` / ``recent`` / ``past`` / ``idle``) at render time AND #}+{# across polling ticks — CSS branches on that one vocabulary to #}+{# switch the badge icon, label text, and color tint per state. #}<div class="hi-state-panel-smoke_detector hi-state-panel-smoke_detector--modal"- {% if smoke_data %}data-state-id="{{ smoke_data.entity_state.id }}" data-status status="{{ smoke_data.latest_sensor_value }}"{% endif %}>+ data-state-id="{{ smoke_data.entity_state.id }}"+ data-status+ status="{{ smoke_data.svg_status_style.status_value }}">- {% if smoke_data %}<div class="hero">- <div class="badge">- <svg class="icon icon--clear" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2L4 5v6c0 5 3.5 9.5 8 11 4.5-1.5 8-6 8-11V5l-8-3zm-1.3 14.3l-3.7-3.7 1.4-1.4 2.3 2.3 5.3-5.3 1.4 1.4-6.7 6.7z"/>- </svg>- <svg class="icon icon--alarm" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>- </svg>- <svg class="icon icon--recent" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>- </svg>- <svg class="icon icon--past" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/>- </svg>- </div>- <div class="status-label status-label--clear">Clear</div>- <div class="status-label status-label--alarm">Smoke Detected</div>+ {% include "entity/state_panels/smoke_detector/badge.html" %}+ <div class="status-label status-label--idle">All Clear</div>+ <div class="status-label status-label--active">Smoke Detected</div>+ <div class="status-label status-label--recent">Recently Cleared</div>+ <div class="status-label status-label--past">Past Alarm</div>+ {% with summary=smoke_data.recent_state_value_summary %}{% if summary.penultimate %}+ <div class="last-event">Triggered {{ summary.penultimate.timestamp|localtime|naturaltime }}</div>+ {% endif %}{% endwith %}</div>- {% endif %}{% if battery_data %}<div class="auxiliary">@@ -35,11 +28,11 @@<div class="aux-label">Battery</div><div class="aux-value"data-state-id="{{ battery_data.entity_state.id }}"- data-display-text>{{ battery_data.latest_display_label }}</div>+ data-display-text+ data-status+ status="{{ battery_data.svg_status_style.status_value }}">{{ battery_data.latest_display_label }}</div></div></div>{% endif %}</div>--{% endwith %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/grid.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/grid.htmlindex 93809c30..ef5c2b17 100644--- a/src/hi/apps/entity/templates/entity/state_panels/thermostat/grid.html+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/grid.html@@ -1,26 +1,29 @@-{% with current_data=state_status_data_by_role.thermostat_current_temperature setpoint_data=state_status_data_by_role.thermostat_target_temperature action_data=state_status_data_by_role.hvac_action %}-+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# current_data, target_data, low_data, high_data, #}+{# action_data, mode_data. #}<div class="hi-state-panel-thermostat hi-state-panel-thermostat--grid"- {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}>+ {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}+ {% if mode_data %}data-hvac-mode-state-id="{{ mode_data.entity_state.id }}" data-hvac-mode="{{ mode_data.latest_sensor_value }}"{% endif %}>- {% if current_data %}- <div class="grid-temp"- data-state-id="{{ current_data.entity_state.id }}"- data-display-text>- {{ current_data.latest_display_label }}- </div>- {% endif %}+ <div class="grid-temp"+ data-state-id="{{ current_data.entity_state.id }}"+ data-display-text>+ {{ current_data.latest_display_label }}+ </div><div class="entity-name">{{ entity.name }}</div>- {% if setpoint_data %}- <div class="setpoint-line">- <span class="dial-mode-label" for-status="heating">Heating</span>- <span class="dial-mode-label" for-status="cooling">Cooling</span>- <span class="dial-mode-label" for-status="idle">Idle</span>- <span class="dial-mode-label" for-status="off">Off</span>- · <strong data-state-id="{{ setpoint_data.entity_state.id }}" data-display-text>{{ setpoint_data.latest_display_label }}</strong>- </div>- {% endif %}+ <div class="setpoint-line">+ <span class="dial-mode-label" for-status="heating">Heating</span>+ <span class="dial-mode-label" for-status="cooling">Cooling</span>+ <span class="dial-mode-label" for-status="idle">Idle</span>+ <span class="dial-mode-label" for-status="off">Off</span>+ {% if low_data and high_data %}+ <span class="setpoint-summary--dual"+ > · <strong data-state-id="{{ low_data.entity_state.id }}" data-display-text>{{ low_data.latest_display_label }}</strong>–<strong data-state-id="{{ high_data.entity_state.id }}" data-display-text>{{ high_data.latest_display_label }}</strong></span>+ {% endif %}+ {% if target_data %}+ <span class="setpoint-summary--single"+ > · <strong data-state-id="{{ target_data.entity_state.id }}" data-display-text>{{ target_data.latest_display_label }}</strong></span>+ {% endif %}+ </div></div>--{% endwith %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/list.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/list.htmlindex dc1a2c56..990bff21 100644--- a/src/hi/apps/entity/templates/entity/state_panels/thermostat/list.html+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/list.html@@ -1,44 +1,67 @@-{% with current_data=state_status_data_by_role.thermostat_current_temperature setpoint_data=state_status_data_by_role.thermostat_target_temperature action_data=state_status_data_by_role.hvac_action %}-+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# current_data, target_data, low_data, high_data, #}+{# action_data, mode_data, humidity_data. #}<div class="hi-state-panel-thermostat hi-state-panel-thermostat--list"- {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}>+ {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}+ {% if mode_data %}data-hvac-mode-state-id="{{ mode_data.entity_state.id }}" data-hvac-mode="{{ mode_data.latest_sensor_value }}"{% endif %}><div class="dial"><svg class="dial-svg" viewBox="0 0 220 220" aria-hidden="true"><circle class="dial-track" cx="110" cy="110" r="95" fill="none" stroke-width="2"/>- {% if setpoint_data %}- <g class="dial-setpoint-marker"- data-marker-state-id="{{ setpoint_data.entity_state.id }}"- data-temp-value="{{ setpoint_data.latest_display_value.magnitude }}">++ {% if low_data and high_data %}+ <g class="dial-setpoint-marker dial-setpoint-marker--dual dial-setpoint-marker--low"+ data-marker-state-id="{{ low_data.entity_state.id }}"+ data-temp-value="{{ low_data.latest_display_value.magnitude }}">+ <line x1="110" y1="10" x2="110" y2="24" stroke-width="6" stroke-linecap="round"/>+ </g>+ <g class="dial-setpoint-marker dial-setpoint-marker--dual dial-setpoint-marker--high"+ data-marker-state-id="{{ high_data.entity_state.id }}"+ data-temp-value="{{ high_data.latest_display_value.magnitude }}"><line x1="110" y1="10" x2="110" y2="24" stroke-width="6" stroke-linecap="round"/></g>{% endif %}- {% if current_data %}- <g class="dial-current-marker"- data-marker-state-id="{{ current_data.entity_state.id }}"- data-temp-value="{{ current_data.latest_display_value.magnitude }}">- <circle cx="110" cy="17" r="9"/>+ {% if target_data %}+ <g class="dial-setpoint-marker dial-setpoint-marker--single"+ data-marker-state-id="{{ target_data.entity_state.id }}"+ data-temp-value="{{ target_data.latest_display_value.magnitude }}">+ <line x1="110" y1="10" x2="110" y2="24" stroke-width="6" stroke-linecap="round"/></g>{% endif %}++ <g class="dial-current-marker"+ data-marker-state-id="{{ current_data.entity_state.id }}"+ data-temp-value="{{ current_data.latest_display_value.magnitude }}">+ <circle cx="110" cy="17" r="9"/>+ </g></svg><div class="dial-center">- {% if current_data %}- <span class="dial-temp"- data-state-id="{{ current_data.entity_state.id }}"- data-display-text>{{ current_data.latest_display_label }}</span>- {% endif %}+ <span class="dial-temp"+ data-state-id="{{ current_data.entity_state.id }}"+ data-display-text>{{ current_data.latest_display_label }}</span></div></div><div class="list-meta"><div class="entity-name">{{ entity.name }}</div>- {% if setpoint_data %}- <div class="setpoint-summary">- Target <strong data-state-id="{{ setpoint_data.entity_state.id }}" data-display-text>{{ setpoint_data.latest_display_label }}</strong>+ {% if low_data and high_data %}+ <div class="setpoint-summary setpoint-summary--dual">+ <strong data-state-id="{{ low_data.entity_state.id }}" data-display-text>{{ low_data.latest_display_label }}</strong>+ –+ <strong data-state-id="{{ high_data.entity_state.id }}" data-display-text>{{ high_data.latest_display_label }}</strong>+ </div>+ {% endif %}+ {% if target_data %}+ <div class="setpoint-summary setpoint-summary--single">+ Target <strong data-state-id="{{ target_data.entity_state.id }}" data-display-text>{{ target_data.latest_display_label }}</strong>+ </div>+ {% endif %}+ {% if humidity_data %}+ <div class="humidity-line">+ Humidity <span data-state-id="{{ humidity_data.entity_state.id }}"+ data-display-text>{{ humidity_data.latest_display_label }}</span></div>{% endif %}</div></div>--{% endwith %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/modal.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/modal.htmlindex 0cca0190..136cad97 100644--- a/src/hi/apps/entity/templates/entity/state_panels/thermostat/modal.html+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/modal.html@@ -1,40 +1,51 @@-{% load common_tags %}-{% with current_data=state_status_data_by_role.thermostat_current_temperature setpoint_data=state_status_data_by_role.thermostat_target_temperature action_data=state_status_data_by_role.hvac_action %}--{# The panel root carries ``data-state-id`` + ``data-status`` for #}-{# the HVAC_ACTION state so the polling dispatcher keeps the #}-{# ``status`` attribute current (idle / heating / cooling / off). #}-{# CSS keyed on ``[status=...]`` handles the color tint and the #}-{# dial-mode label visibility. The setpoint and current-temperature #}-{# markers on the dial are JS-positioned because their angle #}-{# depends on the numeric magnitude, which CSS alone can't compute. #}+{# Aliases declared in panel.py (role_data_template_aliases): #}+{# current_data, target_data, low_data, high_data, #}+{# action_data, mode_data, fan_data, preset_data, humidity_data. #}+{# #}+{# Setpoint UI selection (dual vs single) is driven by the live #}+{# ``data-hvac-mode`` attribute on the panel root: the template renders #}+{# every available setpoint block, and CSS hides the inactive one. #}+{# thermostat.js keeps ``data-hvac-mode`` synced with the polled #}+{# HVAC_MODE value so changing the mode select swaps the visible #}+{# setpoint controls without reopening the modal. #}<div class="hi-state-panel-thermostat hi-state-panel-thermostat--modal"- {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}>+ {% if action_data %}data-state-id="{{ action_data.entity_state.id }}" data-status status="{{ action_data.latest_sensor_value }}"{% endif %}+ {% if mode_data %}data-hvac-mode-state-id="{{ mode_data.entity_state.id }}" data-hvac-mode="{{ mode_data.latest_sensor_value }}"{% endif %}><div class="dial"><svg class="dial-svg" viewBox="0 0 220 220" aria-hidden="true"><circle class="dial-track" cx="110" cy="110" r="95" fill="none" stroke-width="2"/>- {% if setpoint_data %}- <g class="dial-setpoint-marker"- data-marker-state-id="{{ setpoint_data.entity_state.id }}"- data-temp-value="{{ setpoint_data.latest_display_value.magnitude }}">++ {% if low_data and high_data %}+ <g class="dial-setpoint-marker dial-setpoint-marker--dual dial-setpoint-marker--low"+ data-marker-state-id="{{ low_data.entity_state.id }}"+ data-temp-value="{{ low_data.latest_display_value.magnitude }}">+ <line x1="110" y1="8" x2="110" y2="24" stroke-width="3" stroke-linecap="round"/>+ </g>+ <g class="dial-setpoint-marker dial-setpoint-marker--dual dial-setpoint-marker--high"+ data-marker-state-id="{{ high_data.entity_state.id }}"+ data-temp-value="{{ high_data.latest_display_value.magnitude }}"><line x1="110" y1="8" x2="110" y2="24" stroke-width="3" stroke-linecap="round"/></g>{% endif %}- {% if current_data %}- <g class="dial-current-marker"- data-marker-state-id="{{ current_data.entity_state.id }}"- data-temp-value="{{ current_data.latest_display_value.magnitude }}">- <circle cx="110" cy="15" r="5"/>+ {% if target_data %}+ <g class="dial-setpoint-marker dial-setpoint-marker--single"+ data-marker-state-id="{{ target_data.entity_state.id }}"+ data-temp-value="{{ target_data.latest_display_value.magnitude }}">+ <line x1="110" y1="8" x2="110" y2="24" stroke-width="3" stroke-linecap="round"/></g>{% endif %}++ <g class="dial-current-marker"+ data-marker-state-id="{{ current_data.entity_state.id }}"+ data-temp-value="{{ current_data.latest_display_value.magnitude }}">+ <circle cx="110" cy="15" r="5"/>+ </g></svg><div class="dial-center">- {% if current_data %}- <span class="dial-temp"- data-state-id="{{ current_data.entity_state.id }}"- data-display-text>{{ current_data.latest_display_label }}</span>- {% endif %}+ <span class="dial-temp"+ data-state-id="{{ current_data.entity_state.id }}"+ data-display-text>{{ current_data.latest_display_label }}</span><span class="dial-mode-label" for-status="idle">Idle</span><span class="dial-mode-label" for-status="heating">Heating</span><span class="dial-mode-label" for-status="cooling">Cooling</span>@@ -42,12 +53,63 @@</div></div>- {% if state_status_data_list %}- <div class="states">- {% include "entity/state_panels/fallback/state_list.html" with entity_state_status_data_list=state_status_data_list %}+ {% if low_data and high_data or target_data or mode_data or fan_data or preset_data %}+ <div class="thermostat-controls">++ {% if low_data and high_data or target_data %}+ <div class="thermostat-setpoint-row">+ {% if low_data and high_data %}+ <div class="control-group setpoint-block setpoint-block--dual">+ <div class="control-label">Low Setpoint</div>+ {% include "entity/state_panels/thermostat/setpoint_stepper.html" with setpoint_data=low_data %}+ </div>+ <div class="control-group setpoint-block setpoint-block--dual">+ <div class="control-label">High Setpoint</div>+ {% include "entity/state_panels/thermostat/setpoint_stepper.html" with setpoint_data=high_data %}+ </div>+ {% endif %}+ {% if target_data %}+ <div class="control-group setpoint-block setpoint-block--single">+ <div class="control-label">Setpoint</div>+ {% include "entity/state_panels/thermostat/setpoint_stepper.html" with setpoint_data=target_data %}+ </div>+ {% endif %}+ </div>+ {% endif %}++ {% if mode_data or fan_data or preset_data %}+ <div class="thermostat-modes-grid">+ {% if mode_data %}+ <div class="control-group">+ <div class="control-label">Mode</div>+ {% include "entity/state_panels/thermostat/role_control.html" with role_data=mode_data %}+ </div>+ {% endif %}+ {% if fan_data %}+ <div class="control-group">+ <div class="control-label">Fan</div>+ {% include "entity/state_panels/thermostat/role_control.html" with role_data=fan_data %}+ </div>+ {% endif %}+ {% if preset_data %}+ <div class="control-group">+ <div class="control-label">Preset</div>+ {% include "entity/state_panels/thermostat/role_control.html" with role_data=preset_data %}+ </div>+ {% endif %}+ </div>+ {% endif %}++ </div>+ {% endif %}++ {% if humidity_data %}+ <div class="thermostat-secondary">+ <span class="secondary-label">Humidity</span>+ <span class="secondary-value"+ data-state-id="{{ humidity_data.entity_state.id }}"+ data-display-text>{{ humidity_data.latest_display_label }}</span></div>{% endif %}</div>--{% endwith %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/role_control.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/role_control.htmlnew file mode 100644index 00000000..a8166b7d--- /dev/null+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/role_control.html@@ -0,0 +1,34 @@+{# Thermostat-local select widget for controllable discrete roles #}+{# (Mode / Fan / Preset). Renders a plain form-wrapped <select>; the #}+{# form is a CSRF + URL carrier only, with no antinode hooks #}+{# (no ``onchange-async``, no ``data-async``). The thermostat JS does #}+{# the POST on change and the framework's unified ``apply`` path #}+{# handles the optimistic UI update via ``data-state-id`` / #}+{# ``data-controller-value`` on the select itself. Sense-only roles #}+{# render as a read-only label. #}+{% if role_data.controller_data_list %}+ {% with controller_data=role_data.controller_data_list.0 %}+ {% with controller=controller_data.controller %}+ <form action="{% url 'control_controller' controller_id=controller.id %}"+ method="post"+ class="thermostat-select-form">+ {% csrf_token %}+ <div class="discrete-control">+ <select name="value"+ class="discrete-select form-select thermostat-select"+ data-state-id="{{ controller_data.entity_state.id }}"+ data-controller-value>+ {% for value, label in controller.choices %}+ <option value="{{ value }}"+ {% if controller_data.latest_sensor_response.value.lower == value.lower %}selected{% endif %}>{{ label }}</option>+ {% endfor %}+ </select>+ </div>+ </form>+ {% endwith %}+ {% endwith %}+{% else %}+ <div class="control-readonly"+ data-state-id="{{ role_data.entity_state.id }}"+ data-display-text>{{ role_data.latest_display_label }}</div>+{% endif %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/thermostat/setpoint_stepper.html b/src/hi/apps/entity/templates/entity/state_panels/thermostat/setpoint_stepper.htmlnew file mode 100644index 00000000..46d0b6b2--- /dev/null+++ b/src/hi/apps/entity/templates/entity/state_panels/thermostat/setpoint_stepper.html@@ -0,0 +1,38 @@+{# Setpoint −/+ stepper. JS click handler reads the hidden input's #}+{# value, bumps by data-stepper-delta, optimistically updates the #}+{# visible label, and POSTs the new value to the controller. The #}+{# polling contract refreshes both the hidden input (via #}+{# data-controller-value) and the visible label (via data-display- #}+{# text) on the next tick, keeping initial / interactive / external- #}+{# change paths consistent. #}+<div class="setpoint-stepper">+ {% if setpoint_data.controller_data_list %}+ {% with controller=setpoint_data.controller_data_list.0.controller %}+ <form action="{% url 'control_controller' controller_id=controller.id %}"+ method="post"+ class="setpoint-stepper-form">+ {% csrf_token %}+ <button type="button"+ class="stepper-btn stepper-btn--decrement"+ data-stepper-delta="-1"+ aria-label="Decrease setpoint">−</button>+ <input type="hidden" name="value"+ class="setpoint-stepper-input"+ data-state-id="{{ setpoint_data.entity_state.id }}"+ data-controller-value+ value="{{ setpoint_data.latest_display_value.magnitude }}">+ <span class="setpoint-value"+ data-state-id="{{ setpoint_data.entity_state.id }}"+ data-display-text>{{ setpoint_data.latest_display_label }}</span>+ <button type="button"+ class="stepper-btn stepper-btn--increment"+ data-stepper-delta="1"+ aria-label="Increase setpoint">+</button>+ </form>+ {% endwith %}+ {% else %}+ <span class="setpoint-value setpoint-value--readonly"+ data-state-id="{{ setpoint_data.entity_state.id }}"+ data-display-text>{{ setpoint_data.latest_display_label }}</span>+ {% endif %}+</div>diff --git a/src/hi/apps/entity/templatetags/state_panel_tags.py b/src/hi/apps/entity/templatetags/state_panel_tags.pyindex ae51061f..6412a486 100644--- a/src/hi/apps/entity/templatetags/state_panel_tags.py+++ b/src/hi/apps/entity/templatetags/state_panel_tags.py@@ -1,74 +1,20 @@-"""Template tags for the EntityStatusPanel framework.--``render_entity_status_panel`` is the dispatch point used at each-panel call site (EntityStatus modal body, collection list card,-collection grid card). It resolves a template along the panel-fallback chain and renders it with the parent context plus-panel-specific additions.--``panel_state`` is a presentation helper for panel templates that-need to pull a specific EntityState by ``EntityStateRole`` (e.g.,-the thermostat panel reaching for the current-temperature state)."""--from typing import Optional-from django import template--from hi.apps.entity.enums import EntityStateRole-from hi.apps.entity.models import Entity, EntityState-from hi.apps.entity.state_panel_dispatch import (- SUPPORTED_DISPLAY_CONTEXTS,- resolve_panel_template,-)+from django.template.loader import get_templateregister = template.Library()@register.simple_tag( takes_context = True )-def render_entity_status_panel( context, entity_status_data, display_context_name : str ):- """Render the panel for ``entity_status_data.entity`` in- ``display_context_name``.-- The panel template's context is the parent's flattened context- merged with the entity_status_data's ``to_template_context()``- fields, so panel templates have ``entity``,- ``state_status_data_list``, ``state_status_data_by_role``, and the- other display fields at the top level regardless of which call- site (modal / list card / grid card) invokes the tag."""-- if display_context_name not in SUPPORTED_DISPLAY_CONTEXTS:- raise ValueError(- f'Unsupported display context: {display_context_name!r}. '- f'Expected one of {SUPPORTED_DISPLAY_CONTEXTS}.'- )-- template_obj = resolve_panel_template(- entity_type = entity_status_data.entity.entity_type,- display_context_name = display_context_name,- )+def include_panel( context, state_panel_data ):+ """Render ``state_panel_data.panel_template`` with the parent context+ flattened and ``state_panel_data.panel_context`` merged on top. The+ view layer resolves which panel to render; this tag handles only the+ context flattening that template-side ``{% include %}`` cannot express.+ The parent's ``request`` is passed through so the inner template+ renders under a RequestContext (re-running context processors)."""flat = context.flatten()- flat.update( entity_status_data.to_template_context() )- flat[ 'display_context_name' ] = display_context_name- return template_obj.render( flat )---def panel_state( entity : Entity, role : str ) -> Optional[ EntityState ]:- """Return the EntityState on ``entity`` whose role matches- ``role`` (case-insensitive name match against ``EntityStateRole``),- or ``None`` when no such state exists. Walks both the entity's- own states and delegated states."""-- try:- role_enum = EntityStateRole.from_name( role )- except ValueError:- return None-- for state in entity.states.all():- if state.entity_state_role == role_enum:- return state- for delegation in entity.entity_state_delegations.select_related( 'entity_state' ).all():- if delegation.entity_state.entity_state_role == role_enum:- return delegation.entity_state- return None+ flat.update( state_panel_data.panel_context )+ return get_template( state_panel_data.panel_template ).render(+ flat, request = context.get( 'request' ),+ )diff --git a/src/hi/apps/entity/tests/test_state_panel_dispatch.py b/src/hi/apps/entity/tests/test_state_panel_dispatch.pydeleted file mode 100644index 29caa959..00000000--- a/src/hi/apps/entity/tests/test_state_panel_dispatch.py+++ /dev/null@@ -1,155 +0,0 @@-import logging-from unittest.mock import patch--from django.template.exceptions import TemplateDoesNotExist--from hi.apps.entity.enums import EntityType-from hi.apps.entity.state_panel_dispatch import (- FRAMEWORK_FALLBACK_TEMPLATES,- SUPPORTED_DISPLAY_CONTEXTS,- resolve_panel_template,-)-from hi.testing.base_test_case import BaseTestCase--logging.disable(logging.CRITICAL)---class TestResolvePanelTemplate(BaseTestCase):- """``resolve_panel_template`` walks a three-step chain: the panel's- context-specific template, the panel's required default (modal.html),- then the framework's per-context fallback. The framework fallbacks- are guaranteed to exist; the panel templates may or may not."""-- def test_falls_back_to_framework_default_when_no_panel_exists(self):- # SMOKE_DETECTOR has no panel templates in Phase 1; resolution- # lands on the framework fallback for the modal context.- template_obj = resolve_panel_template(- entity_type = EntityType.OTHER,- display_context_name = 'modal',- )- self.assertEqual(- template_obj.origin.template_name,- FRAMEWORK_FALLBACK_TEMPLATES[ 'modal' ],- )-- def test_falls_back_to_framework_default_for_list_context(self):- template_obj = resolve_panel_template(- entity_type = EntityType.OTHER,- display_context_name = 'list',- )- self.assertEqual(- template_obj.origin.template_name,- FRAMEWORK_FALLBACK_TEMPLATES[ 'list' ],- )-- def test_falls_back_to_framework_default_for_grid_context(self):- template_obj = resolve_panel_template(- entity_type = EntityType.OTHER,- display_context_name = 'grid',- )- self.assertEqual(- template_obj.origin.template_name,- FRAMEWORK_FALLBACK_TEMPLATES[ 'grid' ],- )-- def test_returns_panel_context_template_when_present(self):- # Simulate a panel directory existing for camera with all- # three context-specific templates.- with patch(- 'hi.apps.entity.state_panel_dispatch.get_template'- ) as mock_get_template:- mock_get_template.side_effect = self._template_existence_simulator({- 'entity/state_panels/camera/grid.html': True,- })- template_obj = resolve_panel_template(- entity_type = EntityType.CAMERA,- display_context_name = 'grid',- )- self.assertEqual(- mock_get_template.call_args_list[ 0 ].args[ 0 ],- 'entity/state_panels/camera/grid.html',- )- self.assertIsNotNone( template_obj )-- def test_list_context_falls_back_to_panel_modal_when_list_absent(self):- # Panel provides modal.html but not list.html; resolution- # should reach modal.html, not the framework fallback.- with patch(- 'hi.apps.entity.state_panel_dispatch.get_template'- ) as mock_get_template:- mock_get_template.side_effect = self._template_existence_simulator({- 'entity/state_panels/camera/modal.html': True,- })- resolve_panel_template(- entity_type = EntityType.CAMERA,- display_context_name = 'list',- )- requested_paths = [ call.args[ 0 ] for call in mock_get_template.call_args_list ]- self.assertIn( 'entity/state_panels/camera/list.html', requested_paths )- self.assertIn( 'entity/state_panels/camera/modal.html', requested_paths )- # Resolution stops at modal.html; framework fallback is never asked.- self.assertNotIn(- FRAMEWORK_FALLBACK_TEMPLATES[ 'list' ],- requested_paths,- )-- def test_modal_context_lookup_order(self):- # Modal context tries the panel's modal.html, then the framework- # fallback. There is no intermediate step.- with patch(- 'hi.apps.entity.state_panel_dispatch.get_template'- ) as mock_get_template:- mock_get_template.side_effect = self._template_existence_simulator( {} )- resolve_panel_template(- entity_type = EntityType.THERMOSTAT,- display_context_name = 'modal',- )- requested_paths = [ call.args[ 0 ] for call in mock_get_template.call_args_list ]- # First lookup is panel/modal; last is framework fallback. The- # middle step (panel/modal again) is harmless duplication.- self.assertEqual(- requested_paths[ 0 ],- 'entity/state_panels/thermostat/modal.html',- )- self.assertEqual(- requested_paths[ -1 ],- FRAMEWORK_FALLBACK_TEMPLATES[ 'modal' ],- )-- def test_unsupported_context_raises(self):- with self.assertRaises( ValueError ):- resolve_panel_template(- entity_type = EntityType.OTHER,- display_context_name = 'sidebar',- )-- def test_all_supported_contexts_resolve_to_real_framework_fallbacks(self):- # Sanity check: every supported context has a framework- # fallback template that actually exists.- for context_name in SUPPORTED_DISPLAY_CONTEXTS:- template_obj = resolve_panel_template(- entity_type = EntityType.OTHER,- display_context_name = context_name,- )- self.assertEqual(- template_obj.origin.template_name,- FRAMEWORK_FALLBACK_TEMPLATES[ context_name ],- )-- # -------------------------------------------------------------------- def _template_existence_simulator( self, existing_template_names_dict ):- """Return a mock side_effect that simulates ``get_template``- finding the listed templates, plus the framework fallbacks- (which are guaranteed to exist in production)."""- from django.template.loader import get_template as real_get_template-- existing = set( existing_template_names_dict )- existing.update( FRAMEWORK_FALLBACK_TEMPLATES.values() )-- def side_effect( template_name ):- if template_name in existing:- return real_get_template( FRAMEWORK_FALLBACK_TEMPLATES[ 'modal' ] )- raise TemplateDoesNotExist( template_name )-- return side_effectdiff --git a/src/hi/apps/entity/tests/test_state_panel_framework.py b/src/hi/apps/entity/tests/test_state_panel_framework.pynew file mode 100644index 00000000..e77a7048--- /dev/null+++ b/src/hi/apps/entity/tests/test_state_panel_framework.py@@ -0,0 +1,387 @@+import logging++from hi.apps.entity.enums import DisplayContext, EntityStateRole, EntityType+from hi.apps.entity.state_panel_base import EntityStatePanel+from hi.apps.entity.state_panel_dispatch import StatePanelDispatcher+from hi.apps.entity.state_panel_registry import EntityStatePanelRegistry+from hi.testing.base_test_case import BaseTestCase+++logging.disable( logging.CRITICAL )+++def _make_panel( **overrides ) -> EntityStatePanel:+ """Build an EntityStatePanel with sensible defaults for testing.+ Only the attributes the test cares about need to be passed."""+ defaults = dict(+ name = 'p',+ display_contexts = { DisplayContext.MODAL },+ priority = 10,+ template_name = 'entity/state_panels/p/panel.html',+ )+ defaults.update( overrides )+ return EntityStatePanel( **defaults )+++class TestEntityStatePanelValidation( BaseTestCase ):++ def test_minimal_construction_succeeds( self ):+ panel = _make_panel()+ self.assertEqual( panel.name, 'p' )+ self.assertIsNone( panel.entity_type )+ self.assertEqual( panel.required_roles, set() )+ self.assertEqual( panel.optional_roles, set() )++ def test_empty_name_rejected( self ):+ with self.assertRaises( TypeError ):+ _make_panel( name = '' )++ def test_non_string_template_name_rejected( self ):+ with self.assertRaises( TypeError ):+ _make_panel( template_name = None )++ def test_empty_display_contexts_rejected( self ):+ with self.assertRaises( TypeError ):+ _make_panel( display_contexts = set() )++ def test_non_context_member_in_display_contexts_rejected( self ):+ with self.assertRaises( TypeError ):+ _make_panel( display_contexts = { 'modal' } )++ def test_non_int_priority_rejected( self ):+ with self.assertRaises( TypeError ):+ _make_panel( priority = '10' )++ def test_non_entity_type_rejected( self ):+ with self.assertRaises( TypeError ):+ _make_panel( entity_type = 'thermostat' )++ def test_overlapping_role_sets_rejected( self ):+ with self.assertRaises( TypeError ):+ _make_panel(+ required_roles = { EntityStateRole.TEMPERATURE },+ optional_roles = { EntityStateRole.TEMPERATURE },+ )++ def test_role_data_template_alias_to_undeclared_role_rejected( self ):+ # Aliasing a role that's not in required_roles | optional_roles+ # is an authoring mistake — the dispatcher would always resolve+ # it to None for typed panels (filtered by-role map) or to+ # whatever happens to be present for fallback panels.+ with self.assertRaises( TypeError ):+ _make_panel(+ required_roles = { EntityStateRole.TEMPERATURE },+ role_data_template_aliases = {+ 'temp_data': EntityStateRole.HUMIDITY,+ },+ )++ def test_role_data_template_alias_must_be_entity_state_role( self ):+ with self.assertRaises( TypeError ):+ _make_panel(+ required_roles = { EntityStateRole.TEMPERATURE },+ role_data_template_aliases = {+ 'temp_data': 'temperature',+ },+ )+++class TestEntityStatePanelRegistry( BaseTestCase ):++ def setUp( self ):+ super().setUp()+ self._registry_snapshot = EntityStatePanelRegistry().snapshot_for_tests()+ EntityStatePanelRegistry().restore_for_tests( ( {}, False ) )++ def tearDown( self ):+ EntityStatePanelRegistry().restore_for_tests( self._registry_snapshot )+ super().tearDown()++ def test_register_adds_panel( self ):+ registry = EntityStatePanelRegistry()+ panel = _make_panel( name = 'alpha' )+ registry.register( panel )+ self.assertIs( registry.get_by_name( 'alpha' ), panel )+ self.assertIn( panel, registry.all_panels() )++ def test_re_registering_same_instance_is_idempotent( self ):+ registry = EntityStatePanelRegistry()+ panel = _make_panel( name = 'alpha' )+ registry.register( panel )+ registry.register( panel )+ self.assertEqual( len( registry.all_panels() ), 1 )++ def test_duplicate_name_different_instance_rejected( self ):+ registry = EntityStatePanelRegistry()+ registry.register( _make_panel( name = 'alpha' ) )+ with self.assertRaises( RuntimeError ):+ registry.register( _make_panel( name = 'alpha' ) )+++class TestResolvePanel( BaseTestCase ):++ def setUp( self ):+ super().setUp()+ self._registry_snapshot = EntityStatePanelRegistry().snapshot_for_tests()+ EntityStatePanelRegistry().restore_for_tests( ( {}, False ) )++ def tearDown( self ):+ EntityStatePanelRegistry().restore_for_tests( self._registry_snapshot )+ super().tearDown()++ def _register( self, panel ):+ EntityStatePanelRegistry().register( panel )+ return panel++ def test_typed_panel_wins_when_required_roles_present( self ):+ thermostat = self._register( _make_panel(+ name = 'thermostat',+ entity_type = EntityType.THERMOSTAT,+ required_roles = { EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE },+ ) )+ fallback = self._register( _make_panel(+ name = 'fallback', entity_type = None,+ ) )+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.MODAL,+ present_roles = { EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE },+ )+ self.assertIs( resolution.panel, thermostat )+ self.assertNotIn( fallback, resolution.trace )++ def test_lower_priority_wins_among_typed_matches( self ):+ winner = self._register( _make_panel(+ name = 'specific',+ entity_type = EntityType.THERMOSTAT,+ priority = 10,+ required_roles = { EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE },+ ) )+ self._register( _make_panel(+ name = 'general',+ entity_type = EntityType.THERMOSTAT,+ priority = 20,+ ) )+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.MODAL,+ present_roles = { EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE },+ )+ self.assertIs( resolution.panel, winner )++ def test_name_breaks_priority_tie_alphabetically( self ):+ a = self._register( _make_panel(+ name = 'aaa', entity_type = EntityType.THERMOSTAT, priority = 10,+ ) )+ self._register( _make_panel(+ name = 'bbb', entity_type = EntityType.THERMOSTAT, priority = 10,+ ) )+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.MODAL,+ present_roles = set(),+ )+ self.assertIs( resolution.panel, a )++ def test_missing_required_role_disqualifies_typed_panel( self ):+ self._register( _make_panel(+ name = 'thermostat',+ entity_type = EntityType.THERMOSTAT,+ required_roles = { EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE },+ ) )+ fallback = self._register( _make_panel(+ name = 'fallback', entity_type = None,+ ) )+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.MODAL,+ present_roles = set(),+ )+ self.assertIs( resolution.panel, fallback )++ def test_display_context_mismatch_disqualifies_typed_panel( self ):+ self._register( _make_panel(+ name = 'modal_only',+ entity_type = EntityType.THERMOSTAT,+ display_contexts = { DisplayContext.MODAL },+ ) )+ fallback = self._register( _make_panel(+ name = 'fallback',+ entity_type = None,+ display_contexts = { DisplayContext.MODAL, DisplayContext.GRID },+ ) )+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.GRID,+ present_roles = set(),+ )+ self.assertIs( resolution.panel, fallback )++ def test_extras_are_roles_outside_declared_set( self ):+ self._register( _make_panel(+ name = 'thermostat',+ entity_type = EntityType.THERMOSTAT,+ required_roles = { EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE },+ optional_roles = { EntityStateRole.HUMIDITY },+ ) )+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.MODAL,+ present_roles = {+ EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE,+ EntityStateRole.HUMIDITY,+ EntityStateRole.SMOKE,+ EntityStateRole.BATTERY_LEVEL,+ },+ )+ self.assertEqual(+ resolution.extras,+ { EntityStateRole.SMOKE, EntityStateRole.BATTERY_LEVEL },+ )++ def test_no_fallback_for_context_raises( self ):+ self._register( _make_panel(+ name = 'fallback',+ entity_type = None,+ display_contexts = { DisplayContext.MODAL },+ ) )+ with self.assertRaises( RuntimeError ):+ StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.GRID,+ present_roles = set(),+ )+++class TestProductionPanelDiscovery( BaseTestCase ):+ """End-to-end check that the panel.py modules under+ ``hi.apps.entity.state_panels`` are wired up: each existing panel+ type resolves to a panel for each display context."""++ EXPECTED_TYPED_PANELS = {+ (EntityType.THERMOSTAT, DisplayContext.MODAL): 'thermostat_modal',+ (EntityType.THERMOSTAT, DisplayContext.LIST): 'thermostat_list',+ (EntityType.THERMOSTAT, DisplayContext.GRID): 'thermostat_grid',+ (EntityType.SMOKE_DETECTOR, DisplayContext.MODAL): 'smoke_detector_modal',+ (EntityType.SMOKE_DETECTOR, DisplayContext.LIST): 'smoke_detector_list',+ (EntityType.SMOKE_DETECTOR, DisplayContext.GRID): 'smoke_detector_grid',+ (EntityType.CAMERA, DisplayContext.MODAL): 'camera_modal',+ (EntityType.CAMERA, DisplayContext.LIST): 'camera_list',+ (EntityType.CAMERA, DisplayContext.GRID): 'camera_grid',+ }++ EXPECTED_FALLBACK_PANELS = {+ DisplayContext.MODAL: 'fallback_modal',+ DisplayContext.LIST: 'fallback_list',+ DisplayContext.GRID: 'fallback_grid',+ }++ def test_typed_panels_resolve_with_required_roles( self ):+ thermostat_present_roles = { EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE }+ smoke_present_roles = { EntityStateRole.SMOKE }+ for ( entity_type, ctx ), expected_name in self.EXPECTED_TYPED_PANELS.items():+ if entity_type == EntityType.THERMOSTAT:+ present_roles = thermostat_present_roles+ elif entity_type == EntityType.SMOKE_DETECTOR:+ present_roles = smoke_present_roles+ else:+ present_roles = set()+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = entity_type,+ display_context = ctx,+ present_roles = present_roles,+ )+ self.assertEqual(+ resolution.panel.name, expected_name,+ msg = f'{entity_type.name}/{ctx.name}',+ )++ def test_unknown_entity_type_falls_back( self ):+ for ctx, expected_name in self.EXPECTED_FALLBACK_PANELS.items():+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.OTHER,+ display_context = ctx,+ present_roles = set(),+ )+ self.assertEqual( resolution.panel.name, expected_name )++ def test_typed_panel_falls_back_when_required_role_absent( self ):+ # Thermostat with no roles -> required THERMOSTAT_CURRENT_TEMPERATURE+ # is missing, so dispatch falls through to fallback.+ resolution = StatePanelDispatcher.resolve_panel(+ entity_type = EntityType.THERMOSTAT,+ display_context = DisplayContext.MODAL,+ present_roles = set(),+ )+ self.assertEqual( resolution.panel.name, 'fallback_modal' )+++class TestDiscoveryErrorHandling( BaseTestCase ):++ def setUp( self ):+ super().setUp()+ self._registry_snapshot = EntityStatePanelRegistry().snapshot_for_tests()++ def tearDown( self ):+ EntityStatePanelRegistry().restore_for_tests( self._registry_snapshot )+ super().tearDown()++ def test_broken_panel_module_does_not_abort_discovery( self ):+ """If one panel.py raises at import, discover() should log and+ continue rather than poisoning Django startup."""+ from unittest.mock import patch+ registry = EntityStatePanelRegistry()+ registry.restore_for_tests( ( {}, False ) )++ with patch(+ 'hi.apps.entity.state_panel_registry.importlib.import_module',+ side_effect = lambda name: (+ ( _ for _ in () ).throw( RuntimeError( 'boom' ) )+ if name.endswith( '.thermostat.panel' )+ else __import__( name, fromlist = [ '*' ] )+ ),+ ):+ registry.discover()++ # The broken panel is skipped, but other panels still register.+ all_names = { p.name for p in registry.all_panels() }+ self.assertIn( 'fallback_modal', all_names )+ # Thermostat module was the one we broke; its panels are absent.+ self.assertNotIn( 'thermostat_modal', all_names )+++class TestIncludePanelTag( BaseTestCase ):++ def test_panel_context_keys_override_parent_context_keys( self ):+ """The {% include_panel %} tag must merge ``panel_context`` over+ the parent context so a panel template sees the panel-filtered+ values, not whatever the wrapper happened to define."""+ from django.template import Context, Template+ from hi.apps.entity.state_panel_dispatch import EntityStatePanelData+ from unittest.mock import Mock++ # A tiny inline template registered via Django's loaders is fussy;+ # easier to mock the loader resolution.+ panel_data = EntityStatePanelData(+ entity_display_data = Mock(),+ panel_template = 'fixtures/test_include_panel.html',+ panel_context = { 'shared_var': 'from-panel-context' },+ )+ from unittest.mock import patch+ rendered = None+ with patch(+ 'hi.apps.entity.templatetags.state_panel_tags.get_template'+ ) as mock_get_template:+ mock_get_template.return_value.render.return_value = 'ok'+ mock_get_template.return_value.render.side_effect = (+ lambda flat, request = None: f'shared_var={flat.get("shared_var")}'+ )+ t = Template(+ '{% load state_panel_tags %}'+ '{% include_panel panel_data %}'+ )+ rendered = t.render( Context( {+ 'panel_data': panel_data,+ 'shared_var': 'from-parent-context',+ } ) )+ self.assertEqual( rendered, 'shared_var=from-panel-context' )diff --git a/src/hi/apps/entity/tests/test_state_panel_tags.py b/src/hi/apps/entity/tests/test_state_panel_tags.pydeleted file mode 100644index 663fb36c..00000000--- a/src/hi/apps/entity/tests/test_state_panel_tags.py+++ /dev/null@@ -1,93 +0,0 @@-import logging--from hi.apps.entity.enums import EntityStateRole, EntityType-from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation-from hi.apps.entity.templatetags.state_panel_tags import panel_state-from hi.testing.base_test_case import BaseTestCase--logging.disable(logging.CRITICAL)---class TestPanelState(BaseTestCase):- """``panel_state`` looks up an EntityState on the entity by- EntityStateRole (case-insensitive name match), walking the- entity's own states then delegated states. Returns None when- no state with the requested role is bound to the entity."""-- def setUp(self):- super().setUp()- self.entity = Entity.objects.create(- name = 'Test Thermostat',- entity_type_str = str( EntityType.THERMOSTAT ),- )- self.current_temp_state = EntityState.objects.create(- entity = self.entity,- name = 'Current Temperature',- entity_state_type_str = 'TEMPERATURE',- role_str = str( EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE ),- )- self.setpoint_state = EntityState.objects.create(- entity = self.entity,- name = 'Target Temperature',- entity_state_type_str = 'TEMPERATURE',- role_str = str( EntityStateRole.THERMOSTAT_TARGET_TEMPERATURE ),- )-- def test_returns_state_matching_role(self):- state = panel_state( self.entity, 'thermostat_current_temperature' )- self.assertEqual( state, self.current_temp_state )-- def test_role_match_is_case_insensitive(self):- state = panel_state( self.entity, 'THERMOSTAT_TARGET_TEMPERATURE' )- self.assertEqual( state, self.setpoint_state )-- def test_returns_none_when_no_state_matches_role(self):- # The entity has no HVAC_MODE state; lookup returns None.- result = panel_state( self.entity, 'hvac_mode' )- self.assertIsNone( result )-- def test_returns_none_for_unknown_role_name(self):- result = panel_state( self.entity, 'definitely_not_a_real_role' )- self.assertIsNone( result )-- def test_walks_delegated_states(self):- # A state delegated from another entity should be reachable- # by role lookup on the delegating entity.- principal_entity = Entity.objects.create(- name = 'External Humidity Sensor',- entity_type_str = str( EntityType.OTHER ),- )- humidity_state = EntityState.objects.create(- entity = principal_entity,- name = 'Humidity',- entity_state_type_str = 'HUMIDITY',- role_str = str( EntityStateRole.HUMIDITY ),- )- EntityStateDelegation.objects.create(- delegate_entity = self.entity,- entity_state = humidity_state,- )-- state = panel_state( self.entity, 'humidity' )- self.assertEqual( state, humidity_state )-- def test_own_state_wins_over_delegated_when_roles_collide(self):- # If both an own state and a delegated state carry the same- # role, the entity's own state is returned (own-states pass- # is first in the lookup order).- principal_entity = Entity.objects.create(- name = 'External', entity_type_str = str( EntityType.OTHER ),- )- delegated_dup = EntityState.objects.create(- entity = principal_entity,- name = 'Other Current Temp',- entity_state_type_str = 'TEMPERATURE',- role_str = str( EntityStateRole.THERMOSTAT_CURRENT_TEMPERATURE ),- )- EntityStateDelegation.objects.create(- delegate_entity = self.entity,- entity_state = delegated_dup,- )-- state = panel_state( self.entity, 'thermostat_current_temperature' )- self.assertEqual( state, self.current_temp_state )diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex cf691c8e..a29de5c9 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -682,6 +682,33 @@ class TestEntityStatusView(DualModeViewTestCase):self.assertEqual(response.status_code, 405)+ def test_type_specific_panel_falls_back_when_required_role_absent(self):+ """A typed panel whose required roles are missing on the entity+ must fall back to the framework fallback panel rather than+ render a misshapen typed view. Wires the resolver + view layer+ end-to-end so a regression in dispatch routing surfaces here."""+ from hi.apps.entity.models import Entity, EntityState+ # THERMOSTAT panel requires THERMOSTAT_CURRENT_TEMPERATURE.+ # Give the entity only an unrelated ON_OFF state so the typed+ # panel is disqualified and the fallback wins.+ thermostat_without_temp = Entity.objects.create(+ integration_id='test.thermostat_no_temp',+ integration_name='test_integration',+ name='Misconfigured Thermostat',+ entity_type_str=str(EntityType.THERMOSTAT),+ )+ EntityState.objects.create(+ entity=thermostat_without_temp,+ entity_state_type_str=str(EntityStateType.ON_OFF),+ name='Some State',+ )+ url = reverse('entity_status', kwargs={'entity_id': thermostat_without_temp.id})+ response = self.client.get(url)+ self.assertSuccessResponse(response)+ state_panel_data = response.context['state_panel_data']+ self.assertEqual(state_panel_data.panel_template,+ 'entity/state_panels/fallback/modal.html')+class TestEntityHistoryView(DualModeViewTestCase):"""EntityHistoryView is the per-entity overview modal showingdiff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.pyindex 4e3d4c65..1b92481b 100644--- a/src/hi/apps/entity/views.py+++ b/src/hi/apps/entity/views.py@@ -9,6 +9,8 @@ from hi.apps.common import datetimeproxyfrom hi.apps.attribute.view_mixins import AttributeEditViewMixinfrom hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer+from hi.apps.entity.enums import DisplayContext+from hi.apps.entity.state_panel_dispatch import StatePanelDispatcherfrom hi.apps.monitor.display_data import EntityDisplayDatafrom hi.apps.monitor.status_display_manager import StatusDisplayManager@@ -43,7 +45,14 @@ class EntityStatusView( HiModalView, EntityViewMixin ):return EntityEditView().get( request, *args, **kwargs )entity_display_data = EntityDisplayData( entity_status_data = entity_status_data )- context = entity_display_data.to_template_context()+ debug = bool( request.GET.get( 'debug_panel' ) )+ state_panel_data = StatePanelDispatcher.build_state_panel_data(+ entity_display_data, DisplayContext.MODAL, debug = debug,+ )+ context = {+ 'state_panel_data' : state_panel_data,+ 'panel_trace' : state_panel_data.trace if debug else None,+ }return self.modal_response( request, context )diff --git a/src/hi/apps/monitor/display_data.py b/src/hi/apps/monitor/display_data.pyindex 9a94a202..05884f66 100644--- a/src/hi/apps/monitor/display_data.py+++ b/src/hi/apps/monitor/display_data.py@@ -9,7 +9,9 @@ conversion, formatted labels, SVG status styles, role-keyed lookup,etc.). Manager produces raw; views project."""from dataclasses import dataclass, field-from typing import Dict, List, Optional+from datetime import datetime+from functools import cached_property+from typing import Dict, List, Optional, Setimport hi.apps.common.datetimeproxy as datetimeproxy@@ -19,7 +21,7 @@ from hi.apps.console.console_converter_helper import (DisplayValue,)from hi.apps.entity.entity_state_role_order import ENTITY_STATUS_VIEW_ORDERING-from hi.apps.entity.enums import EntityStateType, EntityStateValue+from hi.apps.entity.enums import EntityStateRole, EntityStateType, EntityStateValuefrom hi.apps.entity.models import Entityfrom hi.hi_styles import StatusStyle@@ -28,6 +30,42 @@ from .enums import EntityDisplayCategoryfrom .status_data import EntityStateStatusData, EntityStatusData+@dataclass(frozen=True)+class StateValueEntry:+ """A single converted entry from the recent state-value cache —+ a display-ready label paired with the timestamp the value was+ recorded. The label has already been through the same+ ``ConsoleConverterHelper`` pipeline as ``latest_display_label``,+ so templates render entries with the user's preferred unit+ without per-entry conversion logic."""+ display_label : str+ timestamp : datetime+++@dataclass(frozen=True)+class RecentStateValueSummary:+ """Cached recent state-value history for a single EntityState,+ surfaced to panel templates. The list is ``SensorResponseManager``'s+ in-cache window (up to 5 entries, newest-first, already deduped+ by value change), with each value converted to its display form.++ Bounded by cache size and cache lifetime: a non-empty summary+ represents only what is currently cached, not a claim about+ full history. Panels that need "no events in window" semantics+ should phrase UI accordingly — the framework makes no+ completeness claims and does not query the DB."""++ entries : List[ StateValueEntry ]++ @property+ def latest(self) -> Optional[ StateValueEntry ]:+ return self.entries[0] if self.entries else None++ @property+ def penultimate(self) -> Optional[ StateValueEntry ]:+ return self.entries[1] if len( self.entries ) > 1 else None++class EntityStateDisplayData:RECENT_MOVEMENT_THRESHOLD_SECS = 90@@ -158,8 +196,43 @@ class EntityStateDisplayData:magnitude+unit form (``"72.0°F"``); other values resolvethrough ``EntityStateValue.to_display_label`` (enum label,humanized free-form, or numeric pass-through)."""- combined = str( self.latest_display_value )- return EntityStateValue.to_display_label( combined )+ return self._display_label_for_display_value( self.latest_display_value )++ def _display_label_for_value(self, sensor_value) -> str:+ """Convert one raw sensor value into its display label via+ the same pipeline as ``latest_display_label``. Shared so+ per-entry conversion in ``recent_state_value_summary``+ produces labels indistinguishable from the latest-only+ path."""+ display_value = ConsoleConverterHelper.from_entity_state_value(+ entity_state_value = sensor_value,+ entity_state = self._entity_state,+ )+ return self._display_label_for_display_value( display_value )++ @staticmethod+ def _display_label_for_display_value(display_value: DisplayValue) -> str:+ return EntityStateValue.to_display_label( str( display_value ) )++ @cached_property+ def recent_state_value_summary(self) -> Optional[ RecentStateValueSummary ]:+ """Cached recent state-value history (up to 5 entries,+ newest-first), each converted to its display label. Returns+ ``None`` when the sensor response cache is empty. See+ ``RecentStateValueSummary`` for the contract — the framework+ makes no claims about completeness, no DB query is performed,+ and these values are not included in the polling-update+ payload (panels see them only at server-side render)."""+ if not self._sensor_response_list:+ return None+ entries = [+ StateValueEntry(+ display_label = self._display_label_for_value( r.value ),+ timestamp = r.timestamp,+ )+ for r in self._sensor_response_list+ ]+ return RecentStateValueSummary( entries = entries )def to_polling_update_dict(self) -> dict:"""Build the per-EntityState row of ``entityStateStatusMap``.@@ -279,6 +352,9 @@ class EntityStateDisplayData:if self.entity_state.entity_state_type == EntityStateType.GAS:return self._get_gas_status_style()+ if self.entity_state.entity_state_type == EntityStateType.BATTERY_LEVEL:+ return self._get_battery_level_status_style()+# TODO: These should map the latest value into a continuous range of colors/opacity## EntityStateType.AIR_PRESSURE@@ -450,6 +526,21 @@ class EntityStateDisplayData:if self.latest_sensor_value == str(EntityStateValue.LOW):return StatusStyle.Lowreturn None++ # Battery percentages below this threshold are flagged ``low``;+ # otherwise ``ok``. The token surfaces via the standard polling+ # pipeline so any panel that opts in via ``data-status`` on a+ # battery-bound element can react with CSS rules.+ BATTERY_LOW_THRESHOLD_PCT = 20++ def _get_battery_level_status_style( self ):+ try:+ magnitude = float( self.latest_sensor_value )+ except (TypeError, ValueError):+ return StatusStyle.BatteryOk+ if magnitude < self.BATTERY_LOW_THRESHOLD_PCT:+ return StatusStyle.BatteryLow+ return StatusStyle.BatteryOk@@ -469,13 +560,12 @@ class EntityDisplayData:)def __post_init__(self):- # Each contained state's ``EntityStateDisplayData`` is built- # exactly once here. ``state_status_data_list`` and- # ``state_status_data_by_role`` below both project from this- # map, so the per-state construction cost (the- # ConsoleConverterHelper lookup and the _get_svg_status_style- # dispatch) is paid once per render even when both projections- # are accessed (the typical ``to_template_context()`` path).+ # Build each contained state's ``EntityStateDisplayData`` exactly+ # once. ``state_status_data_list`` and ``state_status_data_by_role``+ # below both project from this map, so the per-state construction+ # cost (the ConsoleConverterHelper lookup and the+ # _get_svg_status_style dispatch) is paid once per render even+ # when both projections are accessed.self.state_display_data_map = {d.entity_state.id: EntityStateDisplayData( d )for d in self.entity_status_data.entity_state_status_data_list@@ -512,6 +602,29 @@ class EntityDisplayData:)return [ self.state_display_data_map[ d.entity_state.id ] for d in ordered_raw ]+ @property+ def present_roles(self) -> Set[EntityStateRole]:+ return {+ d.entity_state.entity_state_role+ for d in self.entity_status_data.entity_state_status_data_list+ }++ def filter_to_roles( self, declared_roles: Set[EntityStateRole] ):+ """Project ``state_status_data_list`` and ``state_status_data_by_role``+ down to states whose role is in ``declared_roles``. Returns a tuple+ ``(state_list, by_role_dict)`` — the same shapes the unfiltered+ properties expose, just filtered."""+ state_list = [+ d for d in self.state_status_data_list+ if d.entity_state.entity_state_role in declared_roles+ ]+ by_role = {+ name: data+ for name, data in self.state_status_data_by_role.items()+ if data.entity_state.entity_state_role in declared_roles+ }+ return state_list, by_role+@propertydef state_status_data_by_role(self) -> Dict[str, 'EntityStateDisplayData']:"""Role-keyed lookup for panel templates that pull a@@ -524,13 +637,3 @@ class EntityDisplayData:for d in self.entity_status_data.entity_state_status_data_list}- def to_template_context(self) -> Dict:- return {- 'entity': self.entity,- 'entity_status_data': self,- 'state_status_data_list': self.state_status_data_list,- 'state_status_data_by_role': self.state_status_data_by_role,- 'entity_for_video': self.entity_for_video,- 'display_only_svg_icon_item': self.display_only_svg_icon_item,- 'display_category': self.display_category,- }diff --git a/src/hi/apps/monitor/tests/test_status_data.py b/src/hi/apps/monitor/tests/test_status_data.pyindex 5d765f5f..9bcd793e 100644--- a/src/hi/apps/monitor/tests/test_status_data.py+++ b/src/hi/apps/monitor/tests/test_status_data.py@@ -128,10 +128,10 @@ class TestEntityStateStatusData(BaseTestCase):class TestEntityStatusData(BaseTestCase):- def test_template_context_includes_all_required_display_data(self):- """``EntityDisplayData.to_template_context`` provides the keys- templates rely on for rendering, with the per-state list- wrapped in display-ready ``EntityStateDisplayData`` items."""+ def test_display_data_exposes_per_state_projections(self):+ """``EntityDisplayData`` wraps the raw status data with a+ display-ordered per-state list and a role-keyed map; both are+ the entry points templates use to find state-specific data."""entity = Entity.objects.create(name='Display Entity',entity_type_str='CAMERA',@@ -158,11 +158,10 @@ class TestEntityStatusData(BaseTestCase):],)display_data = EntityDisplayData(entity_status_data=status_data)- context = display_data.to_template_context()- self.assertIn('entity', context)- self.assertIn('state_status_data_list', context)- self.assertEqual(context['entity'], entity)- self.assertEqual(len(context['state_status_data_list']), 2)+ self.assertEqual(display_data.entity, entity)+ self.assertEqual(len(display_data.state_status_data_list), 2)+ self.assertEqual(set(display_data.state_status_data_by_role.keys()),+ {'on_off', 'movement'})def test_entity_status_data_supports_optional_display_icon(self):"""Test entity status data with optional SVG icon for display."""@@ -200,10 +199,10 @@ class TestEntityStatusData(BaseTestCase):self.assertEqual(len(status_data.entity_state_status_data_list), 0)self.assertIsNone(status_data.display_only_svg_icon_item)- # Template context should still be valid (via display wrapper)- context = EntityDisplayData(entity_status_data=status_data).to_template_context()- self.assertEqual(context['entity'], entity)- self.assertEqual(len(context['state_status_data_list']), 0)+ # Display wrapper still exposes the entity and an empty state list.+ display_data = EntityDisplayData(entity_status_data=status_data)+ self.assertEqual(display_data.entity, entity)+ self.assertEqual(len(display_data.state_status_data_list), 0)def test_entity_status_data_aggregates_multiple_state_types(self):"""Test entity status data aggregation across different state types."""@@ -303,7 +302,7 @@ class TestStateStatusDataByRole(BaseTestCase):display_data = EntityDisplayData(entity_status_data=status_data)self.assertEqual(display_data.state_status_data_by_role, {})- def test_template_context_includes_by_role_map(self):+ def test_by_role_map_is_dict(self):entity = Entity.objects.create(name='Ctx Test', entity_type_str='OTHER',)@@ -311,5 +310,4 @@ class TestStateStatusDataByRole(BaseTestCase):entity=entity, entity_state_status_data_list=[],)display_data = EntityDisplayData(entity_status_data=status_data)- context = display_data.to_template_context()- self.assertIn('state_status_data_by_role', context)+ self.assertIsInstance(display_data.state_status_data_by_role, dict)diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.pyindex 5f4ba921..4544a257 100644--- a/src/hi/apps/monitor/tests/test_status_display_data.py+++ b/src/hi/apps/monitor/tests/test_status_display_data.py@@ -2,10 +2,15 @@ import loggingfrom datetime import datetime, timedeltafrom unittest.mock import Mock, patch+import hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.entity.enums import EntityStateValuefrom hi.apps.sense.transient_models import SensorResponse-from hi.apps.monitor.display_data import EntityStateDisplayData+from hi.apps.monitor.display_data import (+ EntityStateDisplayData,+ RecentStateValueSummary,+ StateValueEntry,+)from hi.apps.monitor.status_data import EntityStateStatusDatafrom hi.hi_styles import StatusStylefrom hi.testing.base_test_case import BaseTestCase@@ -686,6 +691,147 @@ class TestLatestDisplayLabel(BaseTestCase):self.assertEqual( display_data.latest_display_label, '' )+class TestRecentStateValueSummary(BaseTestCase):+ """``recent_state_value_summary`` exposes the cached+ SensorResponse list (already deduped by value change in+ ``SensorResponseManager``) as a display-ready structure. Each+ entry's label flows through the same conversion pipeline as+ ``latest_display_label``; the framework adds no completeness+ claims and does not query the DB."""++ def setUp(self):+ super().setUp()+ self.entity = Entity.objects.create(+ name='Test Entity',+ entity_type_str='SENSOR',+ )++ def _make_display_data(self, entity_state_type_str, value_timestamp_pairs,+ units=None):+ entity_state = EntityState.objects.create(+ entity = self.entity,+ entity_state_type_str = entity_state_type_str,+ units = units,+ )+ responses = []+ for value, ts in value_timestamp_pairs:+ response = Mock(spec=SensorResponse)+ response.value = value+ response.timestamp = ts+ responses.append( response )+ status_data = EntityStateStatusData(+ entity_state = entity_state,+ sensor_response_list = responses,+ controller_data_list = [],+ )+ return EntityStateDisplayData( status_data )++ def test_empty_sensor_response_list_returns_none(self):+ # No cached responses (fresh install, cache cleared, sensor+ # never reported) → caller distinguishes "nothing to show"+ # from a populated-but-old summary without inspecting list+ # length.+ display_data = self._make_display_data( 'MOVEMENT', [] )+ self.assertIsNone( display_data.recent_state_value_summary )++ def test_single_entry_populates_latest_only(self):+ now = datetime.now()+ display_data = self._make_display_data(+ 'SMOKE', [ ( str(EntityStateValue.SMOKE_DETECTED), now ) ],+ )+ summary = display_data.recent_state_value_summary+ self.assertIsInstance( summary, RecentStateValueSummary )+ self.assertEqual( len( summary.entries ), 1 )+ self.assertIsNotNone( summary.latest )+ self.assertIsNone( summary.penultimate )+ self.assertEqual( summary.latest.timestamp, now )++ def test_multi_entry_preserves_newest_first_order(self):+ # SensorResponseManager already LPUSHes newest-first; the+ # summary preserves that order so ``latest`` is index [0]+ # and ``penultimate`` is index [1]. Timestamps are+ # timezone-aware because EntityStateDisplayData's status-style+ # computation subtracts against ``datetimeproxy.now()``.+ now = datetimeproxy.now()+ earlier = now - timedelta( minutes = 14 )+ oldest = now - timedelta( hours = 2 )+ display_data = self._make_display_data(+ 'SMOKE',+ [+ ( str(EntityStateValue.OFF), now ),+ ( str(EntityStateValue.SMOKE_DETECTED), earlier ),+ ( str(EntityStateValue.OFF), oldest ),+ ],+ )+ summary = display_data.recent_state_value_summary+ self.assertEqual( len( summary.entries ), 3 )+ self.assertEqual( summary.latest.timestamp, now )+ self.assertEqual( summary.penultimate.timestamp, earlier )+ self.assertEqual( summary.entries[2].timestamp, oldest )++ def test_entry_label_matches_latest_display_label_for_enum(self):+ # Per-entry conversion must produce identical labels to the+ # single-entry path so panels render history rows that look+ # like the current value (just at different timestamps).+ display_data = self._make_display_data(+ 'SMOKE',+ [ ( str(EntityStateValue.SMOKE_DETECTED), datetime.now() ) ],+ )+ summary = display_data.recent_state_value_summary+ self.assertEqual(+ summary.latest.display_label,+ display_data.latest_display_label,+ )+ self.assertEqual( summary.latest.display_label, 'Smoke Detected' )++ def test_entry_label_applies_unit_conversion(self):+ # A unit-bearing state's history must convert each cached+ # raw value through the same display-unit translation as+ # the current value; otherwise temperature history would+ # show stored °C while the headline number is °F.+ now = datetime.now()+ display_data = self._make_display_data(+ 'TEMPERATURE',+ [ ( '22', now ), ( '21', now - timedelta( minutes = 5 ) ) ],+ units = '°C',+ )+ summary = display_data.recent_state_value_summary+ for entry in summary.entries:+ self.assertTrue(+ '°F' in entry.display_label or '°C' in entry.display_label,+ f'expected temperature unit symbol in entry label,'+ f' got {entry.display_label!r}',+ )+ # Latest entry must equal the latest_display_label so panels+ # that show both the headline and the history don't disagree.+ self.assertEqual(+ summary.latest.display_label,+ display_data.latest_display_label,+ )++ def test_summary_is_memoized(self):+ # ``cached_property`` semantics: repeated access returns the+ # same object so panels touching the summary multiple times+ # (e.g. once for latest, once for penultimate) don't pay the+ # per-entry conversion cost on each access.+ display_data = self._make_display_data(+ 'SMOKE',+ [ ( str(EntityStateValue.SMOKE_DETECTED), datetime.now() ) ],+ )+ first = display_data.recent_state_value_summary+ second = display_data.recent_state_value_summary+ self.assertIs( first, second )++ def test_state_value_entry_is_immutable_dataclass(self):+ # Frozen dataclass: panels can't mutate per-entry fields+ # mid-render. Documents the immutability contract.+ entry = StateValueEntry(+ display_label = 'x', timestamp = datetime.now(),+ )+ with self.assertRaises( Exception ):+ entry.display_label = 'y'++class TestToPollingUpdateDict(BaseTestCase):"""``to_polling_update_dict`` builds the per-EntityState row ofthe unified ``entityStateStatusMap``. Pins the contract fordiff --git a/src/hi/hi_styles.py b/src/hi/hi_styles.pyindex 71cb69c6..2a119456 100644--- a/src/hi/hi_styles.py+++ b/src/hi/hi_styles.py@@ -719,6 +719,22 @@ class StatusStyle:fill_color = STATUS_BAD_COLOR,fill_opacity = 0.5,)+ BatteryLow = SvgStatusStyle(+ status_value = 'low',+ stroke_color = STATUS_BAD_COLOR,+ stroke_width = DEFAULT_STROKE_WIDTH,+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,+ fill_color = STATUS_BAD_COLOR,+ fill_opacity = 0.5,+ )+ BatteryOk = SvgStatusStyle(+ status_value = 'ok',+ stroke_color = STATUS_OK_COLOR,+ stroke_width = DEFAULT_STROKE_WIDTH,+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,+ fill_color = STATUS_OK_COLOR,+ fill_opacity = 0.15,+ )@classmethoddef default( cls, status_value : str = DEFAULT_STATUS_VALUE ):diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex 42b396f6..58925a25 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -100,6 +100,7 @@ from hi.simulator.services.hass.sim_models import (HassPresenceSensorFields,HassSmartBulbFields,HassSmokeDetectorFields,+ HassSmokeDetectorWithBatteryFields,HassSwitchFields,HassWaterLeakSensorFields,HassWeatherStationFields,@@ -387,6 +388,7 @@ class Command(BaseCommand):self._add_hass_door_contact( profile, 'Zoo Door Contact' )self._add_hass_window_contact( profile, 'Zoo Window Contact' )self._add_hass_smoke_detector( profile, 'Zoo Smoke Detector' )+ self._add_hass_smoke_detector_with_battery( profile, 'Zoo Smoke Detector (Battery)' )self._add_hass_carbon_monoxide_detector( profile, 'Zoo CO Detector' )self._add_hass_gas_detector( profile, 'Zoo Gas Detector' )self._add_hass_temperature_sensor( profile, 'Zoo Thermometer' )@@ -566,6 +568,15 @@ class Command(BaseCommand):fields_kwargs = {'name': name},)+ def _add_hass_smoke_detector_with_battery(self, profile, name):+ self._create_db_entity(+ profile = profile,+ simulator_id = 'hass',+ fields_class = HassSmokeDetectorWithBatteryFields,+ sim_entity_type = SimEntityType.SMOKE_DETECTOR,+ fields_kwargs = {'name': name},+ )+def _add_hass_carbon_monoxide_detector(self, profile, name):self._create_db_entity(profile = profile,diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.pyindex 3df0db07..0acf5a89 100644--- a/src/hi/simulator/services/hass/sim_models.py+++ b/src/hi/simulator/services/hass/sim_models.py@@ -828,6 +828,81 @@ class HassSmokeDetectorState( HassState ):}+@dataclass( frozen = True )+class HassSmokeDetectorWithBatteryFields( SimEntityFields ):+ """Smoke detector that also reports a battery percentage —+ common shape for battery-powered Zigbee / Z-Wave smoke alarms."""+ pass+++@dataclass+class HassSmokeDetectorWithBatterySmokeState( HassState ):+ sim_entity_fields : HassSmokeDetectorWithBatteryFields+ sim_state_type : SimStateType = SimStateType.ON_OFF+ sim_state_id : str = 'smoke'+ value : str = 'off'++ @property+ def name(self):+ return f'{self.entity_name} Smoke'++ @property+ def entity_id(self):+ return _binary_sensor_entity_id( self.entity_name )++ @property+ def state(self):+ return 'on' if str_to_bool( self.value ) else 'off'++ @property+ def attributes(self) -> Dict[ str, str ]:+ return {+ 'device_class': 'smoke',+ 'friendly_name': self.entity_name,+ 'icon': 'mdi:smoke-detector',+ }+++@dataclass+class HassSmokeDetectorWithBatteryBatteryState( HassState ):+ sim_entity_fields : HassSmokeDetectorWithBatteryFields+ sim_state_type : SimStateType = SimStateType.CONTINUOUS+ sim_state_id : str = 'battery'+ value : str = '85'++ @property+ def name(self):+ return f'{self.entity_name} Battery'++ @property+ def entity_id(self):+ return _sensor_entity_id( self.entity_name, suffix = '_battery' )++ @property+ def state(self):+ return self.value++ @property+ def attributes(self) -> Dict[ str, str ]:+ return {+ 'device_class' : 'battery',+ 'friendly_name' : f'{self.entity_name} Battery',+ 'unit_of_measurement': '%',+ }++ @property+ def min_value(self):+ return 0++ @property+ def max_value(self):+ return 100++ @property+ def display_unit(self) -> str:+ return '%'++@dataclass( frozen = True )class HassCarbonMonoxideDetectorFields( SimEntityFields ):"""A carbon monoxide detector (``binary_sensor`` with@@ -3088,6 +3163,15 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [HassSmokeDetectorState,],),+ SimEntityDefinition(+ class_label = 'Smoke Detector (smoke + battery)',+ sim_entity_type = SimEntityType.SMOKE_DETECTOR,+ sim_entity_fields_class = HassSmokeDetectorWithBatteryFields,+ sim_state_class_list = [+ HassSmokeDetectorWithBatterySmokeState,+ HassSmokeDetectorWithBatteryBatteryState,+ ],+ ),SimEntityDefinition(class_label = 'Carbon Monoxide Detector',sim_entity_type = SimEntityType.CARBON_MONOXIDE_DETECTOR,diff --git a/src/hi/static/js/entity_state_status.js b/src/hi/static/js/entity_state_status.jsindex 8dbdbe2b..6fa1319e 100644--- a/src/hi/static/js/entity_state_status.js+++ b/src/hi/static/js/entity_state_status.js@@ -31,7 +31,7 @@* self-describing, so authors place the markers on whichever* element they want updated.*- * After the universal apply pass, registered EntityStatusPanel+ * After the universal apply pass, registered EntityStatePanel* handlers run. Panels that need behavior beyond what the universal* dispatcher handles (e.g., a thermostat dial whose SVG marker* angles are computed from numeric values) register a handler via@@ -46,7 +46,7 @@window.Hi = window.Hi || {};Hi.entityStateStatus = Hi.entityStateStatus || {};- // EntityStatusPanel JS that wants to react to polling updates+ // EntityStatePanel JS that wants to react to polling updates// beyond what CSS keyed on the ``status`` attribute can do// registers an update handler via ``registerUpdate``. Update// handlers receive the full statusMap keyed by state id and@@ -80,7 +80,7 @@try {handler();} catch ( e ) {- console.error( 'EntityStatusPanel init handler error:', e );+ console.error( 'EntityStatePanel init handler error:', e );}}}@@ -131,7 +131,7 @@try {handler( statusMap );} catch ( e ) {- console.error( 'EntityStatusPanel handler error:', e );+ console.error( 'EntityStatePanel handler error:', e );}}};@@ -214,7 +214,93 @@$display.text( format.replace( '{n}', slider.value ) );}+ // Generic optimistic-apply for user-driven control changes. When+ // a state-bound control changes (select / checkbox / numeric+ // input / scripted change on a hidden input), synthesize a one-+ // entry statusMap and run the universal apply. Dependent display+ // elements (``data-display-text``, ``data-display-magnitude``,+ // ``data-status``, panel-root status attr, etc.) update in lock+ // step with the user's intent, and registered update handlers+ // (dial marker positioning, panel-root ``data-hvac-mode`` sync,+ // etc.) fire immediately — the polling cycle merely confirms or+ // corrects, never drives the first-frame UI response.+ //+ // The server-bound submit path (antinode's ``onchange-async``+ // form-submit) runs independently of this handler on the same+ // ``change`` event, so error responses still surface through the+ // normal mechanism. If the server rejects the change, the next+ // polling tick overwrites the optimistic value with the canonical+ // one.+ function buildSyntheticEntry( $el ) {+ const stateId = $el.attr( 'data-state-id' );+ const tag = ( $el.prop( 'tagName' ) || '' ).toUpperCase();+ const type = ( $el.attr( 'type' ) || '' ).toLowerCase();+ let value = $el.val();+ let displayText = String( value );++ if ( tag === 'SELECT' ) {+ const $opt = $el.find( 'option:selected' );+ if ( $opt.length ) displayText = $opt.text() || displayText;+ } else if ( tag === 'INPUT' && type === 'checkbox' ) {+ const checked = $el.prop( 'checked' );+ value = checked ? ( $el.val() || 'on' ) : 'off';+ displayText = checked+ ? ( $el.attr( 'data-on-text' ) || 'On' )+ : ( $el.attr( 'data-off-text' ) || 'Off' );+ } else if ( stateId ) {+ // Numeric / hidden-input case: format the optimistic value+ // by mirroring the existing displayed text — same decimal+ // precision and same unit suffix. Heuristic, but it keeps+ // an optimistic "73.0°F" matching the canonical "72.0°F"+ // until the next polling tick reconciles. Backend authority+ // returns on every poll, so a brief divergence here is+ // self-correcting; the goal is just to avoid the visible+ // jump that happens when the optimistic value is+ // unformatted ("73") and polling replaces it with the+ // formatted version ("73.0°F").+ const $paired = $( '[data-state-id="' + stateId + '"][data-display-text]' )+ .not( $el ).first();+ if ( $paired.length ) {+ const prev = $paired.text();+ const numMatch = prev.match( /-?\d+\.?\d*/ );+ const decimalMatch = numMatch ? numMatch[ 0 ].match( /\.(\d+)$/ ) : null;+ const precision = decimalMatch ? decimalMatch[ 1 ].length : 0;+ const unitMatch = prev.match( /[^\d\s.\-+][^\d]*$/ );+ const unit = unitMatch ? unitMatch[ 0 ] : '';+ const num = parseFloat( value );+ if ( ! isNaN( num ) ) {+ displayText = num.toFixed( precision ) + unit;+ }+ }+ }++ const entry = {+ controller: { value: value },+ display: { text: displayText },+ status: String( value ).toLowerCase(),+ };+ const magnitude = parseFloat( value );+ if ( ! isNaN( magnitude ) ) {+ entry.display.magnitude = magnitude;+ }+ return entry;+ }+jQuery(function($) {+ $( document ).on(+ 'change',+ '[data-state-id][data-controller-value]',+ function() {+ const $el = $( this );+ const stateId = $el.attr( 'data-state-id' );+ if ( ! stateId ) return;+ const entry = buildSyntheticEntry( $el );+ const synthetic = {};+ synthetic[ stateId ] = entry;+ Hi.entityStateStatus.apply( synthetic );+ }+ );+// Slider drag mirror — keep the paired display in lock-step// with the thumb during user drag. ``input`` fires// continuously; ``change`` only fires on release, whichdiff --git a/src/hi/static/state_panels/camera/camera.css b/src/hi/static/state_panels/camera/camera.cssindex 71907b7f..e5e0e73c 100644--- a/src/hi/static/state_panels/camera/camera.css+++ b/src/hi/static/state_panels/camera/camera.css@@ -1,4 +1,4 @@-/* EntityStatusPanel for CAMERA entities.+/* EntityStatePanel for CAMERA entities.** All rules nested under .hi-state-panel-camera. The panel composes* existing video-stream and state-status partials; this CSS supplies@@ -124,3 +124,60 @@line-height: 1.2;text-shadow: 0 0 4px rgba(0,0,0,0.6);}++/* ============================================================== */+/* Motion chip — small status indicator overlaid on the stream */+/* corner when the camera entity carries a MOVEMENT role. Uses */+/* the framework's decay-aware status tokens so the chip color */+/* matches the rest of the app's motion treatment. */+/* ============================================================== */++.hi-state-panel-camera .stream {+ position: relative;+}+.hi-state-panel-camera .motion-chip {+ position: absolute;+ top: 8px;+ right: 8px;+ width: 36px;+ height: 36px;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(0, 0, 0, 0.55);+ color: var(--status-idle-color);+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);+ z-index: 2;+}+.hi-state-panel-camera .motion-chip svg {+ width: 65%;+ height: 65%;+}+.hi-state-panel-camera .motion-chip[status="active"] {+ background: var(--status-active-color);+ color: var(--on-status-active-color);+ animation: hi-camera-motion-pulse 1.2s ease-in-out infinite;+}+.hi-state-panel-camera .motion-chip[status="recent"] {+ background: var(--status-recent-color);+ color: var(--on-status-recent-color);+}+.hi-state-panel-camera .motion-chip[status="past"] {+ background: var(--status-past-color);+ color: var(--on-status-past-color);+}++@keyframes hi-camera-motion-pulse {+ 0%, 100% { transform: scale(1); opacity: 1; }+ 50% { transform: scale(1.12); opacity: 0.9; }+}++/* Smaller chip in compact contexts. */+.hi-state-panel-camera--list .motion-chip,+.hi-state-panel-camera--grid .motion-chip {+ width: 24px;+ height: 24px;+ top: 4px;+ right: 4px;+}diff --git a/src/hi/static/state_panels/fallback/fallback.js b/src/hi/static/state_panels/fallback/fallback.jsindex da9f91e3..f6ab1b43 100644--- a/src/hi/static/state_panels/fallback/fallback.js+++ b/src/hi/static/state_panels/fallback/fallback.js@@ -1,5 +1,5 @@/*- * Fallback EntityStatusPanel — client-side behaviors specific to+ * Fallback EntityStatePanel — client-side behaviors specific to* the flat-list rendering used when no per-EntityType panel is* registered.*diff --git a/src/hi/static/state_panels/smoke_detector/smoke_detector.css b/src/hi/static/state_panels/smoke_detector/smoke_detector.cssindex b2cb68eb..66e7902e 100644--- a/src/hi/static/state_panels/smoke_detector/smoke_detector.css+++ b/src/hi/static/state_panels/smoke_detector/smoke_detector.css@@ -1,101 +1,102 @@-/* EntityStatusPanel for SMOKE_DETECTOR entities.+/* EntityStatePanel for SMOKE_DETECTOR entities.** All rules nested under .hi-state-panel-smoke_detector so the short- * scoped class names (.icon, .label, .badge, .hero, .aux-item, etc.)- * don't leak. Variant switching is CSS-only and driven by the- * ``status`` attribute on the panel root. Two status vocabularies- * land on the root over a panel's lifetime: the raw sensor value- * (smoke_clear / smoke_detected) on initial server render, and the- * decay-aware value (idle / active / recent / past) once the first- * polling refresh lands. CSS handles both so the panel reads- * correctly at any moment.+ * scoped class names (.icon, .status-label, .badge, .hero, etc.)+ * don't leak. The panel root carries the SMOKE state's polling-+ * driven status attribute — its value is the decay-aware token+ * (``idle`` / ``active`` / ``recent`` / ``past``) at both initial+ * render and across polling refreshes, because the template seeds+ * it from ``smoke_data.svg_status_style.status_value`` and the+ * polling pipeline writes the same vocabulary. CSS keyed on the+ * single token suffices.*/:root {- --hi-smoke-clear-color: #059669;- --hi-smoke-clear-bg: rgba(5, 150, 105, 0.10);- --hi-smoke-alarm-color: #dc2626;- --hi-smoke-alarm-bg: rgba(220, 38, 38, 0.15);+ --hi-smoke-idle-color: #059669;+ --hi-smoke-idle-bg: rgba(5, 150, 105, 0.10);+ --hi-smoke-active-color: #dc2626;+ --hi-smoke-active-bg: rgba(220, 38, 38, 0.15);--hi-smoke-recent-color: #d97706;- --hi-smoke-recent-bg: rgba(217, 119, 6, 0.12);- --hi-smoke-past-color: #ca8a04;- --hi-smoke-past-bg: rgba(202, 138, 4, 0.10);+ --hi-smoke-recent-bg: rgba(217, 119, 6, 0.12);+ --hi-smoke-past-color: #6b7280;+ --hi-smoke-past-bg: rgba(107, 114, 128, 0.08);}/* ============================================================== */-/* Variant visibility: which icon and label show per status value. */+/* Badge — circular icon hero, shared across contexts. */+/* ============================================================== */++.hi-state-panel-smoke_detector .badge {+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 50%;+ flex-shrink: 0;+}+.hi-state-panel-smoke_detector .icon {+ width: 60%;+ height: 60%;+}++/* ============================================================== */+/* Per-state visibility: icon + label variants *//* ============================================================== */.hi-state-panel-smoke_detector .icon,.hi-state-panel-smoke_detector .status-label {display: none;}--.hi-state-panel-smoke_detector[status="smoke_clear"] .icon--clear,-.hi-state-panel-smoke_detector[status="idle"] .icon--clear,-.hi-state-panel-smoke_detector[status="smoke_clear"] .status-label--clear,-.hi-state-panel-smoke_detector[status="idle"] .status-label--clear {- display: inline-block;+.hi-state-panel-smoke_detector[status="idle"] .icon--idle,+.hi-state-panel-smoke_detector[status="idle"] .status-label--idle,+.hi-state-panel-smoke_detector[status="active"] .icon--active,+.hi-state-panel-smoke_detector[status="active"] .status-label--active,+.hi-state-panel-smoke_detector[status="recent"] .icon--recent,+.hi-state-panel-smoke_detector[status="recent"] .status-label--recent,+.hi-state-panel-smoke_detector[status="past"] .icon--past,+.hi-state-panel-smoke_detector[status="past"] .status-label--past {+ display: block;}-.hi-state-panel-smoke_detector[status="smoke_detected"] .icon--alarm,-.hi-state-panel-smoke_detector[status="active"] .icon--alarm,-.hi-state-panel-smoke_detector[status="smoke_detected"] .status-label--alarm,-.hi-state-panel-smoke_detector[status="active"] .status-label--alarm {- display: inline-block;-}+/* ============================================================== */+/* Per-state color tints */+/* ============================================================== */-.hi-state-panel-smoke_detector[status="recent"] .icon--recent,-.hi-state-panel-smoke_detector[status="recent"] .status-label--clear {- display: inline-block;-}+.hi-state-panel-smoke_detector[status="idle"] .badge { background: var(--hi-smoke-idle-bg); color: var(--hi-smoke-idle-color); }+.hi-state-panel-smoke_detector[status="active"] .badge { background: var(--hi-smoke-active-bg); color: var(--hi-smoke-active-color); }+.hi-state-panel-smoke_detector[status="recent"] .badge { background: var(--hi-smoke-recent-bg); color: var(--hi-smoke-recent-color); }+.hi-state-panel-smoke_detector[status="past"] .badge { background: var(--hi-smoke-past-bg); color: var(--hi-smoke-past-color); }-.hi-state-panel-smoke_detector[status="past"] .icon--past,-.hi-state-panel-smoke_detector[status="past"] .status-label--clear {- display: inline-block;-}+.hi-state-panel-smoke_detector .status-label { font-weight: 600; }+.hi-state-panel-smoke_detector[status="idle"] .status-label { color: var(--hi-smoke-idle-color); }+.hi-state-panel-smoke_detector[status="active"] .status-label { color: var(--hi-smoke-active-color); }+.hi-state-panel-smoke_detector[status="recent"] .status-label { color: var(--hi-smoke-recent-color); }+.hi-state-panel-smoke_detector[status="past"] .status-label { color: var(--hi-smoke-past-color); }/* ============================================================== */-/* Color tints — applied to badge background per status. */+/* "Triggered X ago" detail line (recent / past only). *//* ============================================================== */+/* Visibility matches the status-label variants: hidden by default */+/* and shown only when the panel root's decay-aware ``status`` */+/* attribute is ``recent`` or ``past``. Idle and active suppress */+/* — idle has nothing to say, active is "now." */-.hi-state-panel-smoke_detector .badge {- background: var(--hi-smoke-clear-bg);- color: var(--hi-smoke-clear-color);- border-radius: 50%;- display: flex;- align-items: center;- justify-content: center;- flex-shrink: 0;-}--.hi-state-panel-smoke_detector[status="smoke_detected"] .badge,-.hi-state-panel-smoke_detector[status="active"] .badge {- background: var(--hi-smoke-alarm-bg);- color: var(--hi-smoke-alarm-color);-}-.hi-state-panel-smoke_detector[status="recent"] .badge {- background: var(--hi-smoke-recent-bg);- color: var(--hi-smoke-recent-color);+.hi-state-panel-smoke_detector .last-event {+ display: none;+ color: var(--text-muted, #6c757d);}-.hi-state-panel-smoke_detector[status="past"] .badge {- background: var(--hi-smoke-past-bg);- color: var(--hi-smoke-past-color);+.hi-state-panel-smoke_detector[status="recent"] .last-event,+.hi-state-panel-smoke_detector[status="past"] .last-event {+ display: block;}-.hi-state-panel-smoke_detector .icon {- width: 60%;- height: 60%;+/* Alarm-state pulse to draw attention. */+.hi-state-panel-smoke_detector[status="active"] .icon--active {+ animation: hi-smoke-alarm-pulse 1.2s ease-in-out infinite;+}+@keyframes hi-smoke-alarm-pulse {+ 0%, 100% { transform: scale(1); opacity: 1; }+ 50% { transform: scale(1.08); opacity: 0.85; }}--/* Status label color follows visual treatment. */-.hi-state-panel-smoke_detector .status-label { font-weight: 600; }-.hi-state-panel-smoke_detector[status="smoke_clear"] .status-label,-.hi-state-panel-smoke_detector[status="idle"] .status-label { color: var(--hi-smoke-clear-color); }-.hi-state-panel-smoke_detector[status="smoke_detected"] .status-label,-.hi-state-panel-smoke_detector[status="active"] .status-label { color: var(--hi-smoke-alarm-color); }-.hi-state-panel-smoke_detector[status="recent"] .status-label { color: var(--hi-smoke-recent-color); }-.hi-state-panel-smoke_detector[status="past"] .status-label { color: var(--hi-smoke-past-color); }/* ============================================================== *//* Modal layout */@@ -114,7 +115,10 @@font-size: 22px;line-height: 1.1;}-+.hi-state-panel-smoke_detector--modal .last-event {+ font-size: 13px;+ line-height: 1.2;+}.hi-state-panel-smoke_detector--modal .auxiliary {border-top: 1px solid var(--line-color, #d0d7de);padding: 14px 20px;@@ -152,8 +156,11 @@.hi-state-panel-smoke_detector--list .entity-name {font-size: 14px; font-weight: 600; line-height: 1.2;}-.hi-state-panel-smoke_detector--list .status-line { font-size: 12px; }.hi-state-panel-smoke_detector--list .status-label { font-size: 12px; }+.hi-state-panel-smoke_detector--list .last-event {+ font-size: 11px;+ line-height: 1.2;+}.hi-state-panel-smoke_detector--list .aux-bits {font-size: 11px;color: var(--text-muted, #6c757d);@@ -168,18 +175,50 @@flex-direction: column;align-items: center;text-align: center;- padding: 8px;+ padding: 12px;gap: 6px;+ height: 100%;}-.hi-state-panel-smoke_detector--grid .badge { width: 64px; height: 64px; margin-top: 4px; }+.hi-state-panel-smoke_detector--grid .badge { width: 72px; height: 72px; margin-top: 6px; }.hi-state-panel-smoke_detector--grid .status-label { font-size: 13px; line-height: 1.1; }.hi-state-panel-smoke_detector--grid .entity-name {- font-size: 11px;+ font-size: 10px;color: var(--text-muted, #6c757d);line-height: 1.2;+ margin-top: 4px;}--.hi-state-panel-smoke_detector--grid[status="smoke_detected"],-.hi-state-panel-smoke_detector--grid[status="active"] { background: var(--hi-smoke-alarm-bg); }+.hi-state-panel-smoke_detector--grid[status="idle"] { background: var(--hi-smoke-idle-bg); }+.hi-state-panel-smoke_detector--grid[status="active"] { background: var(--hi-smoke-active-bg); }.hi-state-panel-smoke_detector--grid[status="recent"] { background: var(--hi-smoke-recent-bg); }-.hi-state-panel-smoke_detector--grid[status="past"] { background: var(--hi-smoke-past-bg); }+.hi-state-panel-smoke_detector--grid[status="past"] { background: var(--hi-smoke-past-bg); }++/* ============================================================== */+/* Battery low-state escalation. */+/* ============================================================== */+/* The polling pipeline emits ``status="low"`` on BATTERY_LEVEL */+/* elements when the value is below the framework threshold */+/* (see EntityStateDisplayData.BATTERY_LOW_THRESHOLD_PCT). The */+/* aux-value text colors red; the grid card surfaces a dedicated */+/* "Low Battery" warning only in the low state. */++.hi-state-panel-smoke_detector--modal .aux-value[status="low"] {+ color: var(--hi-smoke-active-color);+ font-weight: 600;+}+.hi-state-panel-smoke_detector--list .aux-bits span[status="low"] {+ color: var(--hi-smoke-active-color);+ font-weight: 600;+}++.hi-state-panel-smoke_detector--grid .low-battery-warning {+ display: none;+ margin-top: 6px;+ font-size: 9px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--hi-smoke-active-color);+}+.hi-state-panel-smoke_detector--grid .low-battery-warning[status="low"] {+ display: block;+}diff --git a/src/hi/static/state_panels/thermostat/thermostat.css b/src/hi/static/state_panels/thermostat/thermostat.cssindex 6907090d..85726efc 100644--- a/src/hi/static/state_panels/thermostat/thermostat.css+++ b/src/hi/static/state_panels/thermostat/thermostat.css@@ -1,4 +1,4 @@-/* EntityStatusPanel for THERMOSTAT entities.+/* EntityStatePanel for THERMOSTAT entities.** All rules nested under .hi-state-panel-thermostat. The dial's* SVG markers (setpoint, current temperature) are positioned by@@ -100,8 +100,103 @@}.hi-state-panel-thermostat--modal .dial-temp { font-size: 56px; }.hi-state-panel-thermostat--modal .dial-mode-label { margin-top: 6px; }-.hi-state-panel-thermostat--modal .states {++.hi-state-panel-thermostat--modal .thermostat-controls {+ display: flex;+ flex-direction: column;+ gap: 16px;width: 100%;+ margin-top: 4px;+}+.hi-state-panel-thermostat--modal .thermostat-setpoint-row {+ display: flex;+ justify-content: center;+ gap: 24px;+ flex-wrap: wrap;+}+.hi-state-panel-thermostat--modal .thermostat-modes-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px 16px;+}+.hi-state-panel-thermostat--modal .control-group {+ display: flex;+ flex-direction: column;+ gap: 6px;+}+.hi-state-panel-thermostat--modal .control-label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--text-muted, #6c757d);+ font-weight: 600;+}+.hi-state-panel-thermostat--modal .control-readonly {+ font-size: 14px;+ color: #1f2328;+ padding: 6px 0;+}++/* Setpoint stepper widget. */+.hi-state-panel-thermostat .setpoint-stepper-form {+ display: inline-flex;+ align-items: center;+ gap: 12px;+ margin: 0;+}+.hi-state-panel-thermostat .setpoint-stepper {+ display: inline-flex;+ align-items: center;+ gap: 12px;+}+.hi-state-panel-thermostat .stepper-btn {+ width: 32px;+ height: 32px;+ border-radius: 50%;+ border: 1px solid var(--line-color, #d0d7de);+ background: white;+ color: var(--primary-color, #177072);+ font-size: 18px;+ line-height: 1;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0;+}+.hi-state-panel-thermostat .stepper-btn:hover { background: var(--info-bg-light, #e8f4f4); }+.hi-state-panel-thermostat .stepper-btn:disabled {+ color: var(--text-muted, #6c757d);+ cursor: not-allowed;+ opacity: 0.55;+}+.hi-state-panel-thermostat .setpoint-value {+ font-size: 20px;+ font-weight: 500;+ min-width: 56px;+ text-align: center;+}+.hi-state-panel-thermostat .setpoint-value--readonly {+ font-size: 16px;+ font-weight: 400;+ text-align: left;+}++.hi-state-panel-thermostat--modal .thermostat-secondary {+ width: 100%;+ border-top: 1px solid var(--line-color, #d0d7de);+ padding-top: 12px;+ margin-top: 16px;+ display: flex;+ gap: 16px;+ font-size: 13px;+ color: var(--text-muted, #6c757d);+}+.hi-state-panel-thermostat--modal .secondary-label { color: var(--text-muted, #6c757d); }+.hi-state-panel-thermostat--modal .secondary-value {+ color: #1f2328;+ font-weight: 500;+ margin-left: 4px;}/* ============================================================== */@@ -125,6 +220,10 @@.hi-state-panel-thermostat--list .setpoint-summary {font-size: 12px; color: var(--text-muted, #6c757d); margin-top: 2px;}+.hi-state-panel-thermostat--list .setpoint-summary strong { color: #1f2328; font-weight: 500; }+.hi-state-panel-thermostat--list .humidity-line {+ font-size: 11px; color: var(--text-muted, #6c757d); margin-top: 2px;+}/* ============================================================== *//* Grid card layout — flat number, color-tinted background. */@@ -160,3 +259,40 @@}.hi-state-panel-thermostat--grid[status="heating"] .setpoint-line { color: var(--hi-thermo-heating-color); }.hi-state-panel-thermostat--grid[status="cooling"] .setpoint-line { color: var(--hi-thermo-cooling-color); }++/* ============================================================== */+/* Setpoint visibility (dual vs single). */+/* ============================================================== */+/* Driven by the live HVAC mode value. thermostat.js keeps */+/* ``data-hvac-mode`` on the panel root in sync with the polled */+/* HVAC_MODE state. Default (mode absent or any non-dual mode): */+/* hide dual markers / blocks / summaries. heat_cool / auto: show */+/* dual, hide single. Placed at end-of-file so the cascade wins */+/* against earlier .control-group / .setpoint-summary layout */+/* rules at equal specificity. */++.hi-state-panel-thermostat .dial-setpoint-marker--dual,+.hi-state-panel-thermostat .setpoint-block--dual,+.hi-state-panel-thermostat .setpoint-summary--dual {+ display: none;+}+.hi-state-panel-thermostat[data-hvac-mode="heat_cool"] .dial-setpoint-marker--dual,+.hi-state-panel-thermostat[data-hvac-mode="auto"] .dial-setpoint-marker--dual {+ display: initial;+}+.hi-state-panel-thermostat[data-hvac-mode="heat_cool"] .setpoint-block--dual,+.hi-state-panel-thermostat[data-hvac-mode="auto"] .setpoint-block--dual {+ display: flex;+}+.hi-state-panel-thermostat[data-hvac-mode="heat_cool"] .setpoint-summary--dual,+.hi-state-panel-thermostat[data-hvac-mode="auto"] .setpoint-summary--dual {+ display: inline;+}+.hi-state-panel-thermostat[data-hvac-mode="heat_cool"] .dial-setpoint-marker--single,+.hi-state-panel-thermostat[data-hvac-mode="auto"] .dial-setpoint-marker--single,+.hi-state-panel-thermostat[data-hvac-mode="heat_cool"] .setpoint-block--single,+.hi-state-panel-thermostat[data-hvac-mode="auto"] .setpoint-block--single,+.hi-state-panel-thermostat[data-hvac-mode="heat_cool"] .setpoint-summary--single,+.hi-state-panel-thermostat[data-hvac-mode="auto"] .setpoint-summary--single {+ display: none;+}diff --git a/src/hi/static/state_panels/thermostat/thermostat.js b/src/hi/static/state_panels/thermostat/thermostat.jsindex 70764466..81837fce 100644--- a/src/hi/static/state_panels/thermostat/thermostat.js+++ b/src/hi/static/state_panels/thermostat/thermostat.js@@ -1,5 +1,5 @@/*- * EntityStatusPanel JS — thermostat.+ * EntityStatePanel JS — thermostat.** The dial's setpoint marker and current-temperature marker need* SVG rotations computed from the numeric temperature magnitude.@@ -46,8 +46,17 @@}function applyAngleToMarker( $marker, tempValue ) {- const angle = temperatureToAngle( tempValue );- $marker.attr( 'transform', 'rotate(' + angle + ' 110 110)' );+ // Hide the marker when there is no numeric value yet (empty+ // ``data-temp-value`` from a sensor with no reading); otherwise+ // ``temperatureToAngle`` would clamp NaN to 0 and the marker+ // would settle at the dial's top, misleadingly.+ const value = parseFloat( tempValue );+ if ( isNaN( value ) ) {+ $marker.css( 'display', 'none' );+ return;+ }+ $marker.css( 'display', '' );+ $marker.attr( 'transform', 'rotate(' + temperatureToAngle( value ) + ' 110 110)' );}// Initial render: each marker has the numeric value baked in@@ -78,9 +87,33 @@});}+ // Keep ``data-hvac-mode`` on each thermostat panel synced with the+ // polled HVAC_MODE value, so CSS rules on the panel root can+ // switch between single and dual setpoint UI (markers + control+ // rows + summary text) when the user changes the mode.+ function applyHvacModeFromStatusMap( statusMap ) {+ $( '.hi-state-panel-thermostat[data-hvac-mode-state-id]' ).each( function() {+ const $panel = $( this );+ const stateId = $panel.attr( 'data-hvac-mode-state-id' );+ const entry = statusMap[ stateId ];+ if ( ! entry ) return;+ // Mode controllers expose their value via entry.controller.value;+ // some integrations may surface it via the display text instead.+ let value = null;+ if ( entry.controller && entry.controller.value != null ) {+ value = entry.controller.value;+ } else if ( entry.display && entry.display.text ) {+ value = entry.display.text.toLowerCase();+ }+ if ( value == null ) return;+ $panel.attr( 'data-hvac-mode', String( value ).toLowerCase() );+ });+ }+if ( window.Hi && Hi.statePanels ) {if ( typeof Hi.statePanels.registerUpdate === 'function' ) {Hi.statePanels.registerUpdate( applyMarkerAnglesFromStatusMap );+ Hi.statePanels.registerUpdate( applyHvacModeFromStatusMap );}if ( typeof Hi.statePanels.registerInit === 'function' ) {// Fires on initial page load and after each async fragment@@ -91,4 +124,55 @@}}+ // Helper: POST the controller form's value to its action URL+ // without engaging antinode's form-submit machinery (which would+ // try to replace the rendered widget with the server response+ // and produce the wrong shape for the thermostat's custom UI).+ // The unified ``Hi.entityStateStatus.apply`` path handles the UI+ // side; polling reconciles on the next tick.+ function postControllerChange( $form, value ) {+ const url = $form.attr( 'action' );+ const csrf = $form.find( 'input[name="csrfmiddlewaretoken"]' ).val();+ $.ajaxSuppressLoader = true;+ return $.post( url, {+ csrfmiddlewaretoken: csrf,+ value: value,+ }).always( function() {+ $.ajaxSuppressLoader = false;+ });+ }++ // Mode / Fan / Preset selects: plain selects with no antinode+ // hooks. The framework's unified change-listener has already+ // synthesized the status update and applied the optimistic UI+ // (including the panel-root ``data-hvac-mode`` that swaps single+ // vs dual setpoint visibility); we just push the value to the+ // server.+ $( document ).on( 'change', '.hi-state-panel-thermostat .thermostat-select', function() {+ const $select = $( this );+ const $form = $select.closest( 'form.thermostat-select-form' );+ if ( ! $form.length ) return;+ postControllerChange( $form, $select.val() );+ });++ // Setpoint stepper: bump the hidden value and let the framework's+ // unified status-apply path handle the UI (display text, dial+ // marker re-positioning, etc.). Trigger ``change`` on the input so+ // the generic optimistic-apply handler picks it up. Server POST+ // runs in parallel; polling reconciles on the next tick.+ $( document ).on( 'click', '.hi-state-panel-thermostat .stepper-btn', function( e ) {+ e.preventDefault();+ const $btn = $( this );+ const $stepper = $btn.closest( '.setpoint-stepper' );+ const $form = $stepper.find( 'form.setpoint-stepper-form' );+ if ( ! $form.length ) return;+ const $input = $form.find( 'input.setpoint-stepper-input' );+ const cur = parseFloat( $input.val() );+ const delta = parseFloat( $btn.attr( 'data-stepper-delta' ) ) || 0;+ if ( isNaN( cur ) || ! delta ) return;+ const next = cur + delta;+ $input.val( next ).trigger( 'change' );+ postControllerChange( $form, next );+ });+})();