Home Information - Your home, your data, organized.
Python
First pass at comment cleanups. Many files.
Anthony Cassandrab96bdb92dc65
diff --git a/docs/dev/shared/coding-standards.md b/docs/dev/shared/coding-standards.mdindex a9036dc0..74ca12a9 100644--- a/docs/dev/shared/coding-standards.md+++ b/docs/dev/shared/coding-standards.md@@ -13,6 +13,7 @@ Checklists for writing and reviewing code.- [ ] The file ends with a newline- [ ] All new files follow the project structure's name and location conventions.- [ ] There are no Emoji's in any code, templates or documentation.+- [ ] All comments and docstrings use ASCII only (no em/en dashes, smart quotes, arrows, degree symbols, ellipses, etc.).**Imports**:- [ ] All module imports are at the top of the file.@@ -246,6 +247,25 @@ The project uses two different flake8 configurations:- **Note**: These are deliberate choices for improved code readability, not oversights- CI Configuration (`src/.flake8-ci`): GitHub Actions enforces these standards and blocks PR merging if violations exist.+### ASCII-Only in Comments and Docstrings++Comments and docstrings use ASCII only. The benefits of visually-precise Unicode characters (em dashes, arrows, degree symbols) are outweighed by the costs: inconsistent rendering across terminals / diff viewers / editor configs; broken `grep` for anyone typing the ASCII equivalent; copy-paste mismatches between source and rendered docs; and visual ambiguity between similar-looking characters.++Common substitutions:++| Unicode | ASCII |+|---------|-------|+| `—` (em dash), `–` (en dash) | `--` or `-` |+| `→` (right arrow), `↔` (left-right arrow) | `->` or `and` |+| `…` (horizontal ellipsis) | `...` |+| `×` (multiplication sign) | `x` |+| `°` (degree symbol) | drop or restructure (e.g., `88F` instead of `88°F`) |+| `"` `"` (smart quotes), `'` `'` (smart apostrophes) | `"` `'` |++This is a syntactic concern (analogous to the no-emoji rule above) and is enforced by the comment-cleanup pass during its run.++Scope: applies to comments and docstrings. Does **not** apply to user-facing strings (`help_text`, `verbose_name`, error messages, log messages) — those follow their own UI / operator-copy conventions and may contain whatever characters their audience needs.+## CommentingThe content and semantics of comments — what to keep, rewrite, or remove — are covered in [Commenting Guidelines](commenting-guidelines.md). The checklist above covers the syntactic surface only.diff --git a/docs/dev/shared/commenting-guidelines.md b/docs/dev/shared/commenting-guidelines.mdindex 6e705339..c0799d2e 100644--- a/docs/dev/shared/commenting-guidelines.md+++ b/docs/dev/shared/commenting-guidelines.md@@ -38,6 +38,10 @@ A comment is justified when a future cold reader would be misled, confused, or sA useful comment in any of these categories is short, points at the non-obvious thing, and would still make sense to a reader who has never heard of the original problem.+### Brevity Even for Keeps++Earning a place is the first bar; earning the current *length* is the second. Many genuinely useful comments are wordier than the substance warrants — extra qualifications, restated context, parenthetical examples that no longer pull their weight. When keeping a comment, ask whether the same substance reads cleaner in half the words. Bias toward shorter even when keeping.+## When a Comment Does Not BelongRemove comments that fall into any of these categories. These are the patterns observed most often.@@ -47,6 +51,7 @@ Remove comments that fall into any of these categories. These are the patterns o- Docstrings that restate the method name and parameter types in prose.- Inline comments that describe *what* the next line does when the line itself says it.- Comments on conditionals, loops, or assignments that add no information beyond the expression.+- **Section labels and step markers** (`# Get the X`, `# Remove the Y`, `# Stage 1: …`, `# Discover Z by scanning W`) when the next 2-3 lines have well-named variables performing exactly what the label claims. Factory-method docstrings like `"""Create a successful result."""` for `success()` are the same anti-pattern. This rule applies to languages with structural grouping (Python, JavaScript). For CSS and other languages without native grouping, see [Per-Language Notes](#per-language-notes).### Information a reader can trivially discover- Argument types and return types already in the signature.@@ -62,11 +67,21 @@ Remove comments that fall into any of these categories. These are the patterns oThese narrate the path to the current code. The reader only needs the current code.+### Forward-looking placeholders and hedges+The mirror of archeology — comments that look forward to changes that may or may not happen. They add no information for the cold reader (any code can be changed later; that's the default).+- `(as of yet)` / `(for now)` / `today` / `currently` / `in the future` / `eventually`.+- "The proper fix is X; deferred because Y" (aspirational alternative designs).+- "Each entry is a small dict so additional metadata can be added later without changing the API surface" (extension-point speculation).+- "deferred to the broader X redesign" (deferral language).++When the substance is genuinely useful — for example, "this is a workaround, not the canonical pattern" — keep that signal but drop the speculation about what the canonical pattern would be.+### Session, PR, or work-stream context- "Phase 3 / Phase 4" references.- "Added in this PR / removed in this PR."- Comments explaining why other code was deleted, moved, or refactored.- Anything that reads like a debugging conversation, status update, or progress note.+- **Issue number references** (`(Issue #281)`, `(#263)`, `Per issue #N`, `Issue #283 sync-check probe`). GitHub holds the historical record; the docstring is the future contract. The issue number is workflow metadata, not code documentation.These have a half-life measured in days. They become noise immediately after merge.@@ -76,6 +91,19 @@ When a change spans many files, there is a temptation to drop a paragraph about### Comments that describe the caller, not the calleeA method's comment should describe what the method does and the contract it offers, not how a specific caller happens to use it. Caller-specific context lives at the call site (or, better, in the call-site code itself).+Common sub-patterns to delete on sight:+- **Caller-name lists**: `"Used by DELETE SAFE on disable and by sync-time refresh removals"`, `"Used by Disable-ALL and as a backstop"`. The list rots whenever a caller is renamed, added, or removed.+- **"for use from X" tails**: `"Async variant of get_entry for use from async monitor / converter paths"` — the `async def` already says "from async contexts"; the specific caller-class enumeration adds nothing.+- **Sibling cross-references**: `"Parallel to get_connector() and get_importer()"` once a reader has scanned the three methods, the parallelism is self-evident. The reference adds maintenance burden without information.++### UI element name-dropping in backend code+Backend comments and docstrings that quote specific UI element labels rot the moment the UI changes — and UI copy changes far more often than the backend code that supports it. Examples seen in practice:+- Button labels: `"REFINE button"`, `"APPLY"`, `"NOT NOW"`, `"GO BACK"`.+- Tile / section / badge names: `"'Detached' tile"`, `"From X UI badge"`, `"Content Sources header"`.+- Modal section references: `"the collapsed Details section"`, `"the sidebar Cameras list"`.++When the backend genuinely needs to mention UI behavior, describe it functionally: "the operator-visible summary", "the details view", "the dismiss action" — not by the current UI label. View-layer files are the hot spot for this pattern; treat them with extra scrutiny.+### Implementation details that belong somewhere else- Details about a collaborator's internals showing up at a usage point.- Details about a caller's flow showing up inside the callee.@@ -105,6 +133,16 @@ Treat the following phrasings as strong signals that the comment is narrating hi- "Without this, …" / "Otherwise …" (when describing the bug it would cause, not the invariant it maintains)- "Phase N" / "Step N of the migration" / "TODO from issue #…"- "Added for X" / "Per the discussion in…" / "Per request from…"+- "(Issue #N)" / "(#N)" / "Per issue #N" — workflow-tracker references; same delete signal.++## Forward-Looking Smells — Phrasings That Signal a Delete++Parallel to the archeology smells but pointing the other direction. Default to deletion unless the substance is clearly load-bearing:++- "(as of yet)" / "(for now)" / "today" / "currently" / "in the future" / "eventually"+- "The proper fix is…" / "deferred because…" / "deferred to the broader X redesign"+- "future call sites that…" / "callers may eventually need…" / "extension point for…"+- "Future:" / "TODO: maybe…" / vague placeholders for not-yet-real features.## Docstrings@@ -128,6 +166,7 @@ When reviewing comments on a branch or in a directory, decide per comment:- The substance is load-bearing but the framing is archeological (narrates the change rather than stating the invariant). Rewrite to state the invariant directly, without reference to what came before.- The comment is correct but verbose or scattered across multiple lines that could be one.- The comment mixes a useful note with debugging narrative — keep the note, drop the narrative.+- **Preserve bracing/warning framing.** When a comment's job is "your default mental model is wrong, brace yourself" (e.g., `"""Counterintuitive: Django's ready() does not behave the way the docs suggest..."""`), the warning role itself is load-bearing. Don't dissolve the bracing into distributed facts — keep the explicit "be surprised here" signal.### Remove- Restates the code, the name, or the type.@@ -135,6 +174,7 @@ When reviewing comments on a branch or in a directory, decide per comment:- Re-explains an architectural fact already stated elsewhere.- Is a stale maintenance liability (file:line refs, name quotes, counts).- Is commented-out code or a vague TODO.+- **Flatten module-vs-class docstring duplication.** When a module docstring and a class docstring in the same file repeat the same content, keep what's unique at each level. The module docstring is the right home for cross-class wire formats and inter-class contracts; the class docstring is the right home for the class's own scope and invariants.### When Unsure — Keep and Flag@@ -145,6 +185,66 @@ Removing a *bad* comment is free. Removing a *load-bearing* comment is expensiveA cleanup pass that errs toward keeping ambiguous comments is correct. A cleanup pass that silently deletes load-bearing context is a regression.+### Authoring Boundary — Edit, Don't Author++The cleanup pass reviews and edits *existing* comments. It does not author new ones — even when a file would clearly benefit from a comment that isn't there (a missing Context block in a template, a missing docstring on a public method, a missing invariant note next to a non-obvious guard).++Identifying these gaps is valuable but is a separate authoring task with different inputs (design intent, contract knowledge) than what the cleanup pass operates on. Surface the gap as a flagged observation if useful; do not silently fill it.++### Substance-at-Wrong-Location — Stay Myopic++A comment may describe semantics owned by another module — for example, an enum docstring that explains the implementation's behavior rather than just naming the choice. The cleanup pass is myopic by design: it does **not** cross files to verify whether the substance exists at its canonical location.++The rule:+- If the comment looks load-bearing reading just this file, **KEEP and FLAG**.+- If it is obviously redundant given the code in this file, REMOVE.+- The cleanup pass does not perform cross-file substance reconciliation.++If a removed (or flagged) comment turns out to have been the only documentation of a piece of substance, that is a pre-existing codebase gap that the cleanup *surfaced*, not one it created. The remediation is a separate piece of work (move the substance to its canonical location), not a reason to retain a misplaced comment.++### Comment-vs-Code Drift — Fix If Local, Flag If Cross-File++When a comment references a name (API hook, method, constant, file path) that no longer matches the code, OR when two comments in the same file disagree, the cleanup pass acts based on where the corrective evidence lives:++- **If the same file makes the canonical name obvious** — the actual code in this file uses the canonical name, or another comment in agreement with the code does — **fix** the drifted comment to match.+- **If determining the canonical name requires reading other files, library docs, or guessing**, **flag** the inconsistency. Picking the wrong side silently is a worse outcome than flagging.++The agent does not go off on cross-file explorations to resolve a drift. The same myopia principle as Substance-at-Wrong-Location: the evidence available in the file under review is the only evidence the cleanup pass uses.++In both cases — fix or flag — leaving the inconsistency in place is the wrong outcome.++## Per-Language Notes++Some languages and formats lack the structural features that Python and JavaScript provide (type signatures, class/function nesting, etc.). When a general rule depends on a missing feature, the rule shifts. The exceptions below are not free passes — they apply only when the cited structural gap is real.++### Templates (Django)++Django templates have no type signatures, which shifts how some general rules apply.++**Context contract blocks are keep-worthy.** A top-of-file block listing the template's context variables and their types — for example:++```django+{% comment %}+Context:+ health_status : HealthStatus (optional)+ integration_data : IntegrationData (required)+{% endcomment %}+```++— is keep-worthy in a way that a Python function's parameter-listing docstring is not. Python has type hints; templates have nothing equivalent. The Context block is the closest thing to a signature, and serves the same purpose: telling a caller (or reader) what to pass in. Preserve these blocks even when they look long, but strip the surrounding caller-naming (which caller passes what is the caller's concern, not the template's).++**UI labels that the template itself renders are not pattern #4 violations.** The "UI element name-dropping in backend code" rule targets backend comments that quote UI labels living elsewhere — those references rot when the UI changes. A template that *renders* a button labeled `UPDATE` and refers to "UPDATE" in its top comment is a different case: the label and the comment about it live in the same file and change together. The cleanup pass can leave these in place. Backend code that references the same `UPDATE` button by name is still pattern #4 — the rule applies to cross-file references, not local self-reference.++### CSS++CSS has no nesting, no module system, and no function/class structure. Section labels are the only grouping construct the language offers.++**Section labels — banner-style or single-line — are keep-worthy.** Both visually-prominent dividers (`/* ==== SECRET FIELD STYLING ==== */`) and short single-line labels above clusters of related rules (`/* Action Bar */`, `/* Drag and Drop Styling */`) serve as the file's only navigation aid. The pattern "section labels restating well-named code" applies far less strictly to CSS than to languages with structural grouping. The bar for removing a CSS section label is high: only remove it when the label adds *zero* information and the next rule's class names are completely self-explanatory.++**UI labels in CSS comments follow the same rule as templates.** When a rule styles a button labeled `UPDATE` and the comment mentions `UPDATE`, the label and the rule live and change together. Pattern #4 does not apply within the file that *implements* the UI element.++**Inline trailing comments on property values are useful and should be kept** when they explain a magic value (`min-height: 44px; /* Touch-friendly minimum */`), a behavioral choice (`flex-shrink: 0; /* Don't shrink button */`), or a browser-compat reason (`border-width: 0.5px; /* Sharper on retina */`). They are pure WHY at the most precise location.+## What Is Out of Scope for the Cleanup PassThe cleanup pass is about **content and semantics**. The following are syntactic concerns that belong to general code review and to [Coding Standards](coding-standards.md):@@ -154,3 +254,18 @@ The cleanup pass is about **content and semantics**. The following are syntactic- Where in a file comments are placed.The cleanup pass should not rewrite a comment purely for syntactic reasons. If a comment's *content* earns its place, leave its form alone.++### User-Facing Strings — Hard Constraint++The cleanup pass does **not** touch strings whose audience is anyone other than a future developer reading the code. These are functional UI / operator copy with a different audience and a different review process:++- Django field metadata: `help_text`, `verbose_name`, `verbose_name_plural`, `choices` labels.+- Error messages displayed to operators (raised exceptions intended to surface in UI, form errors).+- Log messages intended for operators or for downstream log analysis.+- Any string that is rendered in a UI, sent in an email, written to a user-visible report, etc.++These strings may contain content that would otherwise match remove-on-sight patterns (specific UI references, integration names, example values). The audience justifies them; leave them alone. If in doubt about whether a string is user-facing, leave it.++### ASCII Normalization++The cleanup pass also normalizes non-ASCII characters in comments and docstrings to ASCII equivalents per [Coding Standards](coding-standards.md). This is a syntactic concern but is applied during the cleanup pass for convenience. Common substitutions: `—` / `–` → `--`, `→` → `->`, `…` → `...`, `×` → `x`, `°` → drop or restructure.diff --git a/src/hi/apps/monitor/apps.py b/src/hi/apps/monitor/apps.pyindex 842fe0c9..e910ac76 100644--- a/src/hi/apps/monitor/apps.py+++ b/src/hi/apps/monitor/apps.py@@ -10,17 +10,21 @@ class MonitorConfig(AppConfig):def ready(self):from hi.background_tasks import HiBackgroundTaskHelper- # Notes:- # - This method does not run in a production-like environment using gunicorn.- # - When it is called, it is often called multiple times during Django initialization.- # - Django seem to be suing different processes on each invocation.+ # Counterintuitive: Django's AppConfig.ready() does not behave the way+ # the docs suggest. The two surprises that drive the guards below:+ #+ # 1. Under runserver, Django itself spawns multiple processes during+ # initialization — not because workers are configured, but as part+ # of normal startup — and ready() runs in each one. RUN_MAIN is set+ # only in the worker that serves requests; the other invocations+ # must bail out to avoid duplicate startup.+ #+ # 2. Under gunicorn, ready() does not run at all. Equivalent startup+ # is delegated to gunicorn's post_fork hook.if os.environ.get('RUN_MAIN') != 'true': # Prevents duplicate execution in `runserver`return- # The responsibility for replicating the logic below falls to- # gunicorn when it is being used (via its post_fork() config file).- #if (( "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""))or ( "gunicorn" in sys.argv[0] )):returndiff --git a/src/hi/integrations/apps.py b/src/hi/integrations/apps.pyindex 9ed5fd56..9f23a3fd 100644--- a/src/hi/integrations/apps.py+++ b/src/hi/integrations/apps.py@@ -10,18 +10,22 @@ class IntegrationsConfig(AppConfig):def ready(self):from hi.background_tasks import HiBackgroundTaskHelper-- # Notes:- # - This method does not run in a production-like environment using gunicorn.- # - When it is called, it is often called multiple times during Django initialization.- # - Django seem to be suing different processes on each invocation.-- if os.environ.get('RUN_MAIN') != 'true': # Prevents duplicate execution in `runserver`- return-- # The responsibility for replicating the logic below falls to- # gunicorn when it is being used (via its post_fork() config file).++ # Counterintuitive: Django's AppConfig.ready() does not behave the way+ # the docs suggest. The two surprises that drive the guards below:+ #+ # 1. Under runserver, Django itself spawns multiple processes during+ # initialization -- not because workers are configured, but as part+ # of normal startup -- and ready() runs in each one. RUN_MAIN is set+ # only in the worker that serves requests; the other invocations+ # must bail out to avoid duplicate startup.#+ # 2. Under gunicorn, ready() does not run at all. Equivalent startup+ # is delegated to gunicorn's post_fork hook.++ if os.environ.get('RUN_MAIN') != 'true':+ return+if (( "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""))or ( "gunicorn" in sys.argv[0] )):returndiff --git a/src/hi/integrations/capability_gateway.py b/src/hi/integrations/capability_gateway.pyindex 9a8ae3f2..23296541 100644--- a/src/hi/integrations/capability_gateway.py+++ b/src/hi/integrations/capability_gateway.py@@ -3,9 +3,7 @@``IntegrationConnector``, ``IntegrationImporter``, and``IntegrationAttributeReferencer`` are the three per-capabilitygateway classes today: each is the framework-facing surface for a-specific ``IntegrationCapability``. They are conceptually peers but-historically shared no base, leaving cross-capability concerns with-no natural home.+specific ``IntegrationCapability``.``CapabilityGateway`` is the shared base. Things that apply to *any*capability (capability identification, operator-facing description,@@ -24,36 +22,24 @@ from .transient_models import IntegrationMetaDataclass CapabilityGateway:- """Base for per-capability gateway peers."""- # Subclasses declare which ``IntegrationCapability`` they- # realize. The framework reads this when iterating an- # integration's capability gateways uniformly.capability: IntegrationCapabilitydef get_metadata(self) -> IntegrationMetaData:- """Return the integration's ``IntegrationMetaData`` constant- (the same object the integration's ``IntegrationGateway``- exposes via ``get_metadata()``). The framework reads- ``.integration_id`` and ``.label`` from it for shared- operations like the auto-reconnect pre-pass and the- entity-removal helper, so each subclass declares the source- of truth in one place instead of repeating the values at- every call site."""+ """Return the integration's ``IntegrationMetaData`` constant --+ the same object the integration's ``IntegrationGateway`` exposes+ via ``get_metadata()``. Declared per subclass so the framework can+ read the integration's identity from a single source."""raise NotImplementedError('Subclasses must override this method')def get_description(self) -> Optional[str]:- """One-line operator-facing description of what this- capability does for this integration. Surfaces in- capability-specific UI (Content Sources header, future- per-source descriptions, etc.). Default None — UI omits the- description when not provided."""+ """One-line operator-facing description of what this capability+ does for this integration, surfaced in capability-specific UI.+ Default None -- UI omits the description when not provided."""return Nonedef get_attribute_actions_template_name(self) -> Optional[str]:"""Optional template fragment to render in the integration- attribute form's action bar. Default None — the action bar- shows only the framework's free buttons. Subclasses override- to provide capability-specific actions (status badges,- lifecycle buttons, etc.)."""+ attribute form's action bar. Default None -- the action bar shows+ only the framework's free buttons."""return Nonediff --git a/src/hi/integrations/connector/views.py b/src/hi/integrations/connector/views.pyindex abbdd90b..ed1d4845 100644--- a/src/hi/integrations/connector/views.py+++ b/src/hi/integrations/connector/views.py@@ -202,11 +202,9 @@ class ConnectorConfigureView( CapabilityConfigureView, ConnectorViewMixin ):f'{integration_data.integration_id}: {e}')- # Phase 7 collapse: when the integration supports sync, run it- # right here and render the sync-result modal directly. The- # previous Configure → Pre-Sync → Sync handshake is now one- # CONNECT click. Connector-less integrations keep the- # original redirect-to-manage behavior.+ # When the integration supports sync, run it inline and render+ # the sync-result modal directly so CONNECT is one click.+ # Connector-less integrations redirect to the manage page.connector = integration_data.integration_gateway.get_connector()if connector is not None:return self.render_sync_result(diff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/entity_operations.pyindex f066a2f0..d07ab57e 100644--- a/src/hi/integrations/entity_operations.py+++ b/src/hi/integrations/entity_operations.py@@ -5,13 +5,10 @@ This module holds mutating operations (disconnect, preserve, detach) thatact on Entity instances relative to the integration that owns them. Theseare distinct from the read-only analytical methods on EntityUserDataDetector.-EventDefinition cleanup (Issue #288) is integration-scoped and is-invoked here from both ``preserve_with_user_data`` and the hard-delete-branch of ``remove_entities_with_closure``. See-``EventDefinitionOperations`` for the policy: only EventDefinition rows-whose own ``integration_id`` matches are removed; user-owned-EventDefinitions referencing the entity's states are intentionally-left alone (deferred to the broader EventDefinition UX redesign).+EventDefinition cleanup is integration-scoped: only EventDefinition rows+whose own ``integration_id`` matches are removed; user-owned EventDefinitions+referencing the entity's states are intentionally left alone. See+``EventDefinitionOperations`` for the full policy."""import logging@@ -34,13 +31,6 @@ logger = logging.getLogger(__name__)class EntityIntegrationOperations:- """- Operations on an Entity relative to its integration attachment.-- Shared between sync-time preservation (when upstream drops an entity- that has user-created data) and integration removal (the SAFE mode of- IntegrationManager.disable_integration).- """@staticmethoddef collect_removal_closure( initial_entity_ids : Iterable[int] ) -> Set[int]:@@ -58,7 +48,7 @@ class EntityIntegrationOperations:- Iterates until no new entities are added (handles chained anddiamond-shaped delegations; cycles are bounded by the visited set).- This function is integration-agnostic — callers pass whatever seed+ This function is integration-agnostic -- callers pass whatever seedset defines the explicit removal scope."""closure : Set[int] = set(initial_entity_ids)@@ -66,9 +56,6 @@ class EntityIntegrationOperations:return closurewhile True:- # Candidate delegates: any delegate_entity reached from an- # entity-state owned by an entity already in the closure, that- # isn't already in the closure itself.candidate_ids = set(EntityStateDelegation.objects.filter(entity_state__entity_id__in = closure,@@ -79,9 +66,7 @@ class EntityIntegrationOperations:if not candidate_ids:break- # Single bulk query for every candidate's full principal- # set, then group in Python — replaces a per-candidate- # query that was O(passes × candidates) on the DB.+ # Bulk-query then group in Python to avoid O(passes x candidates) DB hits.principals_by_candidate : Dict[int, Set[int]] = {}for delegate_id, principal_id in EntityStateDelegation.objects.filter(delegate_entity_id__in = candidate_ids,@@ -126,36 +111,30 @@ class EntityIntegrationOperations:result : Optional[IntegrationSyncResult] = None ):"""Canonical removal for integration-owned entities.- Walks ``collect_removal_closure(seed_entity_ids)`` so every- delegate entity that would be orphaned by the removal (e.g.,- the Area auto-created when a camera was placed in a view) is- included. Each entity in the closure is then handled the- same way:-- * ``preserve_user_data=True`` (the SAFE pattern, used by- DELETE SAFE on disable and by sync-time refresh- removals): entities carrying operator-added attributes- are detached from the integration (active integration- identity cleared, previous identity recorded for the- auto-reconnect path); others are hard-deleted.-- * ``preserve_user_data=False`` (the DELETE ALL pattern):- every entity in the closure is hard-deleted, including- those with user-added data.-- ``result`` is optional. When provided, each closure entity's- name is appended to either ``result.removed_list`` (the- hard-delete branch) or ``result.detached_list`` (the- preserve branch) — never both. The preserve branch also- adds its diagnostic note to ``result.info_list``.-- Each entity in the closure is classified by its *own* user- data, independent of the seed's classification. This- produces the right outcome in the camera-preserved /- Area-no-user-data corner: an auto-created Area's display- purpose depends on the principal's live state, which the- preserve path removes — so deleting the now-purposeless- Area is correct even when its principal is being kept.+ Walks ``collect_removal_closure(seed_entity_ids)`` so every delegate+ entity that would be orphaned by the removal (e.g., the Area+ auto-created when a camera was placed in a view) is included. Each+ entity in the closure is handled per ``preserve_user_data``:++ * ``True`` (SAFE pattern): entities carrying operator-added+ attributes are detached from the integration (active integration+ identity cleared, previous identity recorded for the auto-+ reconnect path); others are hard-deleted.++ * ``False`` (DELETE ALL pattern): every entity in the closure is+ hard-deleted, including those with user-added data.++ When ``result`` is provided, each closure entity's name is appended+ to either ``result.removed_list`` (hard-delete branch) or+ ``result.detached_list`` (preserve branch) -- never both. The+ preserve branch also adds its diagnostic note to ``result.info_list``.++ Each entity in the closure is classified by its *own* user data,+ independent of the seed's classification. This produces the right+ outcome in the camera-preserved / Area-no-user-data corner: an+ auto-created Area's display purpose depends on the principal's live+ state, which the preserve path removes -- so deleting the+ now-purposeless Area is correct even when its principal is being kept."""closure_ids = cls.collect_removal_closure( seed_entity_ids )for entity in Entity.objects.filter( id__in = closure_ids ):@@ -172,7 +151,7 @@ class EntityIntegrationOperations:result.removed_list.append( entity.name )# Django's DB-level CASCADE from Entity.delete() reaches# EventClause / ControlAction (the children) but stops- # there — the parent EventDefinition row is never+ # there -- the parent EventDefinition row is never# touched. Delete integration-owned EventDefinitions# for this entity first, then let CASCADE handle the# rest of the entity graph.@@ -183,20 +162,15 @@ class EntityIntegrationOperations:@staticmethoddef summarize_for_removal( integration_id : str ) -> IntegrationRemovalSummary:"""- Classify the entities attached to the integration for the- confirmation dialogs that gate a Disable or a Refresh: counts- total entities (plus orphan-after-removal delegates) and how- many carry user-created data.-- Both the Disable modal and the pre-Refresh modal use the same- classification: each is asking the operator a *policy*- question ("if items with custom data are about to be let go,- retain them or delete them?") and surfaces the SAFE / ALL- choice only when ``has_mixed_state``. Refresh's actual dropped- set is decided at sync execution against fresh upstream — the- operator's choice expresses the policy that applies if drops- include user-data items, regardless of which specific items- end up dropping.+ Classify the entities attached to the integration: total (including+ orphan-after-removal delegates) and how many carry user-created data.+ Used to populate the policy choice in the operator confirmation+ dialogs (retain user-data items vs delete).++ This is a policy classification, not the actual dropped set. For+ Refresh, the dropped set is decided at sync execution against fresh+ upstream -- the operator's choice expresses the policy that applies+ if drops include user-data items."""target_ids = EntityIntegrationOperations.get_removal_entity_ids(integration_id = integration_id,@@ -220,35 +194,28 @@ class EntityIntegrationOperations:result : Optional[ IntegrationSyncResult ] = None,) -> Dict[ IntegrationKey, Entity ]:"""- Auto-reconnect candidate lookup (Issue #281). Pure read.+ Auto-reconnect candidate lookup. Pure read.- Given a set of upstream IntegrationKeys that the- synchronizer's primary-match step did NOT match, return a- map of ``upstream_key → matching disconnected entity`` for- every key that uniquely aligns with a disconnected entity's+ Given a set of upstream IntegrationKeys that the synchronizer's+ primary-match step did NOT match, return a map of+ ``upstream_key -> matching disconnected entity`` for every key that+ uniquely aligns with a disconnected entity's``previous_integration_id`` / ``previous_integration_name``.- Ambiguous matches (multiple disconnected entities sharing- the same previous identity) are dropped from the result map.- The issue's contract is to leave the duplicate for the user- to resolve via merge (#263), since the system has no basis- to pick one side over the other. A WARNING is logged and a- breadcrumb is appended to ``result.info_list`` (when- provided) for each ambiguous case so the operator can find- them.-- The per-entity reconnect mutations and converter dispatch- are deliberately NOT performed here. Callers (the- per-integration synchronizers) own that step because each- integration's converter has a different signature and- callers also want to enrich ``result`` with their own- operator-facing messages. ``strip_disconnected_prefix`` is- provided as a shared helper for the name-cleanup step.-- The lookup is a single batched DB query keyed on- ``(previous_integration_id, previous_integration_name__in=...)``- — O(1) DB round trips regardless of how many upstream keys- the caller passes.+ Ambiguous matches (multiple disconnected entities sharing the same+ previous identity) are dropped from the result map; the contract is+ to leave the duplicate for the user to resolve via merge, since the+ system has no basis to pick one side over the other. A WARNING is+ logged and a breadcrumb is appended to ``result.info_list`` (when+ provided) for each ambiguous case.++ The per-entity reconnect mutations and converter dispatch are+ deliberately not performed here -- each integration's converter has a+ different signature and callers also want to enrich ``result`` with+ their own messages.++ Single batched DB query -- O(1) round trips regardless of how many+ upstream keys are passed."""upstream_keys = list( upstream_keys )if not upstream_keys:@@ -299,25 +266,20 @@ class EntityIntegrationOperations:integration_name : str,result : Optional[IntegrationSyncResult] = None ):"""- Preserve an entity with user-created data by disconnecting it- from its integration and removing only integration-related- components (sensors, controllers, orphaned states,- integration-owned attributes, integration-owned- EventDefinitions). The entity's previous integration identity- is recorded on the entity so the auto-reconnect path can- recognize it if the same upstream key reappears later. The- detached state is signaled structurally — ``integration_id``- becomes NULL and ``previous_integration_id`` carries the prior- identity — and surfaced to the operator via a "From- <integration>" badge in the entity-detail UI.-- Issue #288: integration-owned EventDefinitions are removed- first inside the atomic block via- ``EventDefinitionOperations.delete_for_entity``. User-owned- EventDefinitions (``integration_id IS NULL``) referencing this- entity's states are intentionally NOT touched here — the- broader UX of broken/partial user rules is deferred to a- separate redesign.+ Preserve an entity with user-created data by disconnecting it from+ its integration and removing only integration-related components+ (sensors, controllers, orphaned states, integration-owned attributes,+ integration-owned EventDefinitions). The entity's previous integration+ identity is recorded on the entity so the auto-reconnect path can+ recognize it if the same upstream key reappears later. The detached+ state is signaled structurally: ``integration_id`` becomes NULL and+ ``previous_integration_id`` carries the prior identity.++ Integration-owned EventDefinitions are deleted first inside the atomic+ block, before the entity-state and controller deletions that would+ otherwise leave dangling parent rows (CASCADE reaches the children but+ not the parents). User-owned EventDefinitions (``integration_id IS NULL``)+ referencing this entity's states are intentionally NOT touched.Args:entity: The Entity to preserve.@@ -327,98 +289,65 @@ class EntityIntegrationOperations:"""original_name = entity.name- # Get integration-related components to removesensor_ids_to_remove = EntityUserDataDetector.get_integration_related_sensors(entity)controller_ids_to_remove = EntityUserDataDetector.get_integration_related_controllers(entity)- # Get entity states that will become orphanedorphaned_state_ids = EntityUserDataDetector.get_orphaned_entity_states(entity, sensor_ids_to_remove, controller_ids_to_remove)with transaction.atomic():- # Remove integration-owned EventDefinitions for this entity.- # Done first so the parent rows are gone before the states/- # controllers they reference are deleted below; CASCADE on- # EventClause/ControlAction reaches only the children, so- # parents must be removed explicitly here. See- # EventDefinitionOperations docstring for the integration-- # scoped policy.EventDefinitionOperations.delete_for_entity( entity )- # Remove integration-related sensorsif sensor_ids_to_remove:removed_sensor_count = Sensor.objects.filter(id__in=sensor_ids_to_remove).delete()[0]logger.debug(f'Removed {removed_sensor_count} integration sensors for {entity}')- # Remove integration-related controllersif controller_ids_to_remove:removed_controller_count = Controller.objects.filter(id__in=controller_ids_to_remove).delete()[0]logger.debug(f'Removed {removed_controller_count} integration controllers for {entity}')- # Remove orphaned entity statesif orphaned_state_ids:removed_state_count = EntityState.objects.filter(id__in=orphaned_state_ids).delete()[0]logger.debug(f'Removed {removed_state_count} orphaned entity states for {entity}')- # Remove integration-created attributes (keep user-added ones).- # Provenance is determined by attribute_type_str: PREDEFINED is- # system/integration-created, CUSTOM is user-added. Note:- # queryset .delete() intentionally bypasses the model-level- # SoftDeleteAttributeModel.delete() override, performing a hard- # delete. Integration attributes should not accumulate as- # soft-deleted records.+ # Drop integration-created attributes, keep user-added ones. Provenance+ # is in attribute_type_str: PREDEFINED is system-created, CUSTOM is+ # user-added. queryset.delete() intentionally bypasses the+ # SoftDeleteAttributeModel.delete() override -- integration attributes+ # should not accumulate as soft-deleted rows.removed_attr_count = entity.attributes.exclude(attribute_type_str=str(AttributeType.CUSTOM),).delete()[0]if removed_attr_count:logger.debug(f'Removed {removed_attr_count} integration attributes for {entity}')- # Disconnect entity from integration. The current integration- # identity is copied to the previous_integration_* fields- # so the auto-reconnect path can recognize this entity if- # the same upstream key reappears later. The presence of- # previous_integration_id is also what drives the- # "From <integration>" UI badge.entity.previous_integration_key = entity.integration_keyentity.integration_key = None- # Restore user-management flags. These are commonly set to False- # by integration converters to prevent the user from deleting or- # extending an integration-managed entity. After detach the- # entity is no longer integration-managed, so user-management- # rights are restored.+ # Restore user-management flags. Integration converters typically set+ # these to False to lock the entity against user changes; on detach+ # the entity is no longer integration-managed.entity.can_user_delete = Trueentity.allow_internal_attributes = True- # The data-source state (now DETACHED) is derived from- # the integration_id / previous_integration_id columns:- # integration_key.setter on line above set integration_id- # to NULL and the previous-pair carries the provenance,- # so the entity now reads as is_detached.-- # Suppress integration-backed capabilities. The intrinsic- # video-stream capability is genuinely lost (the backing sensor- # was deleted above). The is_disabled flag is the general- # capability gate — listing/enumeration sites use it to keep- # a detached entity out of capability-driven UX (e.g., the- # sidebar Cameras list).+ # has_video_stream: the backing sensor was deleted, so the capability+ # is genuinely lost. is_disabled: the general capability gate that+ # keeps a detached entity out of capability-driven enumerations.entity.has_video_stream = Falseentity.is_disabled = Trueentity.save()if result is not None:- # detached_list drives the operator-visible "Detached"- # tile + per-category list in the sync result modal;- # info_list keeps the diagnostic note for the collapsed- # Details section.+ # detached_list surfaces in the operator-visible summary;+ # info_list carries the diagnostic note for the details view.result.detached_list.append( entity.name )result.info_list.append(f'Preserved {integration_name} item "{original_name}" with user data; 'diff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.pyindex e930823d..79ce1b3b 100644--- a/src/hi/integrations/enums.py+++ b/src/hi/integrations/enums.py@@ -18,20 +18,6 @@ ALL_CAPABILITIES = frozenset( IntegrationCapability )class IntegrationDisableMode( LabeledEnum ):- """- Mode used when removing (disabling) an integration. Controls how the- integration's attached entities are handled.-- SAFE — delete entities without user-created data; preserve entities with- user-created data by detaching them from the integration (strips- integration association, removes integration-only components, records- the previous integration identity to drive the "From ..." UI- badge and the auto-reconnect path). This mirrors the sync-time- preservation behavior.-- ALL — hard-delete all entities attached to the integration regardless of- user-created data.- """SAFE = ( 'Delete Safe','Delete entities without user data; preserve those with user data' )@@ -44,7 +30,7 @@ class IntegrationDisableMode( LabeledEnum ):class IntegrationAttributeType( LabeledEnum ):- """ Abstract base class for integrations ot define the required attributes they need. """+ """Base for per-integration attribute-type enums."""def __init__( self,label : str,diff --git a/src/hi/integrations/event_definition_operations.py b/src/hi/integrations/event_definition_operations.pyindex 49339079..1793c529 100644--- a/src/hi/integrations/event_definition_operations.py+++ b/src/hi/integrations/event_definition_operations.py@@ -1,26 +1,22 @@"""Operations on EventDefinition rows with respect to integration ownership.-This module holds the integration-scoped cleanup helpers for-EventDefinition. The policy is deliberately narrow:-- * Only EventDefinition rows whose own ``integration_id`` matches the- disconnecting integration are removed. User-owned EventDefinition- rows (``integration_id IS NULL``) are never touched here, even when- they reference an entity state that an integration is about to- delete. The silent semantic change of a user-owned multi-clause- rule losing one of its clauses is a known gap deferred to the- broader EventDefinition UX redesign.- * The cleanup is invoked at the integration disconnect / sync-removal- boundary (``EntityIntegrationOperations``); there is no general- "EntityState delete cascades to parent EventDefinition" rule.--EventDefinition has no FK back to Entity. The reverse path is-``EventDefinition → EventClause → EntityState → Entity``, traversed-explicitly in the queries below. Children-(``EventClause`` / ``ControlAction`` / ``AlarmAction`` / ``EventHistory``)-have ``on_delete=CASCADE`` to ``EventDefinition`` and are removed by-the parent delete; we do not need to enumerate them here.+Integration-scoped cleanup with a deliberately narrow policy:++ * Only EventDefinition rows whose own ``integration_id`` matches are+ removed. User-owned EventDefinition rows (``integration_id IS NULL``)+ are never touched here, even when they reference an entity state that+ an integration is about to delete. The silent semantic change of a+ user-owned multi-clause rule losing one of its clauses is a known gap.+ * No general "EntityState delete cascades to parent EventDefinition"+ rule exists -- cleanup runs only at the integration disconnect /+ sync-removal boundary.++EventDefinition has no FK back to Entity; the reverse path is+``EventDefinition -> EventClause -> EntityState -> Entity``, traversed+explicitly in the queries below. Children (``EventClause``,+``ControlAction``, ``AlarmAction``, ``EventHistory``) cascade from the+parent delete and are not enumerated here."""import logging@@ -33,22 +29,15 @@ logger = logging.getLogger(__name__)class EventDefinitionOperations:- """- Integration-scoped cleanup of EventDefinition rows.-- All methods are explicit and integration-id-bounded. Callers are- expected to invoke these from inside their own ``transaction.atomic``- boundary; the helpers do not open transactions themselves.- """+ """Callers must wrap invocations in ``transaction.atomic``; the helpers+ do not open transactions themselves."""@staticmethoddef delete_for_integration( integration_id : str ) -> int:"""Delete every EventDefinition whose own ``integration_id`` matches.-- Used by Disable-ALL and as a backstop. Does not consider clauses- — the integration_id on the EventDefinition itself is the- ownership signal.+ Does not traverse clauses -- the integration_id on the EventDefinition+ itself is the ownership signal."""if not integration_id:return 0@@ -67,12 +56,9 @@ class EventDefinitionOperations:def delete_for_entity( cls, entity : Entity ) -> int:"""Delete EventDefinitions owned by this entity's integration whose- clauses reference any of this entity's states.-- Used by ``EntityIntegrationOperations.preserve_with_user_data``- and per-entity sync removal. Returns 0 (no-op) when the entity- is not currently integration-attached, so callers can invoke- this unconditionally.+ clauses reference any of this entity's states. Returns 0 when the+ entity is not currently integration-attached, so callers may invoke+ unconditionally."""if not entity.integration_id:return 0diff --git a/src/hi/integrations/integration_attribute_edit_context.py b/src/hi/integrations/integration_attribute_edit_context.pyindex 259e435d..f88354a5 100644--- a/src/hi/integrations/integration_attribute_edit_context.py+++ b/src/hi/integrations/integration_attribute_edit_context.py@@ -1,10 +1,3 @@-"""-Integration Attribute Edit Context - Integration-specific context for attribute editing templates.--This module contains Integration-specific implementations of the AttributeItemEditContext-pattern, encapsulating integration-specific domain knowledge while maintaining-the generic template interface.-"""from typing import Any, Dict, Optional, Typefrom django.forms import ModelForm, BaseInlineFormSet@@ -24,16 +17,10 @@ from .integration_data import IntegrationDataclass IntegrationAttributeItemEditContext(AttributeItemEditContext):"""- Integration-specific context provider for attribute editing templates.-- This class encapsulates Integration-specific knowledge while providing- the generic interface expected by attribute editing templates.-- Construction takes the active ``CapabilityGateway`` directly (rather- than the capability enum). The instance carries both the capability- identity (``capability_gateway.capability``) used for attribute- filtering and the capability-specific UI hooks (description,- attribute-form action template) the rendered templates consult.+ Constructed with the active ``CapabilityGateway`` directly (not the+ capability enum), so the instance carries both the capability identity+ used for attribute filtering and the capability-specific UI hooks+ (description, attribute-form action template)."""def __init__( self,@@ -47,11 +34,9 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):super().__init__( owner_type = 'integration', owner = integration_data.integration )self.integration_data = integration_dataself._capability_gateway = capability_gateway- # capability_gateway may be None in legacy paths (e.g., an- # integration declares a capability metadata-side but- # exposes no implementation instance). The attribute- # queryset falls back to "no capability filter" in that- # case, which preserves existing behavior.+ # capability_gateway may be None when an integration declares a+ # capability metadata-side but exposes no implementation instance;+ # the attribute queryset then falls back to no capability filter.self._capability = (capability_gateway.capability if capability_gateway is not None else None)@@ -64,7 +49,6 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):@propertydef integration(self) -> Integration:- """Get the Integration instance (typed accessor)."""return self.owner@property@@ -121,12 +105,12 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):@propertydef attribute_upload_form_class(self) -> Type[AttributeUploadForm]:- # No file uploads for Integration attributes (as of yet)+ # No file uploads for Integration attributes.return None@propertydef file_upload_url(self) -> str:- # No file uploads for Integration attributes (as of yet)+ # No file uploads for Integration attributes.return Nonedef to_template_context(self) -> Dict[str, Any]:diff --git a/src/hi/integrations/integration_converter_helper.py b/src/hi/integrations/integration_converter_helper.pyindex f60d4a8c..544d49a5 100644--- a/src/hi/integrations/integration_converter_helper.py+++ b/src/hi/integrations/integration_converter_helper.py@@ -8,17 +8,14 @@ from .transient_models import IntegrationKeyclass IntegrationConverterHelper:- """Shared classmethod helpers for integration converters- (which are stateless containers of related methods).-- The cached ``_Internal`` instance bridges this classmethod- facade to the project's instance-method ``SensorResponseMixin``- pattern so manager access still goes through the mixin's- coordination path. The proper fix is to make converters- Singleton instances and inherit ``SensorResponseMixin``- directly; deferred because the converter call surface is- pervasively classmethod-based and that conversion is a much- larger change.+ """Shared classmethod helpers for integration converters (stateless+ containers of related methods).++ The nested ``_Internal`` instance bridges this classmethod facade to+ the instance-method ``SensorResponseMixin`` pattern so manager access+ still goes through the mixin's coordination path. This is a workaround+ for the classmethod-based converter call surface, not the canonical+ pattern."""class _Internal( SensorResponseMixin ):@@ -48,19 +45,17 @@ class IntegrationConverterHelper:def get_cache_entry(cls, integration_key : IntegrationKey,) -> Dict[str, Any]:- """Return cached EntityState metadata used by integration- value translation. The dict has a ``units`` key holding the- EntityState.units string (or None when no translation is- needed). Backed by ``IntegrationMetadataCache`` (process-wide,- lazy-warmed)."""+ """Cached EntityState metadata for value translation. The dict has a+ ``units`` key holding the EntityState.units string (or None when no+ translation is needed). Backed by ``IntegrationMetadataCache``+ (process-wide, lazy-warmed)."""return IntegrationMetadataCache().get_entry( integration_key )@classmethodasync def get_cache_entry_async(cls, integration_key : IntegrationKey,) -> Dict[str, Any]:- """Async variant of ``get_cache_entry`` for use from async- monitor / converter paths."""+ """Async variant of ``get_cache_entry``."""return await IntegrationMetadataCache().get_entry_async( integration_key )@classmethod@@ -70,12 +65,10 @@ class IntegrationConverterHelper:external_unit : str,integration_key : IntegrationKey,) -> float:- """Inbound boundary: translate a numeric value from the- integration's external unit (e.g., HA's reported- ``unit_of_measurement``) to the EntityState's stored unit.- The target unit is read from the IntegrationMetadataCache.- Pass-through when the EntityState has no units or the units- already match."""+ """Inbound boundary: translate a value from the integration's external+ unit (e.g., HA's reported ``unit_of_measurement``) to the EntityState's+ stored unit, read from the IntegrationMetadataCache. Pass-through when+ the EntityState has no units or the units already match."""target_unit = cls.get_cache_entry(integration_key,).get( 'units' )@@ -92,9 +85,8 @@ class IntegrationConverterHelper:external_unit : str,integration_key : IntegrationKey,) -> float:- """Async variant of ``to_entity_state_value`` for use from- async monitor paths. Cache lookup goes through- sync_to_async; conversion arithmetic is pure-Python."""+ """Async variant of ``to_entity_state_value``. Cache lookup goes+ through sync_to_async; conversion arithmetic is pure-Python."""entry = await cls.get_cache_entry_async( integration_key )return cls._convert_between_units(value = external_value,@@ -109,12 +101,11 @@ class IntegrationConverterHelper:external_unit : str,integration_key : IntegrationKey,) -> float:- """Outbound boundary: translate a numeric value in the- EntityState's stored unit to the integration's external- unit (e.g., HA's currently-reported native unit). The- source unit is read from the IntegrationMetadataCache.- Pass-through when the EntityState has no units or the units- already match."""+ """Outbound boundary: translate a value in the EntityState's stored+ unit (read from the IntegrationMetadataCache) to the integration's+ external unit (e.g., HA's currently-reported native unit).+ Pass-through when the EntityState has no units or the units already+ match."""source_unit = cls.get_cache_entry(integration_key,).get( 'units' )@@ -145,10 +136,9 @@ class IntegrationConverterHelper:from_unit : Optional[str],to_unit : Optional[str],) -> float:- """Pure-Python Pint conversion between unit strings.- Pass-through when either side is missing or the units- already match. Defensive on parse failures so a malformed- unit string never raises into the converter call sites."""+ """Pure-Python Pint conversion between unit strings. Pass-through+ when either side is missing or the units already match. Defensive on+ parse failures so a malformed unit string never raises."""if not from_unit or not to_unit or from_unit == to_unit:return valuetry:diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex 91a093e8..4cb35f50 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -20,69 +20,47 @@ from hi.integrations.transient_models import (class IntegrationGateway:- """- Each integration needs to provide an Integration Manager that implements these methods.- """+ """Subclassed by each integration to expose its lifecycle and capability hooks."""def get_metadata(self) -> IntegrationMetaData:raise NotImplementedError('Subclasses must override this method')def notify_settings_changed(self):- """- This method is called when Integration or IntegrationAttribute models- are modified. Each integration should implement this to reload its- configuration and notify any dependent components.- """+ """Called when Integration or IntegrationAttribute models are+ modified. Subclass implementations should reload configuration and+ notify dependent components."""raise NotImplementedError('Subclasses must override this method')def get_connector(self) -> Optional[IntegrationConnector]:- """- Return the integration's connector when it supports sync;- None otherwise. Sync is an opt-in capability — not every- integration requires one. The framework owns the sync workflow- (pre-sync confirmation, sync execution, post-sync placement);- the connector participates by providing the integration-- specific work plus a small amount of peripheral metadata.+ """Return the integration's connector when it supports the CONNECT+ capability; None otherwise. The framework owns the sync workflow;+ the connector supplies the integration-specific work and metadata.- The Issue #283 sync-check probe also rides on the connector- (see ``IntegrationConnector.check_needs_sync``): integrations- without a connector naturally opt out of both full sync and- the periodic drift check.- """+ Integrations without a connector opt out of both full sync and the+ periodic drift check (the sync-check probe rides on the connector)."""return Nonedef get_importer(self) -> Optional[IntegrationImporter]:- """- Return the integration's importer when it supports the IMPORT- capability; None otherwise. Parallel to get_connector() for- the CONNECT capability. The framework owns the import workflow- (Data Import page, preview, confirm, result modal, placement);- the importer supplies the integration-specific candidate- listing, item ingest, and discard operations.- """+ """Return the integration's importer when it supports the IMPORT+ capability; None otherwise. The framework owns the import workflow;+ the importer supplies integration-specific candidate listing, item+ ingest, and discard operations."""return Nonedef get_attribute_referencer(self) -> Optional[IntegrationAttributeReferencer]:- """- Return the integration's attribute-referencer when it- supports the ATTRIBUTE_REFERENCE capability; None otherwise.- Parallel to get_connector() and get_importer(). The- framework owns the picker UI and the TEXT-attribute attach- lifecycle; the referencer supplies the integration-specific- search-against-upstream operation.- """+ """Return the integration's attribute-referencer when it supports the+ ATTRIBUTE_REFERENCE capability; None otherwise. The framework owns+ the picker and the TEXT-attribute attach lifecycle; the referencer+ supplies the integration-specific search-against-upstream operation."""return Nonedef validate_configuration(self,integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:- """- Schema-only validation of the proposed configuration. Must NOT- perform network operations. Returns success if the attribute set- is structurally usable; returns an error otherwise. For live- access validation, see validate_access().- """+ """Schema-only validation of the proposed configuration. Must NOT+ perform network operations. For live access validation, see+ ``validate_access``."""raise NotImplementedError('Subclasses must override this method')def validate_access(@@ -90,27 +68,21 @@ class IntegrationGateway:integration_attributes: List[IntegrationAttribute],timeout_secs: Optional[float],) -> ConnectionTestResult:- """- Live probe to validate access to the upstream system using the- proposed configuration. Must respect the bounded timeout. Used- at attribute-save time (Configure / Reconfigure) and before- relaunching monitors (Resume).- """+ """Live probe to validate access to the upstream system using the+ proposed configuration. Must respect the bounded timeout."""raise NotImplementedError('Subclasses must override this method')def group_entities_for_placement(self, entities: List[Entity],) -> EntityPlacementInput:- """Partition the given entities into the EntityPlacementInput- shape consumed by the placement modal. Capability-neutral —- both Connect-sync and Import-run flows feed entities through- this same method, so a given integration groups its entities- the same way regardless of how they arrived.+ """Partition the given entities into the EntityPlacementInput shape+ consumed by placement. Capability-neutral -- both sync and import+ flows feed entities through this method, so a given integration+ groups its entities the same way regardless of how they arrived.- Default: group by ``EntityGroupType`` rollup using the- rollup's humanized label as the group name. Subclasses- override when a different domain grouping makes sense- (e.g., HomeBox's Location/Tag/Type fallback)."""+ Default: group by ``EntityGroupType`` rollup using the rollup's+ humanized label as the group name. Subclasses override when a+ different domain grouping makes sense."""return PlacementInputBuilder.by_entity_type_group(entities = entities,item_key_fn = self._placement_item_key,diff --git a/src/hi/integrations/integration_metadata_cache.py b/src/hi/integrations/integration_metadata_cache.pyindex b3d28f72..2ea3fe8d 100644--- a/src/hi/integrations/integration_metadata_cache.py+++ b/src/hi/integrations/integration_metadata_cache.py@@ -15,26 +15,22 @@ logger = logging.getLogger(__name__)class IntegrationMetadataCache( Singleton ):- """Process-wide, lazily-warmed cache of EntityState metadata- that integration converters need at value-translation time.-- Polling loops are hot paths and the inbound and outbound- converters need per-entity metadata (today: stored units;- potentially more in the future) on every call. Caching avoids- per-call DB queries; the underlying fields are set at creation- and rarely change in practice, so a process-lifetime cache- with no active invalidation is the right trade-off (the- workaround for the rare edit is a process restart).-- Keyed by ``IntegrationKey``. Each entry is a small dict so- additional metadata can be added later without changing the- API surface. Today the only entry key is ``units`` (the- EntityState.units string, or None when the EntityState has- no units).-- Concurrency: bulk-warmup and lazy single-row fills take the- write lock; reads of an already-populated entry are unlocked- (CPython dict reads are atomic for our access pattern).+ """Process-wide, lazily-warmed cache of EntityState metadata that+ integration converters need at value-translation time.++ Polling loops are hot paths and the inbound/outbound converters need+ per-entity metadata on every call. Caching avoids per-call DB queries;+ the underlying fields are set at creation and rarely change, so a+ process-lifetime cache with no active invalidation is the right+ trade-off -- the workaround for the rare edit is a process restart.++ Keyed by ``IntegrationKey``; each entry is a dict with a ``units`` key+ (the EntityState.units string, or None when the EntityState has no+ units).++ Concurrency: bulk-warmup and lazy single-row fills take the write+ lock; reads of an already-populated entry are unlocked (CPython dict+ reads are atomic for our access pattern)."""def __init_singleton__(self):@@ -46,12 +42,10 @@ class IntegrationMetadataCache( Singleton ):def get_entry(self, integration_key : IntegrationKey,) -> Dict[str, Any]:- """Return the cached metadata dict for the given- ``integration_key``. Triggers a single bulk warmup on the- first call across the process; entities created after- warmup are filled lazily on miss. Sync API; use- ``get_entry_async`` from async contexts to avoid Django's- SynchronousOnlyOperation guard during DB-touching paths."""+ """Return the cached metadata dict for ``integration_key``. Triggers+ a single bulk warmup on first use; entities created after warmup are+ filled lazily on miss. Sync API -- use ``get_entry_async`` from async+ contexts to avoid Django's SynchronousOnlyOperation guard."""if not self._warmed:self._warmup()entry = self._cache.get( integration_key )@@ -62,11 +56,10 @@ class IntegrationMetadataCache( Singleton ):async def get_entry_async(self, integration_key : IntegrationKey,) -> Dict[str, Any]:- """Async variant of ``get_entry``. After the cache is- warmed, reads are pure-Python dict accesses and the- sync_to_async hop is essentially free; before warm and on- lazy-fill misses, the DB lookup happens in a thread pool- so it's safe to call from async monitor contexts."""+ """Async variant of ``get_entry``. After warmup, reads are pure-Python+ dict accesses and the sync_to_async hop is essentially free; before+ warm and on lazy-fill misses, the DB lookup happens in a thread pool+ so it's safe to call from async contexts."""if self._warmed and integration_key in self._cache:return self._cache[ integration_key ]return await sync_to_async(@@ -81,7 +74,7 @@ class IntegrationMetadataCache( Singleton ):by ``HiModelHelper``; ``integration_id`` namespacing preventscross-integration collisions). Sensor entries win on overlap;a warning fires if the Controller's entry would have- disagreed — canary for invariant violations."""+ disagreed -- canary for invariant violations."""with self._lock:if self._warmed:return@@ -108,21 +101,16 @@ class IntegrationMetadataCache( Singleton ):self._warmed = Truedef invalidate(self):- """Drop all cached entries and reset the warmup flag.-- Called by the integration framework after any operation- that creates, refreshes, or removes EntityStates with- integration_keys (sync, disable). The next ``get_entry``- triggers a fresh bulk warmup from the now-consistent DB- state.-- Necessary because ``_lazy_fill`` caches ``{'units': None}``- on miss to keep the polling-loop hot path free of repeat- DB queries. Without invalidation, a poll that races an- in-progress import pins a bad entry for the lifetime of- the process — visible as raw, unconverted values for any- new unit-bearing EntityState (most obviously a wrong-by-- ~88°F temperature reading)."""+ """Drop all cached entries and reset the warmup flag. The next+ ``get_entry`` triggers a fresh bulk warmup. Call after any operation+ that creates, refreshes, or removes EntityStates with integration_keys.++ Necessary because ``_lazy_fill`` caches ``{'units': None}`` on miss to+ keep the polling-loop hot path free of repeat DB queries. Without+ invalidation, a poll that races an in-progress import pins a bad entry+ for the lifetime of the process -- visible as raw, unconverted values+ for any new unit-bearing EntityState (a wrong-by-~88F temperature+ reading, most obviously)."""with self._lock:self._cache.clear()self._warmed = Falsediff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.pyindex 57d7293c..fdfbc09a 100644--- a/src/hi/integrations/models.py+++ b/src/hi/integrations/models.py@@ -78,15 +78,12 @@ class IntegrationAttribute( AttributeModel ):return 'integration/attributes/'def _get_history_model_class(self):- """Return the history model class for IntegrationAttribute."""return IntegrationAttributeHistoryclass IntegrationDetailsModel( models.Model ):- """- For use in DB objects that need to be associated with an integration- device, sensor, controller, attribute, etc.- """+ """Mixin for DB models that need integration provenance fields+ (active key, previous-disconnected key, and arbitrary payload)."""objects = IntegrationDetailsModelManager()class Meta:@@ -108,14 +105,13 @@ class IntegrationDetailsModel( models.Model ):blank = True,help_text = 'Integration-specific data (e.g., HA domain, device capabilities)',)- # The previous_integration_* fields record the integration identity- # an instance had at the moment it was disconnected (e.g., via- # sync-time preservation or Disable-SAFE). They drive the- # auto-reconnect path in IntegrationConnector: when an upstream- # entity reappears whose key matches a disconnected entity's- # previous identity, the entity is reconnected rather than a- # duplicate being created. The previous_integration_id is indexed- # because the secondary-match query during sync filters on it.+ # The previous_integration_* fields record the integration identity an+ # instance had at the moment it was disconnected. They drive the+ # auto-reconnect path: when an upstream entity reappears whose key+ # matches a disconnected entity's previous identity, the entity is+ # reconnected rather than a duplicate being created. The+ # previous_integration_id is indexed because the secondary-match query+ # during sync filters on it.previous_integration_id = models.CharField('Previous Integration Id',max_length = 32,@@ -130,10 +126,9 @@ class IntegrationDetailsModel( models.Model ):@propertydef integration_key(self) -> IntegrationKey:- # Symmetric with the setter: returns None when the underlying- # fields are unset, so reading the property on a never-attached- # or already-disconnected instance is safe (and round-trips- # cleanly through the setter as a no-op clear).+ # Returns None when the underlying fields are unset, so reading on a+ # never-attached or already-disconnected instance is safe. Round-trips+ # through the setter as a no-op clear.if self.integration_id is None or self.integration_name is None:return Nonereturn IntegrationKey(@@ -149,14 +144,10 @@ class IntegrationDetailsModel( models.Model ):returnself.integration_id = integration_key.integration_idself.integration_name = integration_key.integration_name- # Re-attaching to an active integration invalidates any- # prior detached-state record. Clearing here is defensive- # against future call sites that set integration_key- # without going through reconnect_disconnected_items: a- # stale previous_integration_* pair on an active entity- # would mis-trigger the "From X" UI badge and- # confuse any future query that filters disconnected- # entities by previous_integration_id alone.+ # Re-attaching to an active integration invalidates any prior+ # detached-state record. Clearing here is defensive: a stale+ # previous_integration_* pair on an active entity would confuse+ # queries that filter disconnected entities on previous_integration_id.self.previous_integration_id = Noneself.previous_integration_name = Nonereturn@@ -208,8 +199,7 @@ class IntegrationDetailsModel( models.Model ):class IntegrationAttributeHistory(AttributeValueHistoryModel):- """History tracking for IntegrationAttribute changes."""-+attribute = models.ForeignKey(IntegrationAttribute,related_name='history',diff --git a/src/hi/integrations/placement_request.py b/src/hi/integrations/placement_request.pyindex b78c70cf..be96312b 100644--- a/src/hi/integrations/placement_request.py+++ b/src/hi/integrations/placement_request.py@@ -1,39 +1,22 @@"""-Placement view request shape — parsing the inputs, encoding the-outputs.--The placement modal carries two related concerns that this module-owns:--* ``PlacementUrlParams`` — the URL/form-param contract- (``is_initial_connect``, ``entity_ids``). Single source of truth- for key names and value encodings; build URLs and parse requests- via this class rather than handling raw strings.--* ``PlacementFormParser`` — the placement-form-body parser. The- placement modal carries a three-level inheritance: top default- → group default → per-entity. Empty selections at any level- inherit from the parent; explicit ``__skip__`` overrides- inheritance with "don't place this entity"; a top-level- ``__new_view__`` value creates one fresh ``LocationView`` named- after the integration; a top-level ``__new_collection__`` value- creates one fresh ``Collection``. Group/entity overrides to- existing views or collections remain in effect even when the- top is one of the new-* sentinels.-- Form values for the dropdowns are *tagged* so views and- collections can share the same select element without colliding- on numeric ids:-- ``view:<id>`` — existing LocationView- ``collection:<id>`` — existing Collection- ``__new_view__`` — create one fresh LocationView (top only)- ``__new_collection__`` — create one fresh Collection (top only)- ``__skip__`` — explicit no-op overriding parent- ``''`` — inherit from parent (top → skip-all)-- ``parse(request, integration_data)`` returns a list of- ``PlacementDecision`` values for the placement service to apply.+Placement view request shape -- parsing the inputs, encoding the outputs.++This module owns two related concerns for the placement modal:++* ``PlacementUrlParams`` -- the URL/form-param contract.+* ``PlacementFormParser`` -- the placement-form-body parser, including+ the three-level inheritance (top default -> group default -> per-entity)+ and the sentinel/tag wire format used in the form-value dropdowns:++ ``view:<id>`` -- existing LocationView+ ``collection:<id>`` -- existing Collection+ ``__new_view__`` -- create one fresh LocationView (top only)+ ``__new_collection__`` -- create one fresh Collection (top only)+ ``__skip__`` -- explicit no-op overriding parent+ ``''`` -- inherit from parent (top -> skip-all)++ Group/entity overrides to existing views or collections remain in+ effect even when the top is one of the new-* sentinels."""import loggingfrom dataclasses import dataclass, field@@ -57,16 +40,13 @@ logger = logging.getLogger(__name__)class PlacementUrlParams:"""Encoded contract for the placement view's URL/form params.- Single source of truth for key names, value encodings, and- list separators — callers build URLs and parse requests via- this class rather than handling raw strings. Renaming a key- or changing an encoding happens in exactly one place.+ Single source of truth for key names, value encodings, and list+ separators -- callers build URLs and parse requests via this class+ rather than handling raw strings.- Scope: the URL query params (``?is_initial_connect=…&entity_ids=…``)- and the matching hidden form fields the placement modal POSTs- back. Does *not* cover the per-entity / per-group form fields- consumed by ``PlacementFormParser`` — those have their own- contract owned by that parser.+ Scope: the URL query params (``?is_initial_connect=...&entity_ids=...``)+ and matching hidden form fields. Does *not* cover the per-entity /+ per-group form fields consumed by ``PlacementFormParser``."""KEY_IS_INITIAL_CONNECT = 'is_initial_connect'@@ -79,8 +59,7 @@ class PlacementUrlParams:entity_ids : List[int] = field(default_factory=list)def to_query_dict(self) -> Dict[str, str]:- """Sparse query dict — keys are omitted when their value- is the default, keeping URLs free of redundant+ """Sparse query dict -- defaults are omitted, keeping URLs free of``?is_initial_connect=0`` cruft."""result : Dict[str, str] = {}if self.is_initial_connect:@@ -98,9 +77,8 @@ class PlacementUrlParams:return f'{base_url}?{urlencode(qd)}' if qd else base_urldef is_initial_connect_form_value(self) -> str:- """The hidden-form-field encoding of ``is_initial_connect``- for templates that need to round-trip the flag through a- POST."""+ """Hidden-form-field encoding of ``is_initial_connect`` for round-trip+ through a POST."""return self.TRUE_VALUE if self.is_initial_connect else self.FALSE_VALUE@classmethod@@ -148,7 +126,6 @@ class PlacementFormParser:integration_data = integration_data,)- # Discover group indices by scanning POST keys.group_indices = sorted({int(k.split('_')[2])for k in request.POST.keys()@@ -185,7 +162,7 @@ class PlacementFormParser:entity = entity, target = entity_target,) )- # Ungrouped items: no group level — entity inherits from top.+ # Ungrouped items: no group level -- entity inherits from top.ungrouped_ids = request.POST.getlist( 'ungrouped_entity_ids' )if ungrouped_ids:ungrouped = list( Entity.objects.filter(@@ -229,15 +206,9 @@ class PlacementFormParser:collection_lookup : dict,integration_data,) -> Tuple[Optional[LocationView], Optional[Collection]]:- """Top-level form value → (location_view, collection) target.-- Top values: ''=skip-all, '__new_view__'=create fresh view,- '__new_collection__'=create fresh collection,- 'view:<id>'=existing view, 'collection:<id>'=existing- collection. Creating a new view/collection is the side- effect of the corresponding sentinel; the new object- becomes the top default for everything else.- """+ """Top-level form value -> (location_view, collection) target. Creating+ a new view/collection is the side effect of the corresponding sentinel;+ the new object then becomes the top default for everything else."""if top_value == cls.FORM_VALUE_NEW_VIEW:return cls._create_new_view(request = request, integration_data = integration_data,@@ -262,12 +233,10 @@ class PlacementFormParser:view_lookup : dict,collection_lookup : dict,) -> Tuple[Optional[LocationView], Optional[Collection]]:- """Group/entity form value → (location_view, collection)- target. Empty inherits from parent; '__skip__' overrides- any inherited parent value with skip; otherwise it's a- tagged existing-target id ('view:<id>' or 'collection:<id>').- Group/entity dropdowns do not offer the new-* sentinels —- only the top level can create a new target."""+ """Group/entity form value -> (location_view, collection) target.+ Empty inherits from parent; ``__skip__`` overrides inheritance.+ Group/entity dropdowns do not offer the new-* sentinels -- only the+ top level can create a new target."""if form_value == '':return parent_targetif form_value == cls.FORM_VALUE_SKIP:@@ -299,10 +268,9 @@ class PlacementFormParser:@classmethoddef _create_new_view( cls, request, integration_data ) -> LocationView:- """Create a single LocationView named after the integration- label, attached to the operator's current default Location.- ``LocationManager.create_location_view`` handles name- collisions via its built-in disambiguation."""+ """Create a single LocationView named after the integration label,+ attached to the operator's current default Location. Name collisions+ are handled by LocationManager's built-in disambiguation."""try:location = LocationManager().get_default_location( request = request )except Location.DoesNotExist:@@ -316,9 +284,8 @@ class PlacementFormParser:@classmethoddef _create_new_collection( cls, integration_data ) -> Collection:- """Create a single Collection named after the integration- label. ``CollectionManager.create_collection`` handles name- collisions via its built-in disambiguation."""+ """Create a single Collection named after the integration label. Name+ collisions are handled by CollectionManager's built-in disambiguation."""return CollectionManager().create_collection(name = integration_data.label,)diff --git a/src/hi/integrations/placement_stats.py b/src/hi/integrations/placement_stats.pyindex 2147cc7e..d2915000 100644--- a/src/hi/integrations/placement_stats.py+++ b/src/hi/integrations/placement_stats.py@@ -35,9 +35,9 @@ from hi.apps.entity.entity_placement import EntityPlacementInputlogger = logging.getLogger(__name__)-# Default viability thresholds. Tuned for the tens-of-items import-# batches the placement modal sees today. Exposed as constants so-# callers can read them and override individual ones per-call.+# Default viability thresholds tuned for the tens-of-items batches+# typical of integration imports. Exposed as constants so callers can+# read them and override individual ones per-call.DEFAULT_MIN_COVERAGE : float = 0.5 # at least half the items must land in a named groupDEFAULT_MIN_GROUP_COUNT : int = 2 # at least two distinct groupsDEFAULT_MAX_GROUP_COUNT : int = 15 # too many groups overwhelms the modal@@ -49,11 +49,10 @@ DEFAULT_MAX_CONCENTRATION : float = 0.9 # a single group holding >90% isn't grclass PlacementGroupingStats:"""Single-pass measurements over an ``EntityPlacementInput``.- "Grouped items" are items in any named group, including a- fallback group like "Untagged". "Ungrouped items" are items- in ``EntityPlacementInput.ungrouped_items`` — the items the- modal renders under its built-in 'Other items' section, which- by convention means the integration found no signal for them.+ "Grouped items" are items in any named group, including a fallback+ group like "Untagged". "Ungrouped items" are items in+ ``EntityPlacementInput.ungrouped_items`` -- by convention, items for+ which the integration found no signal."""total_items : intgrouped_items : int@@ -70,9 +69,8 @@ class PlacementGroupingStats:@propertydef concentration(self) -> float:- """Largest group size as a fraction of grouped items. Close- to 1.0 means one dominant group — the strategy isn't really- partitioning."""+ """Largest group size as a fraction of grouped items. Close to 1.0+ means one dominant group -- the strategy isn't really partitioning."""if self.grouped_items == 0:return 0.0return self.largest_group_size / self.grouped_itemsdiff --git a/src/hi/integrations/templates/integrations/connector/panes/connect_attribute_actions.html b/src/hi/integrations/templates/integrations/connector/panes/connect_attribute_actions.htmlindex f668bc1c..48593bec 100644--- a/src/hi/integrations/templates/integrations/connector/panes/connect_attribute_actions.html+++ b/src/hi/integrations/templates/integrations/connector/panes/connect_attribute_actions.html@@ -1,10 +1,9 @@{% comment %}Attribute-form action-bar fragment for the CONNECT capability:health-status badge linking to the health-detail modal. Rendered-when ``health_status`` is in scope (the CONNECT manage view passes-it; modals that include this body do not).+only when ``health_status`` is in scope.-Context (inherited from the surrounding edit body):+Context:health_status : HealthStatus (optional)integration_data : IntegrationData (required){% endcomment %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/integration_health_banner.html b/src/hi/integrations/templates/integrations/connector/panes/integration_health_banner.htmlindex 6a5007af..f9696b29 100644--- a/src/hi/integrations/templates/integrations/connector/panes/integration_health_banner.html+++ b/src/hi/integrations/templates/integrations/connector/panes/integration_health_banner.html@@ -1,11 +1,10 @@{% load icons %}{% comment %}-Integration health banner — surfaces WARNING / ERROR / DISABLED states+Integration health banner -- surfaces WARNING / ERROR / DISABLED statesin any UI that depends on an integration's data. Renders nothing whenthe integration is HEALTHY or when health_status is unavailable.-Parameters (supplied by the ``integration_health_banner`` template-tag):+Context:health_status : HealthStatus instance, or None.integration_label : Display label for the integration (e.g.,"Home Assistant").@@ -15,8 +14,8 @@ tag):stale; controls may not respond.").Styling defers to HealthStatus.status_alert_class (Bootstrap alert-variant) and status_icon (icon name) so the visual treatment matches-the rest of the health-status UI in the application.+variant) and status_icon (icon name) for consistency with the rest+of the health-status UI.{% endcomment %}{% if health_status and not health_status.is_healthy %}<div class="alert {{ health_status.status_alert_class }} d-flex align-items-start mb-3 py-2"diff --git a/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html b/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.htmlindex cda29756..78f86a16 100644--- a/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html+++ b/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html@@ -1,26 +1,23 @@{% load icons %}{% comment %}-Compact integration-status indicator — small icon + tooltip, no label.+Compact integration-status indicator -- small icon + tooltip, no label.Composes HealthStatus, the integration's is_paused flag, and the-Issue #283 sync-check state into a single attention-grabbing glyph-for the sidebar nav-tab.+sync-check state into a single attention-grabbing glyph.-Parameters:+Context:health_status : HealthStatus instance (required).- is_paused : bool — integration's is_paused flag (required).- sync_check_result : SyncCheckResult or None (optional) — Issue #283- sync-check state for this integration.+ is_paused : bool -- integration's is_paused flag (required).+ sync_check_result : SyncCheckResult or None (optional) -- sync-check+ state for this integration.Visual priority (worst-of):ERROR > WARNING > paused > needs-sync-HEALTHY-and-not-paused-and-in-sync renders nothing — sidebar should-be visually clean when there is nothing to draw the operator's-attention to.+HEALTHY-and-not-paused-and-in-sync renders nothing.-DISABLED is intentionally not handled — disabled integrations are-excluded from the sidebar tab list upstream.+DISABLED is intentionally not handled -- disabled integrations are+excluded from the tab list upstream.-UNKNOWN is intentionally not handled — initialization edge, transient.+UNKNOWN is intentionally not handled -- initialization edge, transient.{% endcomment %}{% if health_status %}{% with status=health_status.status %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html b/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.htmlindex 97b54668..6151af94 100644--- a/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html+++ b/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html@@ -1,11 +1,7 @@{% load icons %}{% comment %}- Shared Pause/Resume lifecycle actions fragment.-- Integrations that have monitors and want to expose Pause/Resume controls- should include this fragment from their per-integration manage template- alongside any other integration-specific controls (e.g., SYNC). Rendering- is conditional on is_enabled so the control is hidden for not-yet-+ Shared Pause/Resume lifecycle actions fragment. Rendering is+ conditional on is_enabled, so the control is hidden for not-yet-configured integrations.{% endcomment %}{% if core.integration_data.is_enabled %}diff --git a/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html b/src/hi/integrations/templates/integrations/connector/panes/sync_actions.htmlindex 3d265fd8..66941f78 100644--- a/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html@@ -3,20 +3,19 @@Shared CONNECT / UPDATE framework action.Sync is a framework concern; integrations participate by providing an- IntegrationConnector from their gateway's get_connector().- Rendering is conditional on (a) the integration being enabled and- (b) the gateway returning a connector. Integrations whose gateway- returns None (sync is opt-in) get no button.+ IntegrationConnector from their gateway's get_connector(). Rendering+ is conditional on (a) the integration being enabled and (b) the+ gateway returning a connector. Integrations whose gateway returns+ None (sync is opt-in) get no button.Label flips on `core.has_entities`: CONNECT for the first-time path,- UPDATE for subsequent re-syncs. The framework manage- view computes has_entities into the `core` context.+ UPDATE for subsequent re-syncs.- When the Issue #283 sync-check probe has detected upstream drift- (`core.sync_check_result.needs_sync`), the update-check variant- promotes from outline-secondary to solid btn-primary so it pulls- the eye. The CONNECT variant is always primary since there is- nothing to compare against on a first run.+ When the sync-check probe has detected upstream drift+ (`core.sync_check_result.needs_sync`), the update variant promotes+ from outline-secondary to solid btn-primary so it pulls the eye.+ The CONNECT variant is always primary since there is nothing to+ compare against on a first run.{% endcomment %}{% if core.integration_data.is_enabled and core.integration_data.integration_gateway.get_connector %}<a href="{% url 'integrations_connect_pre_sync' integration_id=core.integration_data.integration_id %}"diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.pyindex 4b32e802..1a312eec 100644--- a/src/hi/integrations/transient_models.py+++ b/src/hi/integrations/transient_models.py@@ -9,8 +9,8 @@ from .enums import IntegrationAttributeType, IntegrationCapability@dataclassclass IntegrationMetaData:- integration_id : str # An identifier that must be unique across all integrations- label : str # For human-friendly displaying+ integration_id : str # unique across all integrations+ label : strattribute_type : IntegrationAttributeTypeallow_entity_deletion : boolallow_internal_attributes : bool = True@@ -45,15 +45,12 @@ class IntegrationKey:external names/identifiers"""- integration_id : str # Internally defined unique identifier for the integration source- integration_name : str # Name or identifier that is used by the external source.+ integration_id : str+ integration_name : strdef __post_init__(self):- # Make matching more robust by canonicalizing both fields.- # The exact rule (currently lowercase) lives in normalize() so- # external callers comparing raw strings against stored- # integration_name values can apply the same rule without- # constructing a full IntegrationKey.+ # Canonicalize both fields so matching is robust against case variation+ # in external names.self.integration_id = self.normalize( self.integration_id )self.integration_name = self.normalize( self.integration_name )return@@ -61,13 +58,11 @@ class IntegrationKey:@staticmethoddef normalize( value : str ) -> str:"""Canonical normalization applied to ``integration_id`` and- ``integration_name``. Exposed so callers that need to compare- raw strings against stored values can apply exactly the same- rule without constructing full IntegrationKey instances. Most- comparisons should go through full ``IntegrationKey`` objects- and rely on the dataclass's ``__hash__`` / ``__eq__`` (which- also use this rule); this static is the escape hatch for- cases where a one-shot string normalization is enough."""+ ``integration_name``. Exposed so callers can apply the same rule when+ comparing raw strings against stored values, without constructing a+ full IntegrationKey. Prefer full ``IntegrationKey`` objects when+ possible (``__hash__`` / ``__eq__`` use this rule); this static is the+ escape hatch for one-shot string normalization."""return value.lower()def __str__(self):@@ -96,21 +91,15 @@ class IntegrationKey:@dataclassclass IntegrationDetails:- """- Integration key plus data for cases where additional integration-specific- data is needed- """+ """IntegrationKey plus an optional payload of integration-specific data."""key : IntegrationKeypayload : Optional[Dict] = None@dataclassclass IntegrationRemovalSummary:- """- Classification of an integration's attached entities for the Remove- confirmation dialog. Raw counts only; derived values are properties so- the object stays consistent.- """+ """Classification of an integration's attached entities: raw counts+ only, with derived values as properties so the object stays consistent."""total_count: intuser_data_count: int@@ -121,24 +110,16 @@ class IntegrationRemovalSummary:@propertydef has_mixed_state(self) -> bool:- """- True when at least one entity has user data. Drives the dialog- decision between a single DELETE action and the DELETE SAFE /- DELETE ALL variants.- """+ """True when at least one entity has user data."""return self.user_data_count > 0@dataclassclass ConnectionTestResult:- """- Result from a live integration connection probe.-- Distinct from IntegrationValidationResult, which represents schema-level- validation outcomes. ConnectionTestResult specifically reports whether- a network probe against the proposed configuration succeeded within a- bounded timeout.- """+ """Result from a live integration connection probe (network probe with+ bounded timeout against the proposed configuration). Distinct from+ ``IntegrationValidationResult``, which represents schema-level validation+ outcomes."""is_success : boolmessage : Optional[str] = None@@ -154,7 +135,6 @@ class ConnectionTestResult:@dataclassclass IntegrationValidationResult:- """Result from integration configuration validation."""is_valid : boolstatus : HealthStatusType@@ -168,7 +148,6 @@ class IntegrationValidationResult:@classmethoddef success(cls) -> 'IntegrationValidationResult':- """Create a successful validation result."""return cls(is_valid=True,status=HealthStatusType.HEALTHY@@ -176,7 +155,6 @@ class IntegrationValidationResult:@classmethoddef error(cls, status: HealthStatusType, error_message: str) -> 'IntegrationValidationResult':- """Create an error validation result."""return cls(is_valid=False,status=status,diff --git a/src/hi/integrations/view_mixins.py b/src/hi/integrations/view_mixins.pyindex e5b2ac64..49eb3dd6 100644--- a/src/hi/integrations/view_mixins.py+++ b/src/hi/integrations/view_mixins.py@@ -19,20 +19,15 @@ from hi.integrations.placement_request import PlacementUrlParamsclass CapabilityBlockViewMixin:- """Block IMPORT initiation when the integration has active- Connect entities, directing the user to disable the integration- first.-- The asymmetry is principled. CONNECT does not need a symmetric- block: sync's reconnect-then-create order will adopt any pre-- existing detached/imported rows for the same integration into- the live Connect session, so no collision is possible. IMPORT- creates new HI-owned rows, which would collide with active-- Connect rows unless we block this entry point.-- Mixed into the IMPORT-side Configure view; CONNECT-side views- can either omit the mixin or call this method as a no-op for- capability=CONNECT.+ """Block IMPORT initiation when the integration has active Connect+ entities, directing the user to disable the integration first.++ The asymmetry is principled. CONNECT does not need a symmetric block:+ sync's reconnect-then-create order will adopt any pre-existing+ detached/imported rows for the same integration into the live Connect+ session, so no collision is possible. IMPORT creates new HI-owned rows,+ which would collide with active-Connect rows unless we block this entry+ point."""def render_capability_block_if_conflict(@@ -41,9 +36,6 @@ class CapabilityBlockViewMixin:integration_data,capability_being_initiated : IntegrationCapability,):- # CONNECT initiation cannot collide; the reconnect path- # adopts any existing provenance entities. Only IMPORT- # initiation needs blocking.if capability_being_initiated != IntegrationCapability.IMPORT:return Nonecapabilities = integration_data.integration_metadata.capabilities@@ -84,11 +76,8 @@ class IntegrationViewMixin:def get_integration_data( self, request, *args, **kwargs ):"""Resolve the URL-routed integration_id to its IntegrationData.- Assumes there is a required ``integration_id`` in kwargs;- raises BadRequest if missing and Http404 if not registered.- Mirrors EntityViewMixin.get_entity's signature so views can- chain helpers uniformly.- """+ Requires ``integration_id`` in kwargs; raises BadRequest if missing+ and Http404 if not registered."""integration_id = kwargs.get('integration_id')if not integration_id:raise BadRequest('Missing integration id.')@@ -115,38 +104,32 @@ class IntegrationViewMixin:error_title ):"""Validate the proposed integration configuration in two stages:- 1. Schema-level check via gateway.validate_configuration (offline,- fast). Catches structural problems with the attribute set.- 2. Live access validation via gateway.validate_access bounded- by IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS. Catches- unreachable upstream / bad credentials so the user sees the- specific reason inline rather than experiencing a silent- save followed by a delayed background error.-- Both gateway methods are required by their contracts to never- throw — they convert any internal exception into the appropriate- result type (IntegrationValidationResult.error /- ConnectionTestResult.failure) carrying a human-readable message.- We deliberately do NOT wrap their invocations in a broad try/- except here: doing so would coerce the gateway's specific- failure message into a generic catch-all string, and would also- hide genuine programming bugs (which should surface through- Django's error pipeline rather than be silently translated into- a form-level error).+ 1. Schema-level check (offline, fast). Catches structural problems+ with the attribute set.+ 2. Live access validation with bounded timeout. Catches unreachable+ upstream / bad credentials so the user sees the specific reason+ inline rather than experiencing a silent save followed by a delayed+ background error.++ Both gateway methods are contractually required to never throw -- they+ convert any internal exception into the appropriate result type+ carrying a human-readable message. We deliberately do NOT wrap their+ invocations in a broad try/except here: that would coerce the gateway's+ specific failure message into a generic catch-all string, and would+ hide genuine programming bugs (which should surface through Django's+ error pipeline rather than be silently translated into a form-level+ error)."""integration_data = attr_item_context.integration_datagateway = integration_data.integration_gateway- # Get current attribute values from the formsetintegration_attributes = []for form in regular_attributes_formset:if form.cleaned_data and not form.cleaned_data.get('DELETE', False):- # Create a temporary attribute-like object with the form dataattr_instance = form.instanceattr_instance.value = form.cleaned_data.get('value', '')integration_attributes.append(attr_instance)- # Stage 1: schema-only validation.validation_result = gateway.validate_configuration(integration_attributes)@@ -157,7 +140,6 @@ class IntegrationViewMixin:)return- # Stage 2: live access validation with bounded timeout.test_result = gateway.validate_access(integration_attributes = integration_attributes,timeout_secs = IntegrationManager.HEALTH_CHECK_TIMEOUT_SECS,@@ -174,11 +156,7 @@ class IntegrationPlacementViewMixin:"""Modal context builders shared across the placement /dismiss-confirm / post-dispatch views. Knows UI conventions(URL routing for the integration placement flow, location-view- dropdown shape) but no business logic.-- Designed to be mixed into ``HiModalView`` subclasses so the- rendering methods can call ``self.modal_response(...)`` directly.- """+ dropdown shape) but no business logic."""def render_placement( self,request,@@ -186,16 +164,14 @@ class IntegrationPlacementViewMixin:placement_input,is_initial_connect : bool,entity_id_filter = None ):- """Render the placement modal seeded with an- ``EntityPlacementInput``. Dropdowns offer both LocationView- and Collection targets; the top dropdown additionally offers- '+ New view' and '+ New collection' sentinels.-- Computes two presentation aids in the view rather than the- template: a smart default for the top dropdown- (``top_default_value``) and an inventory preview line shown- beneath it (``inventory_preview``). The template is then a- thin renderer of these and the placement_input itself.+ """Render the placement modal seeded with an ``EntityPlacementInput``.+ Dropdowns offer both LocationView and Collection targets; the top+ dropdown additionally offers '+ New view' and '+ New collection'+ sentinels.++ Computes two presentation aids in the view rather than the template:+ a smart default for the top dropdown (``top_default_value``) and an+ inventory preview line shown beneath it (``inventory_preview``)."""location_view_groups = self._build_location_view_groups()collection_list = self._build_collection_list()@@ -219,17 +195,17 @@ class IntegrationPlacementViewMixin:inventory_preview = self._build_inventory_preview(placement_input = placement_input,)- # Suppress the column-header heading when the grouping- # dimension is the implicit default ("Item Type") — it- # adds no information. The heading still renders when an- # integration override conveys context (e.g. "HomeBox Location").+ # Suppress the column-header heading when the grouping dimension is+ # the implicit default ("Item Type") -- it adds no information. The+ # heading still renders when an integration override conveys context+ # (e.g. "HomeBox Location").grouping_heading = (placement_input.headingif placement_input.heading != PLACEMENT_DEFAULT_HEADINGelse None)- # The form posts back to the same URL that rendered the- # modal — single CBV, GET renders / POST processes.+ # Form posts back to the same URL that rendered the modal -- single+ # CBV, GET renders / POST processes.placement_url = reverse('integrations_placement',kwargs = { 'integration_id': integration_data.integration_id },@@ -259,11 +235,10 @@ class IntegrationPlacementViewMixin:integration_data,is_initial_connect : bool,entity_ids = None ):- """Render the NOT NOW confirmation modal. GO BACK targets- the placement GET endpoint, with is_initial_connect and- (when present) the entity-id scope threaded through as- query parameters so the operator returns to the same set- they were viewing."""+ """Render the dismiss confirmation modal. The back action targets the+ placement GET endpoint with is_initial_connect and (when present) the+ entity-id scope threaded through as query parameters so the operator+ returns to the same set they were viewing."""placement_url = PlacementUrlParams(is_initial_connect = is_initial_connect,entity_ids = list( entity_ids ) if entity_ids else [],@@ -285,17 +260,13 @@ class IntegrationPlacementViewMixin:integration_data,outcome,is_initial_connect : bool ):- """Render the post-dispatch summary modal from a- ``PlacementOutcome``.-- The primary action button is REFINE for view-targeted- primary summaries (drag entities into spatial position) and- REVIEW for collection-targeted primary summaries (no spatial- refinement; the link just lands on the collection's view- page). ``PlacementOutcome.primary_summary`` already prefers- view-targeted summaries when any exist, so the REFINE path- is taken whenever the operator placed at least one entity- into a LocationView."""+ """Render the post-dispatch summary modal from a ``PlacementOutcome``.++ The primary action targets the view-refinement endpoint for view-+ targeted primary summaries (drag entities into spatial position) and+ the collection-view page for collection-targeted primary summaries+ (no spatial refinement). ``PlacementOutcome.primary_summary`` already+ prefers view-targeted summaries when any exist."""primary = outcome.primary_summaryprimary_action = Nonesecondary_action_list = []@@ -318,14 +289,12 @@ class IntegrationPlacementViewMixin:)def _build_location_view_groups( self ):- """Existing-views dropdown source: ``[(Location,- [LocationView])]`` ordered by Location.order_id, views by- LocationView.order_id within each. Always grouped (never- flat) so multi-Location deployments can disambiguate views- with shared names. Single SQL query joining LocationView ↔- Location; insertion-order in the dict preserves the sort- from the database. Empty Locations drop out, which is the- right behavior for a dropdown source."""+ """Existing-views dropdown source: ``[(Location, [LocationView])]``+ ordered by Location.order_id, views by LocationView.order_id within+ each. Always grouped (never flat) so multi-Location deployments can+ disambiguate views with shared names. Single SQL query joining+ LocationView and Location; insertion-order in the dict preserves the+ sort from the database. Empty Locations drop out."""queryset = LocationView.objects.select_related('location').order_by('location__order_id', 'order_id',)@@ -341,10 +310,9 @@ class IntegrationPlacementViewMixin:return list( Collection.objects.order_by('order_id').all() )def _summary_url( self, summary ) -> str:- """URL for the post-dispatch modal's per-summary action.- Views go through ``integrations_refine`` (which lands the- operator in edit mode for that view); collections link to- the read-only ``collection_view`` page."""+ """URL for each per-summary action. Views go through ``integrations_refine``+ (which lands the operator in edit mode for that view); collections link+ to the read-only ``collection_view`` page."""if summary.is_view:return reverse('integrations_refine',@@ -360,15 +328,14 @@ class IntegrationPlacementViewMixin:is_initial_connect : bool ) -> str:"""Smart default for the placement's top dropdown.- On Initial Connect the operator has no existing target — pre-- select '+ New view' so they can click APPLY without further- input.+ On Initial Connect the operator has no existing target -- pre-select+ '+ New view' so they can apply without further input.- On update check, prefer whichever existing target (LocationView- OR Collection) currently holds the most entities for this- integration. Ties broken by id ascending (deterministic).- Falls back to '' (Don't place) when no existing target holds- any of this integration's entities — operator picks.+ On update check, prefer whichever existing target (LocationView OR+ Collection) currently holds the most entities for this integration.+ Ties broken by id ascending (deterministic). Falls back to '' (no+ default) when no existing target holds any of this integration's+ entities -- operator picks."""if is_initial_connect:return '__new_view__'@@ -398,10 +365,9 @@ class IntegrationPlacementViewMixin:return f'view:{top_view["location_view_id"]}'if collection_count > view_count:return f'collection:{top_collection["collection_id"]}'- # Equal counts — prefer lower target type ordinal. Views- # before collections is an arbitrary but deterministic- # tiebreak; the operator's own count was already a true- # tie so either answer is fine.+ # Equal counts -- prefer lower target type ordinal. Views before+ # collections is an arbitrary but deterministic tiebreak; the+ # operator's own count was already a true tie so either answer is fine.return f'view:{top_view["location_view_id"]}'if top_view:@@ -411,27 +377,24 @@ class IntegrationPlacementViewMixin:return ''def _derive_new_target_names( self, request, integration_label : str ) -> tuple:- """Pre-resolve the names that the '+ New view' / '+ New- collection' options would actually produce on Apply, so the- dropdown labels match the operator's eventual reality.-- Without this, an operator who already has a view named- 'Home Assistant' would see the option 'New view: "Home- Assistant"' but get a view named 'Home Assistant (2)' on- save — confusing.-- Returns ``(new_view_name, new_collection_name)``. Falls- back to ``integration_label`` for the view name when no- default Location is configured (the apply path will raise- BadRequest in that case anyway; the modal label just shows- the un-disambiguated label).-- Race-condition note: another operator could create a same-- named view/collection between render and submit, in which- case the apply-time disambiguation produces a different- suffix than the modal advertised. This is an extremely rare- case and the apply-time logic always picks a free name, so- no special handling is needed.+ """Pre-resolve the names that the '+ New view' / '+ New collection'+ options would actually produce on Apply, so the dropdown labels match+ the operator's eventual reality.++ Without this, an operator who already has a view named 'Home Assistant'+ would see the option 'New view: "Home Assistant"' but get a view named+ 'Home Assistant (2)' on save -- confusing.++ Returns ``(new_view_name, new_collection_name)``. Falls back to+ ``integration_label`` for the view name when no default Location is+ configured (the apply path will raise BadRequest in that case; the+ modal label just shows the un-disambiguated label).++ Race-condition note: another operator could create a same-named+ view/collection between render and submit, in which case the apply-time+ disambiguation produces a different suffix than the modal advertised.+ This is rare and the apply-time logic always picks a free name, so no+ special handling is needed."""try:location = LocationManager().get_default_location( request = request )@@ -449,15 +412,12 @@ class IntegrationPlacementViewMixin:def _build_inventory_preview( self, placement_input ) -> list:"""Compact label/count summary of what's about to be placed.- Used as a single-line preview beneath the top dropdown when- the operator has the group rows collapsed — preserves the- 'free preview of what's about to be imported' signal that- the always-visible group cards previously provided.+ Used as a single-line preview beneath the top dropdown when the+ operator has the group rows collapsed.- Returns an empty list for the rare truly-ungrouped case- (no groups, only ``ungrouped_items``). Callers should hide- the preview entirely in that case, since restating the- count is just noise.+ Returns an empty list for the truly-ungrouped case (no groups, only+ ``ungrouped_items``). Callers should hide the preview entirely in that+ case, since restating the count is just noise."""if not placement_input.groups:return []diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.pyindex 46dc38dd..0c66354b 100644--- a/src/hi/integrations/views.py+++ b/src/hi/integrations/views.py@@ -35,18 +35,17 @@ class CapabilityConfigureView( HiModalView,"""Base for the per-capability credentials Configure modal.Subclasses set the four class-level constants and override- ``handle_post_success`` to define what happens after credentials- save. The base owns:- * the GET render flow (block check → ensure_all_attributes_exist →- build edit context → render modal)- * the POST save flow (post_attribute_form → delegate to subclass)+ ``handle_post_success`` to define what happens after credentials save.+ The base owns:+ * the GET render flow (block check -> ensure_all_attributes_exist ->+ build edit context -> render modal)+ * the POST save flow (post_attribute_form -> delegate to subclass)* the ``validate_attributes_extra`` hook for AttributeEditViewMixin.- Subclasses own the timing of ``notify_settings_changed()`` because- the right moment is capability-specific: Connect-side managers- gate client (re)build on ``integration.is_enabled``, so the notify- must fire AFTER ``enable_integration``; Import flows fire it- before reading candidates.+ Subclasses own the timing of ``notify_settings_changed()`` because the+ right moment is capability-specific: Connect-side managers gate client+ (re)build on ``integration.is_enabled``, so the notify must fire AFTER+ ``enable_integration``; Import flows fire it before reading candidates."""capability : IntegrationCapability = None@@ -58,11 +57,10 @@ class CapabilityConfigureView( HiModalView,return self.template_namedef get_capability_gateway( self, integration_data ):- """Return the ``CapabilityGateway`` instance for this configure- view's capability. Subclasses implement by calling the- appropriate per-capability getter on the gateway. The base- class deliberately does not enumerate capabilities — each- subclass already knows its own."""+ """Return the ``CapabilityGateway`` instance for this configure view's+ capability. Subclasses implement by calling the appropriate+ per-capability getter on the gateway. The base deliberately does not+ enumerate capabilities -- each subclass already knows its own."""raise NotImplementedError('Subclasses must override this method')def _build_attr_item_context( self, integration_data ):@@ -127,7 +125,6 @@ class CapabilityConfigureView( HiModalView,attr_item_context,regular_attributes_formset,request ):- """ Override for AttributeEditViewMixin """self.validate_attributes_extra_helper(attr_item_context,regular_attributes_formset,@@ -138,21 +135,19 @@ class CapabilityConfigureView( HiModalView,class IntegrationPlacementView( HiModalView, IntegrationViewMixin,IntegrationPlacementViewMixin ):- """Placement modal — single CBV handling both the GET (render)- and POST (form submission) paths on one URL.+ """Placement modal -- single CBV handling both the GET (render) and+ POST (form submission) paths on one URL.GET queries currently-unplaced entities for the integration- (optionally scoped by ``entity_ids`` URL param), runs them- through the connector's ``group_entities_for_placement``,- and renders the placement modal. Empty result falls back to- a brief acknowledgement modal so the operator isn't dropped- onto an empty placement.-- POST processes the placement form. The form has two submit- buttons — APPLY and NOT NOW — sharing ``name="action"`` with- distinct values; this view branches on the value to render- either the post-dispatch summary modal (apply path) or the- dismiss-confirm modal (not-now path).+ (optionally scoped by ``entity_ids`` URL param), runs them through+ the connector's ``group_entities_for_placement``, and renders the+ placement modal. Empty result falls back to a brief acknowledgement+ modal so the operator isn't dropped onto an empty placement.++ POST processes the placement form. The form has two submit buttons+ sharing ``name="action"`` with distinct values (apply vs dismiss);+ this view branches on the value to render either the post-dispatch+ summary modal or the dismiss-confirm modal."""DISMISS_ACTION_VALUE = 'dismiss'@@ -173,10 +168,9 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,entities = EntityPlacementService.query_unplaced_entities(integration_id = integration_data.integration_id,)- # When the caller scoped the URL to specific entity ids- # (sync-result CTA), narrow the unplaced set to those.- # Without scoping, the placement operates on the full- # unplaced set for the integration (recovery flow).+ # When the caller scoped the URL to specific entity ids, narrow the+ # unplaced set to those. Without scoping, the placement operates on the+ # full unplaced set for the integration.if entity_id_filter is not None:entities = [ e for e in entities if e.id in entity_id_filter ]@@ -225,11 +219,10 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,@staticmethoddef _extract_placement_entity_ids( request ):- """Pull the entity ids the placement form just posted.- The placement renders ``all_group_<i>_entity_ids`` per- group plus a single ``ungrouped_entity_ids`` field — both- carry the entity ids regardless of whether the operator- opened any drill-down."""+ """Pull the entity ids the placement form just posted. The form+ renders ``all_group_<i>_entity_ids`` per group plus a single+ ``ungrouped_entity_ids`` field -- both carry the entity ids regardless+ of whether the operator opened any drill-down."""ids = []for key, values in request.POST.lists():if key == 'ungrouped_entity_ids' or (@@ -245,10 +238,9 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,def _render_empty( self, request, integration_data,connector, is_initial_connect : bool ):- """No-unplaced-items acknowledgement: render the result- modal with the integration's icon + a brief 'no items'- info note rather than an empty placement. Counts stay- zero so the modal lead reads 'Nothing new.'"""+ """No-unplaced-items acknowledgement: render the result modal with+ the integration's icon and a brief 'no items' info note rather than+ an empty placement."""sync_result = IntegrationSyncResult(title = connector.get_result_title(is_initial_connect = is_initial_connect,@@ -267,12 +259,9 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,class IntegrationRefineView( View ):- """- Convenience entry to edit-mode for a specific LocationView,- used by the post-dispatch modal's REFINE button(s). Sets the- session's current LocationView, flips view mode to EDIT, and- redirects to the location view page.- """+ """Convenience entry to edit-mode for a specific LocationView. Sets the+ session's current LocationView, flips view mode to EDIT, and redirects+ to the location view page."""def get(self, request, *args, **kwargs):try:@@ -327,7 +316,6 @@ class IntegrationAttributeHistoryInlineView( View,class IntegrationAttributeRestoreInlineView( View,IntegrationViewMixin,AttributeEditViewMixin ):- """View for restoring IntegrationAttribute values from history inline."""def get(self, request, integration_id, attribute_id, history_id, *args, **kwargs):""" Need to do restore in a GET since nested in main form and cannot have a form in a form """diff --git a/src/hi/simulator/services/apps.py b/src/hi/simulator/services/apps.pyindex 3c5b9d3c..e3069bea 100644--- a/src/hi/simulator/services/apps.py+++ b/src/hi/simulator/services/apps.py@@ -13,6 +13,18 @@ class ServicesConfig( AppConfig ):from hi.apps.common.asyncio_utils import start_background_event_loopfrom .service_simulator_manager import ServiceSimulatorManager+ # Counterintuitive: Django's AppConfig.ready() does not behave the way+ # the docs suggest. The two surprises that drive the guards below:+ #+ # 1. Under runserver, Django itself spawns multiple processes during+ # initialization — not because workers are configured, but as part+ # of normal startup — and ready() runs in each one. RUN_MAIN is set+ # only in the worker that serves requests; the other invocations+ # must bail out to avoid duplicate startup.+ #+ # 2. Under gunicorn, ready() does not run at all. Equivalent startup+ # is delegated to gunicorn's post_fork hook.+if os.environ.get('RUN_MAIN') != 'true':returndiff --git a/src/hi/static/css/attribute.css b/src/hi/static/css/attribute.cssindex 452f0a11..f4665da4 100644--- a/src/hi/static/css/attribute.css+++ b/src/hi/static/css/attribute.css@@ -1,4 +1,4 @@-/* Attribute V2 System Styles - Fresh Start */+/* Attribute V2 System Styles *//* Container Structure */.attr-v2-container {@@ -133,7 +133,7 @@resize: vertical;}-/* Section Titles - Reduced size to match mockup */+/* Section Titles */.attr-v2-section-title {font-size: 0.875rem;font-weight: 600;@@ -800,7 +800,7 @@flex-wrap: wrap;}- /* Attrribute actions stack vertically */+ /* Attribute actions stack vertically */.attr-v2-attribute-actions {flex-direction: column;gap: 0.25rem;@@ -938,7 +938,7 @@}}-/* Add Attrribute Form */+/* Add Attribute Form */.attr-v2-add-form {border: 1px solid var(--line-color);border-radius: 0.375rem;@@ -1159,7 +1159,7 @@animation: pulse 2s infinite;}-/* Attrribute name dirty styling - fallback approach for broader browser support */+/* Attribute name dirty styling - fallback approach for broader browser support */.attr-v2-attribute-name.has-dirty-indicator {font-weight: 600;color: var(--warning-color);@@ -1588,7 +1588,7 @@background: rgba(220, 53, 69, 0.05);}-/* Attrribute Card Deletion Styling */+/* Attribute Card Deletion Styling */.attr-v2-attribute-card.marked-for-deletion {position: relative;background: rgba(220, 53, 69, 0.05);@@ -1633,10 +1633,10 @@}/* ====================================================================== */-/* ENTITY EDIT MODAL V2 STYLING IMPROVEMENTS */+/* ENTITY EDIT MODAL V2 STYLING *//* ====================================================================== */-/* Task 1: Standardize delete icon colors to red */+/* Delete icon colors standardized to red */.attr-v2-attribute-actions .attr-v2-delete-btn {color: #dc3545 !important;border-color: #dc3545 !important;@@ -1647,7 +1647,7 @@color: white !important;}-/* Task 2: Style "Add New Attrribute" form for visual distinction */+/* "Add New Attribute" form -- visual distinction */.attr-v2-new-attribute {background-color: rgba(23, 112, 114, 0.05) !important;border: 2px dashed rgba(23, 112, 114, 0.3) !important;@@ -1661,7 +1661,7 @@}-/* Task 3: Make Add File and Add Attrribute buttons consistent size */+/* Add File and Add Attribute buttons -- consistent size */.attr-v2-action-buttons label.btn {min-height: 44px;padding: 0.375rem 0.75rem;@@ -1674,7 +1674,7 @@cursor: pointer;}-/* Task 4: Make attribute name/labels more prominent than values */+/* Attribute names/labels -- more prominent than values */.attr-v2-attribute-name {font-size: 0.9rem !important;font-weight: 600 !important;@@ -1787,14 +1787,14 @@}/* Zero the modal-body's top padding so the sticky search form is flush- against the title — otherwise modal-body's default padding-top shows+ against the title -- otherwise modal-body's default padding-top showsscrolling content through the gap above the sticky element. Thesearch form supplies its own padding-top for breathing room. */.hi-attr-picker .modal-body {padding-top: 0;}-/* Source banner — always rendered. With one source the button is+/* Source banner -- always rendered. With one source the button isdisabled (no caret, no hover affordance) so the visual matchesthe multi-source case structurally but doesn't invite a clickthat does nothing useful. The button face shows the source'sdiff --git a/src/hi/static/js/attr-dirty-tracking.js b/src/hi/static/js/attr-dirty-tracking.jsindex 114033c6..a5283279 100644--- a/src/hi/static/js/attr-dirty-tracking.js+++ b/src/hi/static/js/attr-dirty-tracking.js@@ -6,13 +6,10 @@(function() {'use strict';-- // Internal constants - dirty tracking specific+const DIRTY_TRACKING_INTERNAL = {- // ConfigurationDEBOUNCE_DELAY: 300,-- // Messages+SINGLE_FIELD_MESSAGE: '1 field modified',MULTIPLE_FIELDS_MESSAGE_TEMPLATE: '{count} fields modified',DIRTY_INDICATOR_CHAR: '●',@@ -21,20 +18,17 @@FIELD_DIRTY_CLASS: 'attr-v2-field-dirty',DIRTY_INDICATOR_CLASS: 'attr-v2-dirty-indicator',};-- // Create namespace+window.Hi = window.Hi || {};window.Hi.attr = window.Hi.attr || {};-+/**- * DirtyTracker Class - Container-specific instance- * Each editing context gets its own isolated tracker+ * Each editing context gets its own isolated DirtyTracker instance.*/function DirtyTracker(containerId) {this.containerId = containerId;this.container = document.getElementById(containerId);-- // Instance-specific configuration+this.config = {formSelector: Hi.ATTR_V2_FORM_CLASS_SELECTOR,messageContainerSelector: Hi.ATTR_V2_DIRTY_MESSAGE_SELECTOR,@@ -42,8 +36,7 @@dirtyFieldClass: DIRTY_TRACKING_INTERNAL.FIELD_DIRTY_CLASS,dirtyIndicatorClass: DIRTY_TRACKING_INTERNAL.DIRTY_INDICATOR_CLASS};-- // Instance-specific state+this.state = {originalValues: new Map(),dirtyFields: new Set(),@@ -51,36 +44,33 @@isInitialized: false};}-+DirtyTracker.prototype = {- // Initialize the dirty tracking system for this containerinit: function() {if (this.state.isInitialized || !this.container) {return;}-+const form = this.container.querySelector(this.config.formSelector);if (!form) {return;}-+this.captureOriginalValues();this.bindEvents();this.state.isInitialized = true;},-- // Capture original values for all form fields in this container+captureOriginalValues: function() {const form = this.container.querySelector(this.config.formSelector);if (!form) return;-+// Entity/Location name fieldconst nameField = form.querySelector('input[name$="name"]:not([name*="-"])');if (nameField) {this.captureFieldValue(nameField);}-- // Attribute form fields+const attributeFields = form.querySelectorAll(`${Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR} input, ${Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR} textarea, ${Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR} select`);attributeFields.forEach(field => {// Skip hidden management form fields@@ -93,24 +83,21 @@orderFields.forEach(field => {this.captureFieldValue(field);});-- // File title input fields+const fileTitleFields = form.querySelectorAll(Hi.ATTR_V2_FILE_TITLE_INPUT_SELECTOR);fileTitleFields.forEach(field => {this.captureFieldValue(field);});},-- // Capture individual field value+captureFieldValue: function(field) {if (!field.name || !field.id) return;-+let originalValue = this.getFieldValue(field);this.state.originalValues.set(field.id, originalValue);field.setAttribute('data-original-value', originalValue);},-- // Get normalized field value+getFieldValue: function(field) {if (field.type === 'checkbox') {return field.checked ? 'true' : 'false';@@ -120,83 +107,74 @@return (field.value || '').trim();}},-- // Check if field has changed+hasFieldChanged: function(field) {const originalValue = this.state.originalValues.get(field.id);const currentValue = this.getFieldValue(field);-+// Special handling for new attribute forms - consider them dirty if they have contentconst isNewAttributeField = field.closest(Hi.ATTR_V2_NEW_ATTRIBUTE_SELECTOR);if (isNewAttributeField && field.name.includes('-name') && currentValue.length > 0) {return true;}-+return originalValue !== currentValue;},-+// Bind event listeners scoped to this container using event delegationbindEvents: function() {const $container = $(`#${this.containerId}`);const form = $container.find(this.config.formSelector);if (form.length === 0) return;-+// Remove any existing dirty tracking event handlers to avoid duplicates$container.off('.dirty-tracking');-- // Text input changes with debouncing - use event delegation+this.bindDebouncedEvents($container, 'input[type="text"], input[type="password"], input[type="number"], textarea', 'input');-- // Immediate changes for selects and checkboxes - use event delegation+this.bindImmediateEvents($container, 'select, input[type="checkbox"]', 'change');-- // Form submission handling - delegate to container+$container.on('submit.dirty-tracking', this.config.formSelector, this.handleFormSubmission.bind(this));-- // Handle file title input activation - delegate to container++ // Handle file title input activation on focus.$container.on('focus.dirty-tracking', '.' + Hi.ATTR_V2_FILE_TITLE_INPUT_CLASS, (e) => {$(e.target).addClass('activated');});},-- // Bind debounced events for text inputs using jQuery event delegation+bindDebouncedEvents: function($container, selector, eventType) {const handler = (e) => {const field = e.target;const fieldId = field.id;-+if (!fieldId) return;-- // Clear existing timer+if (this.state.debounceTimers.has(fieldId)) {clearTimeout(this.state.debounceTimers.get(fieldId));}-- // Set new timer+const timer = setTimeout(() => {this.handleFieldChange(field);this.state.debounceTimers.delete(fieldId);}, this.config.debounceDelay);-+this.state.debounceTimers.set(fieldId, timer);};-+$container.on(`${eventType}.dirty-tracking`, selector, handler);},-- // Bind immediate events for selects and checkboxes using jQuery event delegation+bindImmediateEvents: function($container, selector, eventType) {const handler = (e) => {this.handleFieldChange(e.target);};-+$container.on(`${eventType}.dirty-tracking`, selector, handler);},-- // Handle individual field change+handleFieldChange: function(field) {const hasChanged = this.hasFieldChanged(field);-+if (hasChanged) {this.markFieldDirty(field);this.state.dirtyFields.add(field.id);@@ -204,73 +182,63 @@this.clearFieldDirty(field);this.state.dirtyFields.delete(field.id);}-+this.updateMessageArea();},-- // Mark field as dirty with visual indicators+markFieldDirty: function(field) {field.classList.add(this.config.dirtyFieldClass);-+// For file title inputs, add activated class for persistent stylingif (field.classList.contains(Hi.ATTR_V2_FILE_TITLE_INPUT_CLASS)) {field.classList.add('activated');}-- // Add indicator to field container+const container = this.getFieldContainer(field);if (container && !container.querySelector('.' + this.config.dirtyIndicatorClass)) {const indicator = this.createDirtyIndicator();this.insertDirtyIndicator(container, indicator);-+// Add fallback CSS classes for browsers without :has() supportthis.addFallbackClasses(container, field);}},-- // Clear dirty state from field+clearFieldDirty: function(field) {field.classList.remove(this.config.dirtyFieldClass);-- // Remove indicator+const container = this.getFieldContainer(field);if (container) {const indicator = container.querySelector('.' + this.config.dirtyIndicatorClass);if (indicator) {indicator.remove();}-- // Remove fallback CSS classes+this.removeFallbackClasses(container, field);}},-- // Get appropriate container for field indicator+getFieldContainer: function(field) {- // For file title inputs, use the file info containerif (field.classList.contains(Hi.ATTR_V2_FILE_TITLE_INPUT_CLASS)) {const fileInfo = field.closest(Hi.ATTR_V2_FILE_INFO_SELECTOR);if (fileInfo) {return field; // Use the input itself as container for positioning}}-- // For attribute cards, use the attribute header+const attributeCard = field.closest(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);if (attributeCard) {return attributeCard.querySelector(Hi.ATTR_V2_ATTRIBUTE_NAME_SELECTOR);}-- // For entity name, use the form group+const formGroup = field.closest('.form-group');if (formGroup) {return formGroup.querySelector('small, label') || formGroup;}-+return field.parentElement;},-- // Create dirty indicator element+createDirtyIndicator: function() {const indicator = document.createElement('span');indicator.className = this.config.dirtyIndicatorClass;@@ -278,73 +246,61 @@indicator.title = DIRTY_TRACKING_INTERNAL.DIRTY_INDICATOR_TITLE;return indicator;},-- // Insert dirty indicator in appropriate position+insertDirtyIndicator: function(container, indicator) {- // For attribute names, append to the endif (container.classList.contains(Hi.ATTR_V2_ATTRIBUTE_NAME_CLASS)) {container.appendChild(indicator);} else {- // For other containers, insert at the endcontainer.appendChild(indicator);}},-+// Add fallback CSS classes for browsers without :has() supportaddFallbackClasses: function(container, field) {- // For attribute namesif (container.classList.contains(Hi.ATTR_V2_ATTRIBUTE_NAME_CLASS)) {container.classList.add('has-dirty-indicator');}-- // For form groups (entity name)+const formGroup = field.closest('.form-group');if (formGroup) {formGroup.classList.add('has-dirty-field');}},-- // Remove fallback CSS classes+removeFallbackClasses: function(container, field) {- // For attribute namesif (container.classList.contains(Hi.ATTR_V2_ATTRIBUTE_NAME_CLASS)) {container.classList.remove('has-dirty-indicator');}-- // For form groups (entity name)+const formGroup = field.closest('.form-group');if (formGroup) {formGroup.classList.remove('has-dirty-field');}},-- // Update message area with current dirty state (scoped to this container)+updateMessageArea: function() {// Get fresh reference to container (important for modal scenarios)this.container = document.getElementById(this.containerId);const messageContainer = this.container ? this.container.querySelector(this.config.messageContainerSelector) : null;if (!messageContainer) return;-+const dirtyCount = this.state.dirtyFields.size;const isDirty = dirtyCount > 0;-- // Update message area+if (dirtyCount === 0) {messageContainer.textContent = '';messageContainer.className = Hi.ATTR_V2_DIRTY_MESSAGE_CLASS;} else {- const message = dirtyCount === 1+ const message = dirtyCount === 1? DIRTY_TRACKING_INTERNAL.SINGLE_FIELD_MESSAGE: DIRTY_TRACKING_INTERNAL.MULTIPLE_FIELDS_MESSAGE_TEMPLATE.replace('{count}', dirtyCount);messageContainer.textContent = message;messageContainer.className = `${Hi.ATTR_V2_DIRTY_MESSAGE_CLASS} active`;}-- // Update button prominence+this.updateButtonProminence(isDirty);},-- // Update UPDATE button prominence based on dirty state+updateButtonProminence: function(isDirty) {const $updateButton = $(this.container).find(Hi.ATTR_V2_UPDATE_BTN_SELECTOR);if ($updateButton.length === 0) return;@@ -355,31 +311,28 @@$updateButton.removeClass('form-dirty');}},-- // Handle form submission+handleFormSubmission: function(e) {// Handle textarea sync for truncated/hidden field patternthis.syncDisplayToHiddenFields();},-- // Sync display fields to hidden fields before submission+syncDisplayToHiddenFields: function() {const form = this.container.querySelector(this.config.formSelector);if (!form) return;-+const textFieldSelector = `${Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR}, ${Hi.ATTR_V2_TEXT_EDIT_FIELD_SELECTOR}`;const displayFields = form.querySelectorAll(textFieldSelector);displayFields.forEach(displayField => {const hiddenFieldId = displayField.getAttribute('data-hidden-field');const hiddenField = hiddenFieldId ? document.getElementById(hiddenFieldId) : null;-+if (hiddenField && !displayField.readOnly && !displayField.classList.contains('truncated')) {hiddenField.value = displayField.value;}});},- // Evaluate order field changes after reorderinghandleOrderFieldChanges: function() {const form = this.container.querySelector(this.config.formSelector);if (!form) return;@@ -389,8 +342,7 @@this.handleFieldChange(field);});},-- // Handle successful form submission+handleFormSuccess: function(e) {// Only clear if the success event is for this container's formconst form = this.container.querySelector(this.config.formSelector);@@ -398,42 +350,35 @@this.clearAllDirtyState();}},-- // Clear all dirty state for this container+clearAllDirtyState: function() {- // Clear visual indicatorsconst form = this.container.querySelector(this.config.formSelector);if (form) {form.querySelectorAll('.' + this.config.dirtyFieldClass).forEach(field => {field.classList.remove(this.config.dirtyFieldClass);});-+form.querySelectorAll('.' + this.config.dirtyIndicatorClass).forEach(indicator => {indicator.remove();});-- // Clear fallback classes+form.querySelectorAll('.has-dirty-indicator').forEach(element => {element.classList.remove('has-dirty-indicator');});-+form.querySelectorAll('.has-dirty-field').forEach(element => {element.classList.remove('has-dirty-field');});}-- // Clear state+this.state.dirtyFields.clear();-- // Clear timers+this.state.debounceTimers.forEach(timer => clearTimeout(timer));this.state.debounceTimers.clear();-- // Clear message+this.updateMessageArea();},-- // Reinitialize for dynamic content+reinitialize: function() {this.clearAllDirtyState();this.state.originalValues.clear();@@ -441,28 +386,23 @@this.init();}};-- /**- * Private DirtyTracker instance management- */+const _instances = new Map();-+const HiAttrDirtyTracking = {- // Instance ManagementgetInstance: function(containerId) {if (!_instances.has(containerId)) {_instances.set(containerId, new DirtyTracker(containerId));}return _instances.get(containerId);},-+createInstance: function(containerId) {const instance = new DirtyTracker(containerId);_instances.set(containerId, instance);return instance;},-- // Bulk Operations+initializeAll: function() {const containers = document.querySelectorAll(Hi.ATTR_V2_CONTAINER_SELECTOR);containers.forEach(container => {@@ -472,7 +412,7 @@}});},-+reinitializeContainer: function(containerId) {const $container = typeof containerId === 'string' ? $(`#${containerId}`) : $(containerId);const id = $container.attr('id');@@ -480,12 +420,11 @@console.warn('DirtyTracking: Container missing ID, skipping initialization');return;}-+const instance = this.getInstance(id);instance.reinitialize();},-- // Event Handling+handleFormSuccess: function(event) {const form = event.target.closest(Hi.ATTR_V2_FORM_CLASS_SELECTOR);if (form) {@@ -496,22 +435,19 @@}}},-- // Initialization+init: function() {this.initializeAll();}};-- // Export to Hi namespace+window.Hi.attr.dirtyTracking = HiAttrDirtyTracking;-- // Auto-initialize when DOM is ready+document.addEventListener('DOMContentLoaded', function() {HiAttrDirtyTracking.init();});-- // Note: Modal initialization is handled by attr.js module, not here- // attr.js calls reinitializeContainer() for modal content-++ // Modal content uses a separate initialization path (reinitializeContainer);+ // it is not bound to DOMContentLoaded.+})();diff --git a/src/hi/static/js/entity_state_status.js b/src/hi/static/js/entity_state_status.jsindex f5df8bd0..d388ac4f 100644--- a/src/hi/static/js/entity_state_status.js+++ b/src/hi/static/js/entity_state_status.js@@ -1,5 +1,5 @@/*- * Home Information — Entity-state polling-update dispatcher.+ * Home Information - Entity-state polling-update dispatcher.** Consumes the ``entityStateStatusMap`` from the polling response* and applies per-EntityState DOM updates. The map is keyed by the@@ -11,23 +11,23 @@* updates carries ``data-state-id="<entity_state_id>"`` plus one or* more declaration attributes. Each declaration is presence-only:*- * data-status → set the element's ``status`` attr to- * ``entry.status`` (singular status push;- * CSS rules elsewhere react to it).- * data-controller-value → set the form value / checked / selected- * from ``entry.controller.value``.- * data-display-text → set element text to ``entry.display.text``.- * data-display-magnitude → set element text to ``entry.display.magnitude``.- * data-display-unit → set element text to ``entry.display.unit``.- * data-svg-style → set every attribute in ``entry.svg_style``- * (status, stroke, fill, stroke-width,- * fill-opacity, stroke-dasharray) on this- * element. Used by LocationView SVG icon /- * path elements.+ * data-status -> set the element's ``status`` attr to+ * ``entry.status`` (singular status push;+ * CSS rules elsewhere react to it).+ * data-controller-value -> set the form value / checked / selected+ * from ``entry.controller.value``.+ * data-display-text -> set element text to ``entry.display.text``.+ * data-display-magnitude -> set element text to ``entry.display.magnitude``.+ * data-display-unit -> set element text to ``entry.display.unit``.+ * data-svg-style -> set every attribute in ``entry.svg_style``+ * (status, stroke, fill, stroke-width,+ * fill-opacity, stroke-dasharray) on this+ * element. Used by LocationView SVG icon /+ * path elements.** The dispatcher walks ``[data-state-id]`` once, looks up the* entry, and applies each declaration the element opts into. No- * descendant traversal and no class-based join — each element is+ * descendant traversal and no class-based join -- each element is* self-describing, so authors place the markers on whichever* element they want updated.*@@ -61,7 +61,7 @@// jQuery ready for the initial page render AND after every async// content insertion (via antinode), so panels in dynamically-loaded// modals get a chance to initialize before the first polling tick.- // Init handlers must be idempotent — they re-scan the whole+ // Init handlers must be idempotent -- they re-scan the whole// document on each call and should be safe to invoke on already-// initialized elements.const panelUpdateHandlers = [];@@ -175,8 +175,6 @@setPropIfDifferent( element, 'value', String( value ) );return;}- // Other shapes (color picker, etc.) get their own branches- // here as widgets are added.}function setPropIfDifferent( element, prop, newValue ) {@@ -210,8 +208,8 @@// display element, looked up within the enclosing// form.// Hi.CONTROLLER_DISPLAY_FORMAT_ATTR Format string with- // ``{n}`` as the value placeholder, e.g. ``{n}%``,- // ``{n}°``. Optional; defaults to ``{n}``.+ // ``{n}`` as the value placeholder, e.g. ``{n}%``.+ // Optional; defaults to ``{n}``.const selector = slider.getAttribute( Hi.CONTROLLER_DISPLAY_TARGET_ATTR );if ( ! selector ) return;const $display = $( slider ).closest( 'form' ).find( selector );@@ -228,7 +226,7 @@// ``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+ // 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``@@ -255,15 +253,15 @@: ( $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+ // 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"+ // an optimistic "73.0F" matching the canonical "72.0F"// 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").+ // formatted version ("73.0F").const $paired = $( '[data-state-id="' + stateId + '"][data-display-text]' ).not( $el ).first();if ( $paired.length ) {@@ -307,7 +305,7 @@});- // Slider drag mirror — keep the paired display in lock-step+ // Slider drag mirror -- keep the paired display in lock-step// with the thumb during user drag. ``input`` fires// continuously; ``change`` only fires on release, which// would let the displayed value lag behind the thumb.@@ -321,7 +319,7 @@// skip sliders the operator is currently manipulating.// Release-side handlers live on ``document`` so a pointer// release outside the viewport still bubbles and clears- // the flag — listening on body alone would leak the flag+ // the flag -- listening on body alone would leak the flag// if the user dragged the thumb past the page edge.$( 'body' ).on('mousedown touchstart pointerdown',diff --git a/src/hi/static/js/video-timeline.js b/src/hi/static/js/video-timeline.jsindex 31130c13..2892e037 100644--- a/src/hi/static/js/video-timeline.js+++ b/src/hi/static/js/video-timeline.js@@ -9,7 +9,7 @@'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';// The connection manager treats both markers as the same kind of- // long-lived MJPEG fetch — both need explicit cleanup on DOM+ // long-lived MJPEG fetch -- both need explicit cleanup on DOM// removal so browser per-host connection slots are released. The// markers themselves are disjoint by content type:// - ``data-video-stream`` : continuous live MJPEG (camera).@@ -23,7 +23,7 @@// the document.//// Responsibilities split with antinode:- // - Antinode fires ``beforeAsyncRender($target)`` immediately+ // - Antinode fires ``beforeContentRemoval($subtree)`` immediately// before replacing a subtree. We register a callback that// force-closes any tracked streams within the outgoing// subtree by swapping ``src`` to a 1x1 transparent GIF. This@@ -60,9 +60,6 @@this.streams.delete( element );},- // Walk the outgoing subtree and force-close every marked- // element within it. Called by antinode's beforeAsyncRender- // hook before content is replaced.closeWithin: function( $scope ) {if ( ! $scope || ! $scope.find ) return;const manager = this;@@ -71,8 +68,6 @@});},- // Re-derive the tracked set from the live DOM. Drops removed- // elements, registers newly-attached ones.reconcile: function() {for ( const element of Array.from( this.streams )) {if ( ! document.contains( element )) {@@ -97,10 +92,8 @@// Polls ``[data-video-snapshot]`` <img> elements at their declared// ``data-stream-fps`` to synthesize a live feed from a still-image- // endpoint (HA cameras and any future integration that offers a- // snapshot URL but no native stream). Pauses while the tab is- // hidden so bandwidth isn't spent rendering frames the user can't- // see.+ // endpoint (HA cameras, etc.). Pauses while the tab is hidden so+ // bandwidth isn't spent rendering frames the user can't see.//// Marker contract:// - ``data-video-snapshot`` : presence opts the <img> into polling.@@ -224,9 +217,8 @@REGISTERED_FLAG: 'videoErrorHandlerRegistered',// Heading + subtitle per marker. Mirrors the server-rendered- // ``.video-placeholder`` markup in entity_video_sensor_history.html- // for the no-source case, so the failed-to-load and no-data cases- // look visually identical.+ // ``.video-placeholder`` markup for the no-source case, so the+ // failed-to-load and no-data cases look visually identical.MESSAGES: {'data-video-stream': {heading: 'Live View Unavailable',@@ -321,13 +313,11 @@}};- // Video Timeline Scrollbar Managementconst VideoTimelineScrollManager = {init: function() {this.timeline = document.getElementById('event-timeline');if (!this.timeline) return;- // Handle initial page loads - scroll to active item if neededthis.handleInitialLoad();},@@ -336,14 +326,11 @@const activeItem = this.timeline.querySelector('.timeline-item.active');if (!activeItem) return;- // Check if coming from live streamconst fromLive = sessionStorage.getItem('navigatingFromLiveStream');if (fromLive) {sessionStorage.removeItem('navigatingFromLiveStream');- // Force scroll to active item - should start at top (case D)setTimeout(() => this.scrollToItem(activeItem, 'from-live'), 50);} else if (!window.videoTimelineInitialized) {- // First time loading - center active item (case A)window.videoTimelineInitialized = true;setTimeout(() => this.scrollToItem(activeItem, 'initial'), 50);}@@ -377,7 +364,7 @@});}} else if (context === 'from-live') {- // For "Recent Event" button, scroll to top (case D)+ // For from-live navigation, scroll to toptimeline.scrollTo({top: 0,behavior: 'auto'@@ -433,7 +420,6 @@}};- // Initialize when DOM is readyfunction initVideoSubsystems() {VideoTimelineScrollManager.init();VideoTimelineScrollManager.tagCurrentVideoWithEventId();@@ -448,10 +434,10 @@}// Hook into antinode lifecycle. ``beforeContentRemoval`` runs- // before any subtree is detached — HTML content swap or modal- // dismissal — with the outgoing subtree. That's where we close+ // before any subtree is detached -- HTML content swap or modal+ // dismissal -- with the outgoing subtree. That's where we close// stream connections cleanly. ``afterAsyncRender`` and- // ``afterModalRender`` run after content is in the DOM — that's+ // ``afterModalRender`` run after content is in the DOM -- that's// where we reconcile our tracked set against the new state.function registerHook( hookName, fn ) {if ( typeof window.AN === 'object'@@ -475,13 +461,11 @@VideoErrorHandler.reconcile();});- // Cleanup on page unload to free connections and stop pollerswindow.addEventListener('beforeunload', () => {VideoConnectionManager.cleanup();SnapshotStreamManager.cleanup();});- // Also cleanup on navigation away from video pageswindow.addEventListener('pagehide', () => {VideoConnectionManager.cleanup();SnapshotStreamManager.cleanup();@@ -497,7 +481,7 @@// cached original URL on each click. The browser sees a new URL,// abandons the previous fetch, and starts a new one. ZoneMinder// serves the clip from the start on each request- // (``replay=single``). Avoids blanking the ``src`` — an empty+ // (``replay=single``). Avoids blanking the ``src`` -- an empty// src would fire ``error`` and trigger ``VideoErrorHandler``'s// placeholder.function videoClipReplayBuster( baseUrl ) {@@ -540,7 +524,6 @@});- // Expose for potential external use and debuggingwindow.VideoTimelineScrollManager = VideoTimelineScrollManager;window.VideoConnectionManager = VideoConnectionManager;window.SnapshotStreamManager = SnapshotStreamManager;