diff --git a/261119notes.txt b/261119notes.txt new file mode 100644 index 00000000..75ed9e3a --- /dev/null +++ b/261119notes.txt @@ -0,0 +1,406 @@ +Now I have a good understanding of the codebase. Let me summarize some refactoring task ideas that would be suitable for the + Armadillo task. The key criteria are: + + 1. Real work on the repo (add feature, fix bug, refactor, write tests) + 2. Complex enough for 3-5 turns + 3. Can be checked with tests or behavior + 4. Not already solved in public + 5. No Docker or external websites needed + + Good refactoring ideas: + + 1. Template Light - Consolidate Color Mode Handling: The template light has massive duplication for + RGB/RGBW/RGBWW/HS/temperature/brightness/effect. Each has its own script, template, state variable, and property. Could + refactor into a unified handler. + + 2. MQTT Light - Schema Consolidation: The MQTT light has 4 schema files (schema_basic.py, schema_json.py, schema_template.py, + schema.py) with lots of shared logic. Could consolidate common functionality. + + 3. DataUpdateCoordinator Enhancement: The coordinator is used everywhere but could benefit from better type hints, async context + manager support, or better error handling patterns. + + 4. Debouncer Improvements: The debouncer is used in many places - could add better metrics, configurable backoff, or integration + with the new async timeout patterns. + + 5. Light Component - Deprecated Constant Cleanup: There are many deprecated constants (SUPPORT_*, COLOR_MODE_*) that could be + cleaned up with automated migration. + + 6. Config Entries - Split Large File: The config_entries.py is 3000+ lines - could split into smaller modules. + + 7. Entity Helper - Common Property Patterns: Many entities have similar patterns for state attributes - could create a mixin or + base class. + + Let me present these ideas to the user. + + Based on my exploration of the Home Assistant codebase, here are refactoring task ideas that fit the Armadillo criteria (real + work, 3-5 turns, testable, no Docker/external deps): + + ──────────────────────────────────────────────────────────────────────────────── + + ### 1. Template Light: Consolidate Color Mode Handling ⭐ Best candidate + + File: homeassistant/components/template/light.py (~1000 lines) + + Problem: Massive duplication for each color mode (RGB, RGBW, RGBWW, HS, temperature, brightness, effect) — each has its own + script, template, state variable, property, and template setup. + + Refactoring: Create a ColorModeHandler dataclass/protocol that encapsulates script/template/state/property per mode. Loop over + supported modes instead of 7× copy-pasted blocks. + + Tests: Existing template light tests in tests/components/template/test_light.py cover all modes. + + ──────────────────────────────────────────────────────────────────────────────── + + ### 2. MQTT Light: Unify Schema Implementations + + Files: homeassistant/components/mqtt/light/schema_{basic,json,template}.py + schema.py + + Problem: 4 schema files with significant overlap in validation, color mode handling, and entity creation logic. + + Refactoring: Extract shared validation/color-mode logic into a common base class or module. Reduce duplication across JSON, + template, and basic schemas. + + Tests: tests/components/mqtt/test_light.py has extensive coverage. + + ──────────────────────────────────────────────────────────────────────────────── + + ### 3. DataUpdateCoordinator: Add Async Context Manager + Better Errors + + File: homeassistant/helpers/update_coordinator.py + + Problem: Coordinators are manually started/stopped. No async with support. Error handling is basic (UpdateFailed only). + + Refactoring: + - Add __aenter__/__aexit__ for automatic async_config_entry_first_refresh + shutdown + - Add richer error types (auth, not_ready, rate_limit) that map to config entry states + - Add optional update_timeout parameter + + Tests: tests/helpers/test_update_coordinator.py + + ──────────────────────────────────────────────────────────────────────────────── + + ### 4. Debouncer: Configurable Backoff + Metrics + + File: homeassistant/helpers/debounce.py + + Problem: Fixed cooldown, no observability. Used in 20+ integrations. + + Refactoring: + - Add exponential backoff option (backoff_factor, max_cooldown) + - Add call_count / last_called / rejected_count properties for debugging + - Add optional callback on debounce rejection + + Tests: tests/helpers/test_debounce.py + + ──────────────────────────────────────────────────────────────────────────────── + + ### 5. Light Component: Remove Deprecated Constants + + File: homeassistant/components/light/__init__.py + integrations + + Problem: ~30 deprecated SUPPORT_* and COLOR_MODE_* constants with DeprecatedConstant wrappers, still imported by many + integrations. + + Refactoring: + - Remove deprecated constants from light __init__.py + - Update remaining integrations (mqtt, template, matter, hue, etc.) to use LightEntityFeature / ColorMode enums directly + - Add codemod script for automated migration + + Tests: Light tests + integration tests for each updated component. + + ──────────────────────────────────────────────────────────────────────────────── + + ### 6. Config Entries: Split Monolithic File + + File: homeassistant/config_entries.py (3,300+ lines) + + Problem: Single massive file handling config entry lifecycle, discovery, flows, storage, migrations, notifications. + + Refactoring: Split into: + - config_entries/entry.py — ConfigEntry dataclass + - config_entries/flow.py — ConfigFlow base + registry + - config_entries/storage.py — Storage logic + - config_entries/discovery.py — Discovery handling + - config_entries/__init__.py — Public re-exports + + Tests: tests/config_entries/ — comprehensive suite. + + ──────────────────────────────────────────────────────────────────────────────── + + ### 7. Entity: Extract Common Attribute Mixins + + Files: homeassistant/helpers/entity.py + many components + + Problem: Repeated patterns for extra_state_attributes, supported_features, capability_attributes across entities. + + Refactoring: Create mixin classes like AttributesMixin, FeaturesMixin with declarative field definitions (similar to dataclasses + or propcache). + + Tests: Entity tests + spot-check integrations. + + ──────────────────────────────────────────────────────────────────────────────── + + ### My Recommendation: Task #1 (Template Light) + + - Self-contained to one file + - High impact — removes ~400 lines of duplication + - Well-tested — existing test suite validates all color modes + - Clear success criteria — all template light tests pass, code is DRY + - No external deps — pure Python refactoring + + Would you like me to elaborate on any of these, or help you pick one to start with? + + + before we explore your ideas - is thie codebase the frontend and the backend? + + + The user is asking if this codebase contains both frontend and backend code. Let me check what's in the repo - Home Assistant is + primarily a Python backend, but it does have some frontend components (like the Lovelace UI, which is served by the backend but + built separately). + + + $ ls -la | head -30 + + ... (25 earlier lines, ctrl+o to expand) + -rw-r--r-- 1 ericbell ericbell 3886 Oct 29 12:01 .pre-commit-config.yaml + -rw-r--r-- 1 ericbell ericbell 233 Oct 29 12:01 .prettierignore + drwxr-xr-x 3 ericbell ericbell 4096 Oct 29 12:01 pylint + -rw-r--r-- 1 ericbell ericbell 43893 Oct 29 12:01 pyproject.toml + -rw-r--r-- 1 ericbell ericbell 1964 Oct 29 12:01 README.rst + + Took 0.0s + + + This is the Home Assistant Core repository - it's a Python backend. Let me check if there's any frontend code in here. + + + $ find . -name "*.ts" -o -name "*.tsx" -o -name "*.vue" -o -name "*.js" -o -name "package.json" 2>/dev/null | head -20 + + ./tests/components/lidarr/fixtures/initialize.js + ./tests/components/lidarr/fixtures/initialize-wrong.js + + Took 0.2s + + + Almost no JavaScript/TypeScript files. This is a Python-only backend. + + + $ ls homeassistant/components/frontend/ + + ... (1 earlier lines, ctrl+o to expand) + __init__.py + manifest.json + services.yaml + storage.py + strings.json + + Took 0.0s + + + The "frontend" component here is just a Python integration that serves the pre-built frontend. Let me check if there's a frontend + directory or if the frontend is completely separate. + + + read homeassistant/components/frontend/__init__.py:1-80 + + + This is the Python backend that serves the frontend. The actual frontend (React/TypeScript) is in a separate repository + (home-assistant/frontend). This repo is the backend only. + + No — this is the backend only (Python). + + The homeassistant/components/frontend/ you see is just a Python integration that serves the pre-built frontend assets + (HTML/JS/CSS). The actual frontend codebase (React + TypeScript) lives in a separate repo: home-assistant/frontend. + + This repo (home-assistant/core) contains: + - Core: event loop, state machine, config entries, entity system + - Integrations: 950+ components (light, mqtt, hue, zwave, etc.) — all Python + - Helpers: update_coordinator, debounce, entity registry, device registry, etc. + - API: REST + WebSocket endpoints + - Frontend serving: static asset delivery, panel registration, theme storage + + No TypeScript, no Vue, no webpack, no npm — pure Python. + + + your #1 idea is template light. you gave a bit of a synopsis already but give me a simplfied tour + + + The user wants a simplified tour of the template light code to understand the refactoring opportunity better. Let me walk through + the key parts of the file. + + + read homeassistant/components/template/light.py:180-379 + + + Let me also look at the turn_on method and the async_turn_on/turn_off methods to see the full picture. + + + read homeassistant/components/template/light.py:500-699 + + + Now I have a good picture. Let me provide a simplified tour. + + ──────────────────────────────────────────────────────────────────────────────── + + Template Light — Simplified Tour + + File: homeassistant/components/template/light.py (~1000 lines) + + ### The Pattern (Repeated 7×) + + For each color mode (brightness, temperature, HS, RGB, RGBW, RGBWW, effect), the class has: + + ┌─────────────────┬────────────────────────────────┬────────────────────────────────┐ + │ Item │ Example (Brightness) │ Example (RGB) │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ Config key │ level_action, level_template │ rgb_action, rgb_template │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ Script │ self._level_script │ self._rgb_script │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ Template │ self._level_template │ self._rgb_template │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ State var │ self._brightness │ self._rgb_color │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ Property │ brightness │ rgb_color │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ Template setup │ _async_setup_templates() block │ _async_setup_templates() block │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ Update callback │ _update_brightness() │ _update_rgb() │ + ├─────────────────┼────────────────────────────────┼────────────────────────────────┤ + │ Turn-on logic │ elif ATTR_BRIGHTNESS... block │ elif ATTR_RGB_COLOR... block │ + └─────────────────┴────────────────────────────────┴────────────────────────────────┘ + + ### Constructor (Lines 180–260) + + ```python + # 7 nearly identical if-blocks: + if (level_action := config.get(CONF_LEVEL_ACTION)) is not None: + self._level_script = Script(hass, level_action, ...) + # ... repeated for temperature, hs, rgb, rgbw, rgbww, effect + + # 7 state variables: + self._brightness = None + self._temperature = None + self._hs_color = None + self._rgb_color = None + self._rgbw_color = None + self._rgbww_color = None + self._effect = None + + # Color mode detection — manual chain: + color_modes = {ColorMode.ONOFF} + if self._level_script: color_modes.add(ColorMode.BRIGHTNESS) + if self._temperature_script: color_modes.add(ColorMode.COLOR_TEMP) + # ... etc + ``` + + ### Properties (Lines 260–330) + + ```python + @property def brightness(self): return self._brightness + @property def color_temp_kelvin(self): ... # conversion logic + @property def hs_color(self): return self._hs_color + @property def rgb_color(self): return self._rgb_color + @property def rgbw_color(self): return self._rgbw_color + @property def rgbww_color(self): return self._rgbww_color + @property def effect(self): return self._effect + # ... all boilerplate + ``` + + ### Template Setup (Lines 330–420) + + ```python + @callback + def _async_setup_templates(self): + if self._template: self.add_template_attribute("_state", ...) + if self._level_template: self.add_template_attribute("_brightness", ...) + if self._max_mireds_template: self.add_template_attribute("_max_mireds_template", ...) + if self._min_mireds_template: self.add_template_attribute("_min_mireds_template", ...) + if self._temperature_template: self.add_template_attribute("_temperature", ...) + if self._color_template: self.add_template_attribute("_hs_color", ...) + if self._hs_template: self.add_template_attribute("_hs_color", ...) + if self._rgb_template: self.add_template_attribute("_rgb_color", ...) + if self._rgbw_template: self.add_template_attribute("_rgbw_color", ...) + if self._rgbww_template: self.add_template_attribute("_rgbww_color", ...) + if self._effect_list_template: self.add_template_attribute("_effect_list", ...) + if self._effect_template: self.add_template_attribute("_effect", ...) + if self._supports_transition_template: self.add_template_attribute(...) + ``` + + ### Turn On (Lines 420–650) — Giant if/elif Chain + + ```python + async def async_turn_on(self, **kwargs): + # 7 optimistic-set blocks (RGB, RGBW, RGBWW each ~25 lines) + # Then 7 script-dispatch blocks: + if ATTR_COLOR_TEMP_KELVIN in kwargs and self._temperature_script: + await self.async_run_script(self._temperature_script, ...) + elif ATTR_EFFECT in kwargs and self._effect_script: + await self.async_run_script(self._effect_script, ...) + elif ATTR_HS_COLOR in kwargs and self._color_script: + ... + elif ATTR_HS_COLOR in kwargs and self._hs_script: + ... + elif ATTR_RGBWW_COLOR in kwargs and self._rgbww_script: + ... + elif ATTR_RGBW_COLOR in kwargs and self._rgbw_script: + ... + elif ATTR_RGB_COLOR in kwargs and self._rgb_script: + ... + elif ATTR_BRIGHTNESS in kwargs and self._level_script: + ... + else: + await self.async_run_script(self._on_script, ...) + ``` + + ### Update Callbacks (Lines 650–850) + + ```python + @callback def _update_brightness(self, brightness): ... + @callback def _update_temperature(self, temperature): ... + @callback def _update_hs(self, hs_color): ... + @callback def _update_rgb(self, rgb_color): ... + @callback def _update_rgbw(self, rgbw_color): ... + @callback def _update_rgbww(self, rgbww_color): ... + @callback def _update_effect(self, effect): ... + @callback def _update_effect_list(self, effect_list): ... + @callback def _update_max_mireds(self, max_mireds): ... + @callback def _update_min_mireds(self, min_mireds): ... + @callback def _update_supports_transition(self, supports_transition): ... + ``` + + ──────────────────────────────────────────────────────────────────────────────── + + The Refactoring + + Replace all of the above with a data-driven approach: + + ```python + @dataclass + class ColorModeHandler: + color_mode: ColorMode + script_key: str # e.g., "rgb_action" + template_key: str # e.g., "rgb_template" + state_attr: str # e.g., "_rgb_color" + property_name: str # e.g., "rgb_color" + attr_key: str # e.g., ATTR_RGB_COLOR + param_builder: Callable # converts kwargs -> run_variables + optimistic_clear: list[str] # which other attrs to clear on optimistic set + + HANDLERS = [ + ColorModeHandler(ColorMode.BRIGHTNESS, "level_action", "level_template", + "_brightness", "brightness", ATTR_BRIGHTNESS, ...), + ColorModeHandler(ColorMode.COLOR_TEMP, "temperature_action", "temperature_template", + "_temperature", "color_temp_kelvin", ATTR_COLOR_TEMP_KELVIN, ...), + # ... 5 more + ] + ``` + + Then: + - Constructor: loop over HANDLERS, create scripts/templates/state vars dynamically + - Properties: use __getattr__ or generate via cached_property loop + - Template setup: loop over HANDLERS, call add_template_attribute + - Turn on: loop over HANDLERS, match attr_key in kwargs + - Update callbacks: single generic _update_state(attr, value) + validator map + + Resu diff --git a/sources/TASK_PLAN.md b/sources/TASK_PLAN.md new file mode 100644 index 00000000..6c88ab0f --- /dev/null +++ b/sources/TASK_PLAN.md @@ -0,0 +1,46 @@ +# Template Light Refactoring Plan: Consolidate Color Mode Handling + +## Current State Analysis +The `LightTemplate` class in `homeassistant/components/template/light.py` (~1000 lines) has massive duplication for each color mode: +- **7 color modes**: RGB, RGBW, RGBWW, HS, legacy COLOR, COLOR_TEMP, BRIGHTNESS, EFFECT +- Each mode has: script variable, template variable, state variable, property, template setup block, update callback, and turn_on handling logic + +## Refactoring Goal +Create a `ColorModeHandler` dataclass/protocol that encapsulates per-mode configuration (script, template, state attr, property name, ColorMode enum, validation/update logic). Loop over supported modes instead of 7× copy-pasted blocks. + +## Suggested 5-Turn Plan + +### Turn 1: Define ColorModeHandler and Refactor __init__ +- Create `ColorModeHandler` dataclass with fields: `color_mode`, `script_attr`, `template_attr`, `state_attr`, `property_name`, `update_callback`, `validation_fn`, `turn_on_priority`, `script_param_builder` +- In `__init__`, build a list `self._color_mode_handlers` by checking which scripts/templates are configured +- Replace individual `_rgb_script`, `_hs_script`, etc. with handler-based lookup +- Compute `supported_color_modes` from handlers dynamically + +### Turn 2: Refactor _async_setup_templates +- Replace 8 separate `if self._xxx_template:` blocks with a loop over `self._color_mode_handlers` +- Each handler registers its template with `add_template_attribute` using its update callback +- Handle special cases (min/max mireds, transition, effect_list) separately or as additional handlers + +### Turn 3: Consolidate Update Callbacks and Properties +- Replace `_update_rgb`, `_update_rgbw`, `_update_rgbww`, `_update_hs`, `_update_temperature`, `_update_brightness` with a generic `_update_color_mode(handler, value)` method +- Use handler's `validation_fn` for mode-specific validation +- Replace individual property methods (`rgb_color`, `hs_color`, etc.) with a generic approach using `__getattr__` or a property map + +### Turn 4: Refactor async_turn_on +- Replace the long if/elif chain (lines 300-450) with a loop over handlers sorted by `turn_on_priority` +- Each handler provides a `script_param_builder(kwargs)` that returns `(script, params)` or `None` +- First matching handler wins, executes its script with built params +- Handle optimistic state setting generically per handler + +### Turn 5: Verify Tests Pass & Clean Up +- Run `pytest tests/components/template/test_light.py -v` +- Fix any regressions +- Remove now-unused constants (CONF_RGB_ACTION, CONF_RGB_TEMPLATE, etc. - but keep for schema compatibility) +- Remove unused instance variables +- Ensure all 50+ tests still pass + +## Key Design Decisions +- Keep schema constants (CONF_*) for backward compatibility +- Handler priority order: EFFECT > RGBWW > RGBW > RGB > HS > COLOR > COLOR_TEMP > BRIGHTNESS > ONOFF (matches current if/elif order) +- Validation functions can be closures or static methods capturing mode-specific bounds +- Script param builders handle the different variable names each script expects (h/s vs r/g/b vs rgbww tuple, etc.) \ No newline at end of file