6 Commits

Author SHA1 Message Date
d828c27c42 finall - lightB is Bresponse ver 2026-11-24 11:45:01 -05:00
d7e9409156 after turn 1 2026-11-22 09:41:06 -05:00
aa373af3cb add 2nd refactor plan 2026-11-21 19:05:37 -05:00
4cd5e06635 added notes/task plan 2026-11-20 18:25:50 -05:00
7db6dc7eba denuded project-instructions.md 2026-11-19 21:26:40 -05:00
cb8eb69adf instructions file 2026-11-19 21:06:23 -05:00
8 changed files with 4001 additions and 254 deletions

406
261119notes.txt Normal file
View File

@@ -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

View File

@@ -2,6 +2,8 @@
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
import logging
from typing import Any
@@ -40,6 +42,7 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.script import Script
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import color as color_util
@@ -157,6 +160,35 @@ async def async_setup_platform(
async_add_entities(await _async_create_entities(hass, config))
@dataclass(slots=True)
class ColorModeHandler:
"""Describe how one color mode of a template light is configured and wired.
A handler exists for every color mode that has a script or a template
configured. A mode is supported only when it has a script; a mode is
optimistic only when it has no template.
"""
color_mode: ColorMode
# LightEntity property exposing the value. It is also the turn_on kwarg
# carrying the value, e.g. "rgb_color" (ATTR_RGB_COLOR).
property_name: str
# Entity attribute holding the current value, e.g. "_rgb_color".
state_attr: str
# Script variable receiving the whole value, e.g. "rgb".
script_attr: str
script: Script | None
template: Template | None
# Parses a template render and stores the result in state_attr.
update_callback: Callable[[Any], None]
# Script variables receiving each component of the value as int,
# e.g. ("r", "g", "b").
component_names: tuple[str, ...] = ()
# Converts the turn_on kwarg into the stored/script value,
# e.g. Kelvin to mireds for color temperature.
value_converter: Callable[[Any], Any] | None = None
class LightTemplate(TemplateEntity, LightEntity):
"""Representation of a templated Light, including dimmable."""
@@ -184,32 +216,6 @@ class LightTemplate(TemplateEntity, LightEntity):
if (level_action := config.get(CONF_LEVEL_ACTION)) is not None:
self._level_script = Script(hass, level_action, friendly_name, DOMAIN)
self._level_template = config.get(CONF_LEVEL_TEMPLATE)
self._temperature_script = None
if (temperature_action := config.get(CONF_TEMPERATURE_ACTION)) is not None:
self._temperature_script = Script(
hass, temperature_action, friendly_name, DOMAIN
)
self._temperature_template = config.get(CONF_TEMPERATURE_TEMPLATE)
self._color_script = None
if (color_action := config.get(CONF_COLOR_ACTION)) is not None:
self._color_script = Script(hass, color_action, friendly_name, DOMAIN)
self._color_template = config.get(CONF_COLOR_TEMPLATE)
self._hs_script = None
if (hs_action := config.get(CONF_HS_ACTION)) is not None:
self._hs_script = Script(hass, hs_action, friendly_name, DOMAIN)
self._hs_template = config.get(CONF_HS_TEMPLATE)
self._rgb_script = None
if (rgb_action := config.get(CONF_RGB_ACTION)) is not None:
self._rgb_script = Script(hass, rgb_action, friendly_name, DOMAIN)
self._rgb_template = config.get(CONF_RGB_TEMPLATE)
self._rgbw_script = None
if (rgbw_action := config.get(CONF_RGBW_ACTION)) is not None:
self._rgbw_script = Script(hass, rgbw_action, friendly_name, DOMAIN)
self._rgbw_template = config.get(CONF_RGBW_TEMPLATE)
self._rgbww_script = None
if (rgbww_action := config.get(CONF_RGBWW_ACTION)) is not None:
self._rgbww_script = Script(hass, rgbww_action, friendly_name, DOMAIN)
self._rgbww_template = config.get(CONF_RGBWW_TEMPLATE)
self._effect_script = None
if (effect_action := config.get(CONF_EFFECT_ACTION)) is not None:
self._effect_script = Script(hass, effect_action, friendly_name, DOMAIN)
@@ -232,29 +238,16 @@ class LightTemplate(TemplateEntity, LightEntity):
self._max_mireds = None
self._min_mireds = None
self._supports_transition = False
self._supported_color_modes = None
color_modes = {ColorMode.ONOFF}
if self._level_script is not None:
color_modes.add(ColorMode.BRIGHTNESS)
if self._temperature_script is not None:
color_modes.add(ColorMode.COLOR_TEMP)
if self._hs_script is not None:
color_modes.add(ColorMode.HS)
if self._color_script is not None:
color_modes.add(ColorMode.HS)
if self._rgb_script is not None:
color_modes.add(ColorMode.RGB)
if self._rgbw_script is not None:
color_modes.add(ColorMode.RGBW)
if self._rgbww_script is not None:
color_modes.add(ColorMode.RGBWW)
self._color_mode_handlers = self._create_color_mode_handlers(
hass, config, friendly_name
)
self._supported_color_modes = filter_supported_color_modes(color_modes)
if len(self._supported_color_modes) > 1:
supported_color_modes = self.supported_color_modes
if len(supported_color_modes) > 1:
self._color_mode = ColorMode.UNKNOWN
if len(self._supported_color_modes) == 1:
self._color_mode = next(iter(self._supported_color_modes))
if len(supported_color_modes) == 1:
self._color_mode = next(iter(supported_color_modes))
self._attr_supported_features = LightEntityFeature(0)
if self._effect_script is not None:
@@ -262,6 +255,89 @@ class LightTemplate(TemplateEntity, LightEntity):
if self._supports_transition is True:
self._attr_supported_features |= LightEntityFeature.TRANSITION
def _create_color_mode_handlers(
self, hass: HomeAssistant, config: ConfigType, friendly_name: str
) -> list[ColorModeHandler]:
"""Create a handler for each color mode with a script or template.
The list order matches the legacy template registration order, so the
color mode set by the last rendered template is unchanged. turn_on
receives at most one color attribute per call, so the order does not
change which script runs.
"""
def script(*action_keys: str) -> Script | None:
for key in action_keys:
if (action := config.get(key)) is not None:
return Script(hass, action, friendly_name, DOMAIN)
return None
def template(*template_keys: str) -> Template | None:
for key in template_keys:
if (value := config.get(key)) is not None:
return value
return None
candidates = [
ColorModeHandler(
color_mode=ColorMode.COLOR_TEMP,
property_name=ATTR_COLOR_TEMP_KELVIN,
state_attr="_temperature",
script_attr="color_temp",
script=script(CONF_TEMPERATURE_ACTION),
template=template(CONF_TEMPERATURE_TEMPLATE),
update_callback=self._update_temperature,
value_converter=color_util.color_temperature_kelvin_to_mired,
),
# The legacy set_color/color_template keys are exclusive with
# set_hs/hs_template and share the HS color mode.
ColorModeHandler(
color_mode=ColorMode.HS,
property_name=ATTR_HS_COLOR,
state_attr="_hs_color",
script_attr="hs",
script=script(CONF_COLOR_ACTION, CONF_HS_ACTION),
template=template(CONF_COLOR_TEMPLATE, CONF_HS_TEMPLATE),
update_callback=self._update_hs,
component_names=("h", "s"),
),
ColorModeHandler(
color_mode=ColorMode.RGB,
property_name=ATTR_RGB_COLOR,
state_attr="_rgb_color",
script_attr="rgb",
script=script(CONF_RGB_ACTION),
template=template(CONF_RGB_TEMPLATE),
update_callback=self._update_rgb,
component_names=("r", "g", "b"),
),
ColorModeHandler(
color_mode=ColorMode.RGBW,
property_name=ATTR_RGBW_COLOR,
state_attr="_rgbw_color",
script_attr="rgbw",
script=script(CONF_RGBW_ACTION),
template=template(CONF_RGBW_TEMPLATE),
update_callback=self._update_rgbw,
component_names=("r", "g", "b", "w"),
),
ColorModeHandler(
color_mode=ColorMode.RGBWW,
property_name=ATTR_RGBWW_COLOR,
state_attr="_rgbww_color",
script_attr="rgbww",
script=script(CONF_RGBWW_ACTION),
template=template(CONF_RGBWW_TEMPLATE),
update_callback=self._update_rgbww,
component_names=("r", "g", "b", "cw", "ww"),
),
]
return [
handler
for handler in candidates
if handler.script is not None or handler.template is not None
]
@property
def brightness(self) -> int | None:
"""Return the brightness of the light."""
@@ -326,9 +402,17 @@ class LightTemplate(TemplateEntity, LightEntity):
return self._color_mode
@property
def supported_color_modes(self):
"""Flag supported color modes."""
return self._supported_color_modes
def supported_color_modes(self) -> set[ColorMode]:
"""Flag supported color modes, derived from the configured scripts."""
color_modes = {ColorMode.ONOFF}
if self._level_script is not None:
color_modes.add(ColorMode.BRIGHTNESS)
color_modes.update(
handler.color_mode
for handler in self._color_mode_handlers
if handler.script is not None
)
return filter_supported_color_modes(color_modes)
@property
def is_on(self) -> bool | None:
@@ -366,54 +450,15 @@ class LightTemplate(TemplateEntity, LightEntity):
self._update_min_mireds,
none_on_template_error=True,
)
if self._temperature_template:
self.add_template_attribute(
"_temperature",
self._temperature_template,
None,
self._update_temperature,
none_on_template_error=True,
)
if self._color_template:
self.add_template_attribute(
"_hs_color",
self._color_template,
None,
self._update_hs,
none_on_template_error=True,
)
if self._hs_template:
self.add_template_attribute(
"_hs_color",
self._hs_template,
None,
self._update_hs,
none_on_template_error=True,
)
if self._rgb_template:
self.add_template_attribute(
"_rgb_color",
self._rgb_template,
None,
self._update_rgb,
none_on_template_error=True,
)
if self._rgbw_template:
self.add_template_attribute(
"_rgbw_color",
self._rgbw_template,
None,
self._update_rgbw,
none_on_template_error=True,
)
if self._rgbww_template:
self.add_template_attribute(
"_rgbww_color",
self._rgbww_template,
None,
self._update_rgbww,
none_on_template_error=True,
)
for handler in self._color_mode_handlers:
if handler.template:
self.add_template_attribute(
handler.state_attr,
handler.template,
None,
handler.update_callback,
none_on_template_error=True,
)
if self._effect_list_template:
self.add_template_attribute(
"_effect_list",
@@ -455,96 +500,17 @@ class LightTemplate(TemplateEntity, LightEntity):
self._brightness = kwargs[ATTR_BRIGHTNESS]
optimistic_set = True
if self._temperature_template is None and ATTR_COLOR_TEMP_KELVIN in kwargs:
color_temp = color_util.color_temperature_kelvin_to_mired(
kwargs[ATTR_COLOR_TEMP_KELVIN]
)
_LOGGER.debug(
"Optimistically setting color temperature to %s",
color_temp,
)
self._color_mode = ColorMode.COLOR_TEMP
self._temperature = color_temp
if self._hs_template is None and self._color_template is None:
self._hs_color = None
if self._rgb_template is None:
self._rgb_color = None
if self._rgbw_template is None:
self._rgbw_color = None
if self._rgbww_template is None:
self._rgbww_color = None
optimistic_set = True
if (
self._hs_template is None
and self._color_template is None
and ATTR_HS_COLOR in kwargs
):
_LOGGER.debug(
"Optimistically setting hs color to %s",
kwargs[ATTR_HS_COLOR],
)
self._color_mode = ColorMode.HS
self._hs_color = kwargs[ATTR_HS_COLOR]
if self._temperature_template is None:
self._temperature = None
if self._rgb_template is None:
self._rgb_color = None
if self._rgbw_template is None:
self._rgbw_color = None
if self._rgbww_template is None:
self._rgbww_color = None
optimistic_set = True
if self._rgb_template is None and ATTR_RGB_COLOR in kwargs:
_LOGGER.debug(
"Optimistically setting rgb color to %s",
kwargs[ATTR_RGB_COLOR],
)
self._color_mode = ColorMode.RGB
self._rgb_color = kwargs[ATTR_RGB_COLOR]
if self._temperature_template is None:
self._temperature = None
if self._hs_template is None and self._color_template is None:
self._hs_color = None
if self._rgbw_template is None:
self._rgbw_color = None
if self._rgbww_template is None:
self._rgbww_color = None
optimistic_set = True
if self._rgbw_template is None and ATTR_RGBW_COLOR in kwargs:
_LOGGER.debug(
"Optimistically setting rgbw color to %s",
kwargs[ATTR_RGBW_COLOR],
)
self._color_mode = ColorMode.RGBW
self._rgbw_color = kwargs[ATTR_RGBW_COLOR]
if self._temperature_template is None:
self._temperature = None
if self._hs_template is None and self._color_template is None:
self._hs_color = None
if self._rgb_template is None:
self._rgb_color = None
if self._rgbww_template is None:
self._rgbww_color = None
optimistic_set = True
if self._rgbww_template is None and ATTR_RGBWW_COLOR in kwargs:
_LOGGER.debug(
"Optimistically setting rgbww color to %s",
kwargs[ATTR_RGBWW_COLOR],
)
self._color_mode = ColorMode.RGBWW
self._rgbww_color = kwargs[ATTR_RGBWW_COLOR]
if self._temperature_template is None:
self._temperature = None
if self._hs_template is None and self._color_template is None:
self._hs_color = None
if self._rgb_template is None:
self._rgb_color = None
if self._rgbw_template is None:
self._rgbw_color = None
for handler in self._color_mode_handlers:
if handler.template is not None or handler.property_name not in kwargs:
continue
value = self._service_value(handler, kwargs)
_LOGGER.debug("Optimistically setting %s to %s", handler.script_attr, value)
self._color_mode = handler.color_mode
setattr(self, handler.state_attr, value)
# Colors of other optimistic modes no longer apply
for other in self._color_mode_handlers:
if other is not handler and other.template is None:
setattr(self, other.state_attr, None)
optimistic_set = True
common_params = {}
@@ -555,17 +521,31 @@ class LightTemplate(TemplateEntity, LightEntity):
if ATTR_TRANSITION in kwargs and self._supports_transition is True:
common_params["transition"] = kwargs[ATTR_TRANSITION]
if ATTR_COLOR_TEMP_KELVIN in kwargs and self._temperature_script:
common_params["color_temp"] = color_util.color_temperature_kelvin_to_mired(
kwargs[ATTR_COLOR_TEMP_KELVIN]
)
effect_requested = ATTR_EFFECT in kwargs and self._effect_script is not None
color_handler = next(
(
handler
for handler in self._color_mode_handlers
if handler.script is not None and handler.property_name in kwargs
),
None,
)
# Script precedence: color temperature, effect, other colors, level, on
if color_handler is not None and (
color_handler.color_mode == ColorMode.COLOR_TEMP or not effect_requested
):
common_params.update(
self._script_variables(
color_handler, self._service_value(color_handler, kwargs)
)
)
await self.async_run_script(
self._temperature_script,
color_handler.script,
run_variables=common_params,
context=self._context,
)
elif ATTR_EFFECT in kwargs and self._effect_script:
elif effect_requested:
effect = kwargs[ATTR_EFFECT]
if effect not in self._effect_list:
_LOGGER.error(
@@ -581,67 +561,6 @@ class LightTemplate(TemplateEntity, LightEntity):
await self.async_run_script(
self._effect_script, run_variables=common_params, context=self._context
)
elif ATTR_HS_COLOR in kwargs and self._color_script:
hs_value = kwargs[ATTR_HS_COLOR]
common_params["hs"] = hs_value
common_params["h"] = int(hs_value[0])
common_params["s"] = int(hs_value[1])
await self.async_run_script(
self._color_script, run_variables=common_params, context=self._context
)
elif ATTR_HS_COLOR in kwargs and self._hs_script:
hs_value = kwargs[ATTR_HS_COLOR]
common_params["hs"] = hs_value
common_params["h"] = int(hs_value[0])
common_params["s"] = int(hs_value[1])
await self.async_run_script(
self._hs_script, run_variables=common_params, context=self._context
)
elif ATTR_RGBWW_COLOR in kwargs and self._rgbww_script:
rgbww_value = kwargs[ATTR_RGBWW_COLOR]
common_params["rgbww"] = rgbww_value
common_params["rgb"] = (
int(rgbww_value[0]),
int(rgbww_value[1]),
int(rgbww_value[2]),
)
common_params["r"] = int(rgbww_value[0])
common_params["g"] = int(rgbww_value[1])
common_params["b"] = int(rgbww_value[2])
common_params["cw"] = int(rgbww_value[3])
common_params["ww"] = int(rgbww_value[4])
await self.async_run_script(
self._rgbww_script, run_variables=common_params, context=self._context
)
elif ATTR_RGBW_COLOR in kwargs and self._rgbw_script:
rgbw_value = kwargs[ATTR_RGBW_COLOR]
common_params["rgbw"] = rgbw_value
common_params["rgb"] = (
int(rgbw_value[0]),
int(rgbw_value[1]),
int(rgbw_value[2]),
)
common_params["r"] = int(rgbw_value[0])
common_params["g"] = int(rgbw_value[1])
common_params["b"] = int(rgbw_value[2])
common_params["w"] = int(rgbw_value[3])
await self.async_run_script(
self._rgbw_script, run_variables=common_params, context=self._context
)
elif ATTR_RGB_COLOR in kwargs and self._rgb_script:
rgb_value = kwargs[ATTR_RGB_COLOR]
common_params["rgb"] = rgb_value
common_params["r"] = int(rgb_value[0])
common_params["g"] = int(rgb_value[1])
common_params["b"] = int(rgb_value[2])
await self.async_run_script(
self._rgb_script, run_variables=common_params, context=self._context
)
elif ATTR_BRIGHTNESS in kwargs and self._level_script:
await self.async_run_script(
self._level_script, run_variables=common_params, context=self._context
@@ -654,6 +573,30 @@ class LightTemplate(TemplateEntity, LightEntity):
if optimistic_set:
self.async_write_ha_state()
@staticmethod
def _service_value(handler: ColorModeHandler, kwargs: dict[str, Any]) -> Any:
"""Return the turn_on value for a color mode, converted for storage."""
value = kwargs[handler.property_name]
if handler.value_converter is not None:
return handler.value_converter(value)
return value
@staticmethod
def _script_variables(handler: ColorModeHandler, value: Any) -> dict[str, Any]:
"""Return the script variables for a color mode value."""
variables: dict[str, Any] = {handler.script_attr: value}
if not handler.component_names:
return variables
components = [int(component) for component in value]
variables.update(zip(handler.component_names, components, strict=False))
# RGBW and RGBWW scripts also receive the plain RGB part
if (
handler.component_names[:3] == ("r", "g", "b")
and handler.script_attr != "rgb"
):
variables["rgb"] = tuple(components[:3])
return variables
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the light off."""
if ATTR_TRANSITION in kwargs and self._supports_transition is True:

View File

@@ -0,0 +1,997 @@
"""Support for Template lights."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
import logging
from typing import Any
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP_KELVIN,
ATTR_EFFECT,
ATTR_HS_COLOR,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
ATTR_RGBWW_COLOR,
ATTR_TRANSITION,
DEFAULT_MAX_KELVIN,
DEFAULT_MIN_KELVIN,
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA as LIGHT_PLATFORM_SCHEMA,
ColorMode,
LightEntity,
LightEntityFeature,
filter_supported_color_modes,
)
from homeassistant.const import (
CONF_ENTITY_ID,
CONF_FRIENDLY_NAME,
CONF_LIGHTS,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.script import Script
from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import color as color_util
from .const import DOMAIN
from .template_entity import (
TEMPLATE_ENTITY_COMMON_SCHEMA_LEGACY,
TemplateEntity,
rewrite_common_legacy_to_modern_conf,
)
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
# Legacy
CONF_COLOR_ACTION = "set_color"
CONF_COLOR_TEMPLATE = "color_template"
CONF_HS_ACTION = "set_hs"
CONF_HS_TEMPLATE = "hs_template"
CONF_RGB_ACTION = "set_rgb"
CONF_RGB_TEMPLATE = "rgb_template"
CONF_RGBW_ACTION = "set_rgbw"
CONF_RGBW_TEMPLATE = "rgbw_template"
CONF_RGBWW_ACTION = "set_rgbww"
CONF_RGBWW_TEMPLATE = "rgbww_template"
CONF_EFFECT_ACTION = "set_effect"
CONF_EFFECT_LIST_TEMPLATE = "effect_list_template"
CONF_EFFECT_TEMPLATE = "effect_template"
CONF_LEVEL_ACTION = "set_level"
CONF_LEVEL_TEMPLATE = "level_template"
CONF_MAX_MIREDS_TEMPLATE = "max_mireds_template"
CONF_MIN_MIREDS_TEMPLATE = "min_mireds_template"
CONF_OFF_ACTION = "turn_off"
CONF_ON_ACTION = "turn_on"
CONF_SUPPORTS_TRANSITION = "supports_transition_template"
CONF_TEMPERATURE_ACTION = "set_temperature"
CONF_TEMPERATURE_TEMPLATE = "temperature_template"
CONF_WHITE_VALUE_ACTION = "set_white_value"
CONF_WHITE_VALUE_TEMPLATE = "white_value_template"
DEFAULT_MIN_MIREDS = 153
DEFAULT_MAX_MIREDS = 500
@dataclass
class ColorModeHandler:
"""Describe how one color mode of a template light is configured.
One handler exists per color mode that has a script and/or a template
configured. It carries everything needed to set up the template, to run
the script and to optimistically track the state for that mode.
"""
color_mode: ColorMode
"""The color mode this handler represents."""
service_attr: str
"""The `light.turn_on` service data key that selects this mode."""
state_attr: str
"""Name of the entity attribute holding the current value."""
property_name: str
"""Name of the LightEntity property exposing the value."""
script: Script | None
"""The script that sets the color, if configured."""
template: Template | None
"""The template that reports the color, if configured."""
update_callback: Callable[[Any], None]
"""Called with the rendered template to update the entity state."""
script_variables: Callable[[Any], dict[str, Any]]
"""Builds the script run variables from the state value."""
to_state: Callable[[Any], Any] = lambda value: value
"""Converts the service data value to the value kept in `state_attr`."""
def _hs_variables(value: Any) -> dict[str, Any]:
return {"hs": value, "h": int(value[0]), "s": int(value[1])}
def _rgb_variables(value: Any) -> dict[str, Any]:
return {
"rgb": value,
"r": int(value[0]),
"g": int(value[1]),
"b": int(value[2]),
}
def _rgbw_variables(value: Any) -> dict[str, Any]:
return {
"rgbw": value,
"rgb": (int(value[0]), int(value[1]), int(value[2])),
"r": int(value[0]),
"g": int(value[1]),
"b": int(value[2]),
"w": int(value[3]),
}
def _rgbww_variables(value: Any) -> dict[str, Any]:
return {
"rgbww": value,
"rgb": (int(value[0]), int(value[1]), int(value[2])),
"r": int(value[0]),
"g": int(value[1]),
"b": int(value[2]),
"cw": int(value[3]),
"ww": int(value[4]),
}
LIGHT_SCHEMA = vol.All(
cv.deprecated(CONF_ENTITY_ID),
vol.Schema(
{
vol.Exclusive(CONF_COLOR_ACTION, "hs_legacy_action"): cv.SCRIPT_SCHEMA,
vol.Exclusive(CONF_COLOR_TEMPLATE, "hs_legacy_template"): cv.template,
vol.Exclusive(CONF_HS_ACTION, "hs_legacy_action"): cv.SCRIPT_SCHEMA,
vol.Exclusive(CONF_HS_TEMPLATE, "hs_legacy_template"): cv.template,
vol.Optional(CONF_RGB_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_RGB_TEMPLATE): cv.template,
vol.Optional(CONF_RGBW_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_RGBW_TEMPLATE): cv.template,
vol.Optional(CONF_RGBWW_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_RGBWW_TEMPLATE): cv.template,
vol.Inclusive(CONF_EFFECT_ACTION, "effect"): cv.SCRIPT_SCHEMA,
vol.Inclusive(CONF_EFFECT_LIST_TEMPLATE, "effect"): cv.template,
vol.Inclusive(CONF_EFFECT_TEMPLATE, "effect"): cv.template,
vol.Optional(CONF_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
vol.Optional(CONF_LEVEL_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_LEVEL_TEMPLATE): cv.template,
vol.Optional(CONF_MAX_MIREDS_TEMPLATE): cv.template,
vol.Optional(CONF_MIN_MIREDS_TEMPLATE): cv.template,
vol.Required(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(CONF_ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_SUPPORTS_TRANSITION): cv.template,
vol.Optional(CONF_TEMPERATURE_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_TEMPERATURE_TEMPLATE): cv.template,
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
).extend(TEMPLATE_ENTITY_COMMON_SCHEMA_LEGACY.schema),
)
PLATFORM_SCHEMA = vol.All(
# CONF_WHITE_VALUE_* is deprecated, support will be removed in release 2022.9
cv.removed(CONF_WHITE_VALUE_ACTION),
cv.removed(CONF_WHITE_VALUE_TEMPLATE),
LIGHT_PLATFORM_SCHEMA.extend(
{vol.Required(CONF_LIGHTS): cv.schema_with_slug_keys(LIGHT_SCHEMA)}
),
)
async def _async_create_entities(hass, config):
"""Create the Template Lights."""
lights = []
for object_id, entity_config in config[CONF_LIGHTS].items():
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)
lights.append(
LightTemplate(
hass,
object_id,
entity_config,
unique_id,
)
)
return lights
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the template lights."""
async_add_entities(await _async_create_entities(hass, config))
class LightTemplate(TemplateEntity, LightEntity):
"""Representation of a templated Light, including dimmable."""
_attr_should_poll = False
def __init__(
self,
hass,
object_id,
config,
unique_id,
):
"""Initialize the light."""
super().__init__(
hass, config=config, fallback_name=object_id, unique_id=unique_id
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, object_id, hass=hass
)
friendly_name = self._attr_name
self._template = config.get(CONF_VALUE_TEMPLATE)
self._on_script = Script(hass, config[CONF_ON_ACTION], friendly_name, DOMAIN)
self._off_script = Script(hass, config[CONF_OFF_ACTION], friendly_name, DOMAIN)
self._level_script = None
if (level_action := config.get(CONF_LEVEL_ACTION)) is not None:
self._level_script = Script(hass, level_action, friendly_name, DOMAIN)
self._level_template = config.get(CONF_LEVEL_TEMPLATE)
self._color_handlers: list[ColorModeHandler] = []
self._setup_color_handlers(hass, config, friendly_name)
self._effect_script = None
if (effect_action := config.get(CONF_EFFECT_ACTION)) is not None:
self._effect_script = Script(hass, effect_action, friendly_name, DOMAIN)
self._effect_list_template = config.get(CONF_EFFECT_LIST_TEMPLATE)
self._effect_template = config.get(CONF_EFFECT_TEMPLATE)
self._max_mireds_template = config.get(CONF_MAX_MIREDS_TEMPLATE)
self._min_mireds_template = config.get(CONF_MIN_MIREDS_TEMPLATE)
self._supports_transition_template = config.get(CONF_SUPPORTS_TRANSITION)
self._state = False
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
self._effect_list = None
self._color_mode = None
self._max_mireds = None
self._min_mireds = None
self._supports_transition = False
supported_color_modes = self.supported_color_modes
if len(supported_color_modes) > 1:
self._color_mode = ColorMode.UNKNOWN
if len(supported_color_modes) == 1:
self._color_mode = next(iter(supported_color_modes))
self._attr_supported_features = LightEntityFeature(0)
if self._effect_script is not None:
self._attr_supported_features |= LightEntityFeature.EFFECT
if self._supports_transition is True:
self._attr_supported_features |= LightEntityFeature.TRANSITION
def _setup_color_handlers(
self, hass: HomeAssistant, config: ConfigType, friendly_name: str
) -> None:
"""Create a handler for every color mode that is configured."""
def script(*keys: str) -> Script | None:
for key in keys:
if (action := config.get(key)) is not None:
return Script(hass, action, friendly_name, DOMAIN)
return None
def template(*keys: str) -> Template | None:
for key in keys:
if (tpl := config.get(key)) is not None:
return tpl
return None
# (handler, configured action keys, configured template keys).
# The legacy color options are an alias of the hs options.
candidates = (
(
ColorModeHandler(
color_mode=ColorMode.COLOR_TEMP,
service_attr=ATTR_COLOR_TEMP_KELVIN,
state_attr="_temperature",
property_name="color_temp_kelvin",
script=None,
template=None,
update_callback=self._update_temperature,
script_variables=lambda mireds: {"color_temp": mireds},
to_state=color_util.color_temperature_kelvin_to_mired,
),
(CONF_TEMPERATURE_ACTION,),
(CONF_TEMPERATURE_TEMPLATE,),
),
(
ColorModeHandler(
color_mode=ColorMode.HS,
service_attr=ATTR_HS_COLOR,
state_attr="_hs_color",
property_name="hs_color",
script=None,
template=None,
update_callback=self._update_hs,
script_variables=_hs_variables,
),
(CONF_HS_ACTION, CONF_COLOR_ACTION),
(CONF_HS_TEMPLATE, CONF_COLOR_TEMPLATE),
),
(
ColorModeHandler(
color_mode=ColorMode.RGB,
service_attr=ATTR_RGB_COLOR,
state_attr="_rgb_color",
property_name="rgb_color",
script=None,
template=None,
update_callback=self._update_rgb,
script_variables=_rgb_variables,
),
(CONF_RGB_ACTION,),
(CONF_RGB_TEMPLATE,),
),
(
ColorModeHandler(
color_mode=ColorMode.RGBW,
service_attr=ATTR_RGBW_COLOR,
state_attr="_rgbw_color",
property_name="rgbw_color",
script=None,
template=None,
update_callback=self._update_rgbw,
script_variables=_rgbw_variables,
),
(CONF_RGBW_ACTION,),
(CONF_RGBW_TEMPLATE,),
),
(
ColorModeHandler(
color_mode=ColorMode.RGBWW,
service_attr=ATTR_RGBWW_COLOR,
state_attr="_rgbww_color",
property_name="rgbww_color",
script=None,
template=None,
update_callback=self._update_rgbww,
script_variables=_rgbww_variables,
),
(CONF_RGBWW_ACTION,),
(CONF_RGBWW_TEMPLATE,),
),
)
for handler, action_keys, template_keys in candidates:
handler.script = script(*action_keys)
handler.template = template(*template_keys)
if handler.script is not None or handler.template is not None:
self._color_handlers.append(handler)
@property
def brightness(self) -> int | None:
"""Return the brightness of the light."""
return self._brightness
@property
def color_temp_kelvin(self) -> int | None:
"""Return the color temperature value in Kelvin."""
if self._temperature is None:
return None
return color_util.color_temperature_mired_to_kelvin(self._temperature)
@property
def min_color_temp_kelvin(self) -> int:
"""Return the warmest color_temp_kelvin that this light supports."""
if self._max_mireds is not None:
return color_util.color_temperature_mired_to_kelvin(self._max_mireds)
return DEFAULT_MIN_KELVIN
@property
def max_color_temp_kelvin(self) -> int:
"""Return the coldest color_temp_kelvin that this light supports."""
if self._min_mireds is not None:
return color_util.color_temperature_mired_to_kelvin(self._min_mireds)
return DEFAULT_MAX_KELVIN
@property
def hs_color(self) -> tuple[float, float] | None:
"""Return the hue and saturation color value [float, float]."""
return self._hs_color
@property
def rgb_color(self) -> tuple[int, int, int] | None:
"""Return the rgb color value."""
return self._rgb_color
@property
def rgbw_color(self) -> tuple[int, int, int, int] | None:
"""Return the rgbw color value."""
return self._rgbw_color
@property
def rgbww_color(self) -> tuple[int, int, int, int, int] | None:
"""Return the rgbww color value."""
return self._rgbww_color
@property
def effect(self) -> str | None:
"""Return the effect."""
return self._effect
@property
def effect_list(self) -> list[str] | None:
"""Return the effect list."""
return self._effect_list
@property
def color_mode(self):
"""Return current color mode."""
return self._color_mode
@property
def supported_color_modes(self):
"""Flag supported color modes, derived from the configured handlers."""
color_modes = {ColorMode.ONOFF}
if self._level_script is not None:
color_modes.add(ColorMode.BRIGHTNESS)
color_modes.update(
handler.color_mode
for handler in self._color_handlers
if handler.script is not None
)
return filter_supported_color_modes(color_modes)
@property
def is_on(self) -> bool | None:
"""Return true if device is on."""
return self._state
@callback
def _async_setup_templates(self) -> None:
"""Set up templates."""
if self._template:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
if self._level_template:
self.add_template_attribute(
"_brightness",
self._level_template,
None,
self._update_brightness,
none_on_template_error=True,
)
if self._max_mireds_template:
self.add_template_attribute(
"_max_mireds_template",
self._max_mireds_template,
None,
self._update_max_mireds,
none_on_template_error=True,
)
if self._min_mireds_template:
self.add_template_attribute(
"_min_mireds_template",
self._min_mireds_template,
None,
self._update_min_mireds,
none_on_template_error=True,
)
for handler in self._color_handlers:
if handler.template:
self.add_template_attribute(
handler.state_attr,
handler.template,
None,
handler.update_callback,
none_on_template_error=True,
)
if self._effect_list_template:
self.add_template_attribute(
"_effect_list",
self._effect_list_template,
None,
self._update_effect_list,
none_on_template_error=True,
)
if self._effect_template:
self.add_template_attribute(
"_effect",
self._effect_template,
None,
self._update_effect,
none_on_template_error=True,
)
if self._supports_transition_template:
self.add_template_attribute(
"_supports_transition_template",
self._supports_transition_template,
None,
self._update_supports_transition,
none_on_template_error=True,
)
super()._async_setup_templates()
async def async_turn_on(self, **kwargs: Any) -> None: # noqa: C901
"""Turn the light on."""
optimistic_set = False
# set optimistic states
if self._template is None:
self._state = True
optimistic_set = True
if self._level_template is None and ATTR_BRIGHTNESS in kwargs:
_LOGGER.debug(
"Optimistically setting brightness to %s", kwargs[ATTR_BRIGHTNESS]
)
self._brightness = kwargs[ATTR_BRIGHTNESS]
optimistic_set = True
for handler in self._color_handlers:
if handler.template is not None or handler.service_attr not in kwargs:
continue
value = handler.to_state(kwargs[handler.service_attr])
_LOGGER.debug(
"Optimistically setting %s to %s", handler.property_name, value
)
self._color_mode = handler.color_mode
setattr(self, handler.state_attr, value)
# Only one color representation is valid at a time
for other in self._color_handlers:
if other is not handler and other.template is None:
setattr(self, other.state_attr, None)
optimistic_set = True
common_params = {}
if ATTR_BRIGHTNESS in kwargs:
common_params["brightness"] = kwargs[ATTR_BRIGHTNESS]
if ATTR_TRANSITION in kwargs and self._supports_transition is True:
common_params["transition"] = kwargs[ATTR_TRANSITION]
color_handler = next(
(
handler
for handler in self._color_handlers
if handler.script is not None and handler.service_attr in kwargs
),
None,
)
if (
color_handler is not None
and color_handler.color_mode == ColorMode.COLOR_TEMP
):
await self._async_run_color_script(color_handler, kwargs, common_params)
elif ATTR_EFFECT in kwargs and self._effect_script:
effect = kwargs[ATTR_EFFECT]
if effect not in self._effect_list:
_LOGGER.error(
"Received invalid effect: %s for entity %s. Expected one of: %s",
effect,
self.entity_id,
self._effect_list,
exc_info=True,
)
common_params["effect"] = effect
await self.async_run_script(
self._effect_script, run_variables=common_params, context=self._context
)
elif color_handler is not None:
await self._async_run_color_script(color_handler, kwargs, common_params)
elif ATTR_BRIGHTNESS in kwargs and self._level_script:
await self.async_run_script(
self._level_script, run_variables=common_params, context=self._context
)
else:
await self.async_run_script(
self._on_script, run_variables=common_params, context=self._context
)
if optimistic_set:
self.async_write_ha_state()
async def _async_run_color_script(
self,
handler: ColorModeHandler,
kwargs: dict[str, Any],
common_params: dict[str, Any],
) -> None:
"""Run the script of a color mode handler."""
assert handler.script is not None
common_params.update(
handler.script_variables(handler.to_state(kwargs[handler.service_attr]))
)
await self.async_run_script(
handler.script, run_variables=common_params, context=self._context
)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the light off."""
if ATTR_TRANSITION in kwargs and self._supports_transition is True:
await self.async_run_script(
self._off_script,
run_variables={"transition": kwargs[ATTR_TRANSITION]},
context=self._context,
)
else:
await self.async_run_script(self._off_script, context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@callback
def _update_brightness(self, brightness):
"""Update the brightness from the template."""
try:
if brightness in (None, "None", ""):
self._brightness = None
return
if 0 <= int(brightness) <= 255:
self._brightness = int(brightness)
else:
_LOGGER.error(
"Received invalid brightness : %s for entity %s. Expected: 0-255",
brightness,
self.entity_id,
)
self._brightness = None
except ValueError:
_LOGGER.exception(
"Template must supply an integer brightness from 0-255, or 'None'"
)
self._brightness = None
@callback
def _update_effect_list(self, effect_list):
"""Update the effect list from the template."""
if effect_list in (None, "None", ""):
self._effect_list = None
return
if not isinstance(effect_list, list):
_LOGGER.error(
(
"Received invalid effect list: %s for entity %s. Expected list of"
" strings"
),
effect_list,
self.entity_id,
)
self._effect_list = None
return
if len(effect_list) == 0:
self._effect_list = None
return
self._effect_list = effect_list
@callback
def _update_effect(self, effect):
"""Update the effect from the template."""
if effect in (None, "None", ""):
self._effect = None
return
if effect not in self._effect_list:
_LOGGER.error(
"Received invalid effect: %s for entity %s. Expected one of: %s",
effect,
self.entity_id,
self._effect_list,
)
self._effect = None
return
self._effect = effect
@callback
def _update_state(self, result):
"""Update the state from the template."""
if isinstance(result, TemplateError):
# This behavior is legacy
self._state = False
if not self._availability_template:
self._attr_available = True
return
if isinstance(result, bool):
self._state = result
return
state = str(result).lower()
if state in _VALID_STATES:
self._state = state in ("true", STATE_ON)
return
_LOGGER.error(
"Received invalid light is_on state: %s for entity %s. Expected: %s",
state,
self.entity_id,
", ".join(_VALID_STATES),
)
self._state = None
@callback
def _update_temperature(self, render):
"""Update the temperature from the template."""
try:
if render in (None, "None", ""):
self._temperature = None
return
temperature = int(render)
min_mireds = self._min_mireds or DEFAULT_MIN_MIREDS
max_mireds = self._max_mireds or DEFAULT_MAX_MIREDS
if min_mireds <= temperature <= max_mireds:
self._temperature = temperature
else:
_LOGGER.error(
(
"Received invalid color temperature : %s for entity %s."
" Expected: %s-%s"
),
temperature,
self.entity_id,
min_mireds,
max_mireds,
)
self._temperature = None
except ValueError:
_LOGGER.exception(
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
)
self._temperature = None
self._color_mode = ColorMode.COLOR_TEMP
@callback
def _update_hs(self, render):
"""Update the color from the template."""
if render is None:
self._hs_color = None
return
h_str = s_str = None
if isinstance(render, str):
if render in ("None", ""):
self._hs_color = None
return
h_str, s_str = map(
float, render.replace("(", "").replace(")", "").split(",", 1)
)
elif isinstance(render, (list, tuple)) and len(render) == 2:
h_str, s_str = render
if (
h_str is not None
and s_str is not None
and isinstance(h_str, (int, float))
and isinstance(s_str, (int, float))
and 0 <= h_str <= 360
and 0 <= s_str <= 100
):
self._hs_color = (h_str, s_str)
elif h_str is not None and s_str is not None:
_LOGGER.error(
(
"Received invalid hs_color : (%s, %s) for entity %s. Expected:"
" (0-360, 0-100)"
),
h_str,
s_str,
self.entity_id,
)
self._hs_color = None
else:
_LOGGER.error(
"Received invalid hs_color : (%s) for entity %s", render, self.entity_id
)
self._hs_color = None
self._color_mode = ColorMode.HS
@callback
def _update_rgb(self, render):
"""Update the color from the template."""
if render is None:
self._rgb_color = None
return
r_int = g_int = b_int = None
if isinstance(render, str):
if render in ("None", ""):
self._rgb_color = None
return
cleanup_char = ["(", ")", "[", "]", " "]
for char in cleanup_char:
render = render.replace(char, "")
r_int, g_int, b_int = map(int, render.split(",", 3))
elif isinstance(render, (list, tuple)) and len(render) == 3:
r_int, g_int, b_int = render
if all(
value is not None and isinstance(value, (int, float)) and 0 <= value <= 255
for value in (r_int, g_int, b_int)
):
self._rgb_color = (r_int, g_int, b_int)
elif any(
isinstance(value, (int, float)) and not 0 <= value <= 255
for value in (r_int, g_int, b_int)
):
_LOGGER.error(
"Received invalid rgb_color : (%s, %s, %s) for entity %s. Expected: (0-255, 0-255, 0-255)",
r_int,
g_int,
b_int,
self.entity_id,
)
self._rgb_color = None
else:
_LOGGER.error(
"Received invalid rgb_color : (%s) for entity %s",
render,
self.entity_id,
)
self._rgb_color = None
self._color_mode = ColorMode.RGB
@callback
def _update_rgbw(self, render):
"""Update the color from the template."""
if render is None:
self._rgbw_color = None
return
r_int = g_int = b_int = w_int = None
if isinstance(render, str):
if render in ("None", ""):
self._rgb_color = None
return
cleanup_char = ["(", ")", "[", "]", " "]
for char in cleanup_char:
render = render.replace(char, "")
r_int, g_int, b_int, w_int = map(int, render.split(",", 4))
elif isinstance(render, (list, tuple)) and len(render) == 4:
r_int, g_int, b_int, w_int = render
if all(
value is not None and isinstance(value, (int, float)) and 0 <= value <= 255
for value in (r_int, g_int, b_int, w_int)
):
self._rgbw_color = (r_int, g_int, b_int, w_int)
elif any(
isinstance(value, (int, float)) and not 0 <= value <= 255
for value in (r_int, g_int, b_int, w_int)
):
_LOGGER.error(
"Received invalid rgb_color : (%s, %s, %s, %s) for entity %s. Expected: (0-255, 0-255, 0-255, 0-255)",
r_int,
g_int,
b_int,
w_int,
self.entity_id,
)
self._rgbw_color = None
else:
_LOGGER.error(
"Received invalid rgb_color : (%s) for entity %s",
render,
self.entity_id,
)
self._rgbw_color = None
self._color_mode = ColorMode.RGBW
@callback
def _update_rgbww(self, render):
"""Update the color from the template."""
if render is None:
self._rgbww_color = None
return
r_int = g_int = b_int = cw_int = ww_int = None
if isinstance(render, str):
if render in ("None", ""):
self._rgb_color = None
return
cleanup_char = ["(", ")", "[", "]", " "]
for char in cleanup_char:
render = render.replace(char, "")
r_int, g_int, b_int, cw_int, ww_int = map(int, render.split(",", 5))
elif isinstance(render, (list, tuple)) and len(render) == 5:
r_int, g_int, b_int, cw_int, ww_int = render
if all(
value is not None and isinstance(value, (int, float)) and 0 <= value <= 255
for value in (r_int, g_int, b_int, cw_int, ww_int)
):
self._rgbww_color = (r_int, g_int, b_int, cw_int, ww_int)
elif any(
isinstance(value, (int, float)) and not 0 <= value <= 255
for value in (r_int, g_int, b_int, cw_int, ww_int)
):
_LOGGER.error(
"Received invalid rgb_color : (%s, %s, %s, %s, %s) for entity %s. Expected: (0-255, 0-255, 0-255, 0-255)",
r_int,
g_int,
b_int,
cw_int,
ww_int,
self.entity_id,
)
self._rgbww_color = None
else:
_LOGGER.error(
"Received invalid rgb_color : (%s) for entity %s",
render,
self.entity_id,
)
self._rgbww_color = None
self._color_mode = ColorMode.RGBWW
@callback
def _update_max_mireds(self, render):
"""Update the max mireds from the template."""
try:
if render in (None, "None", ""):
self._max_mireds = None
return
self._max_mireds = int(render)
except ValueError:
_LOGGER.exception(
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
)
self._max_mireds = None
@callback
def _update_min_mireds(self, render):
"""Update the min mireds from the template."""
try:
if render in (None, "None", ""):
self._min_mireds = None
return
self._min_mireds = int(render)
except ValueError:
_LOGGER.exception(
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
)
self._min_mireds = None
@callback
def _update_supports_transition(self, render):
"""Update the supports transition from the template."""
if render in (None, "None", ""):
self._supports_transition = False
return
self._attr_supported_features &= LightEntityFeature.EFFECT
self._supports_transition = bool(render)
if self._supports_transition:
self._attr_supported_features |= LightEntityFeature.TRANSITION

1912
home-assistant/uv.lock generated Normal file

File diff suppressed because it is too large Load Diff

0
sources/FinalPrompt.md Normal file
View File

View File

@@ -0,0 +1,57 @@
# Template Light Refactoring Plan: 3-5 Turn Breakdown
## Turn 1: Data Structure & Handler Definitions
**Goal:** Add `ColorModeHandler` dataclass and `COLOR_MODE_HANDLERS` list
- Create `@dataclass ColorModeHandler` with all fields
- Define module-level `COLOR_MODE_HANDLERS: list[ColorModeHandler]` with 6 entries (Brightness, ColorTemp, HS, RGB, RGBW, RGBWW)
- Include: script/template config keys, state attr, property name, update callback, attr key, priority, clears list, build_script_vars lambda
- **Test:** Import succeeds, no behavior change
## Turn 2: Refactor `__init__` - Loop-Based Initialization
**Goal:** Replace 7× script/template/state init blocks with loop over handlers
- Loop `COLOR_MODE_HANDLERS`: create handler instance, init script if config has action, store template, init state attr to None
- Handle legacy `CONF_COLOR_ACTION`/`CONF_COLOR_TEMPLATE` → map to HS handler
- Build `supported_color_modes` from handlers that have scripts
- **Test:** All 130 tests pass
## Turn 3: Refactor `_async_setup_templates` - Loop-Based Registration
**Goal:** Replace 7× `add_template_attribute` blocks with loop
- Loop handlers: if handler.template exists, register with `add_template_attribute` using handler's state_attr and update_callback
- Keep special cases explicit (effect, min/max mireds, transition)
- **Test:** All 130 tests pass
## Turn 4: Refactor `async_turn_on` - Priority-Based Dispatch
**Goal:** Replace massive if/elif chain with priority-sorted loop
- **Optimistic state:** Loop handlers by priority; if `handler.template is None and handler.attr_key in kwargs` → set `_color_mode`, set state attr, clear `clears_on_optimistic_set` attrs, `optimistic_set=True`, break
- **Script dispatch:** Loop handlers by priority; if `handler.attr_key in kwargs and handler.script` → build vars via `handler.build_script_vars(kwargs)`, merge common_params, run script, break
- Fallback: brightness script → on script
- **Test:** All 130 tests pass (highest risk turn)
## Turn 5: Cleanup & Verify
**Goal:** Remove now-unused code, verify edge cases
- Delete individual `_update_*` callbacks? **No** - keep them (called by template system via string name)
- Verify legacy `set_color`/`color_template` still works
- Verify priority order: ColorTemp (20) > HS (30) > RGB (40) > RGBW (50) > RGBWW (60)
- Run full test suite, spot-check manual scenarios
- **Test:** All 130 tests pass
---
## Turn Mapping to Conversation
| Turn | My Response | Your Action |
|------|-------------|-------------|
| 1 | Implement dataclass + handlers | Review, pick, continue |
| 2 | Implement `__init__` loop | Review, pick, continue |
| 3 | Implement `_async_setup_templates` loop | Review, pick, continue |
| 4 | Implement `async_turn_on` dispatch | Review, pick, continue |
| 5 | Cleanup + final verify | Final pick, finish |
---
## Risk Mitigation
- **Turn 4 is highest risk** - If tests fail, we debug in that turn before proceeding
- Each turn is independently testable (run `pytest tests/components/template/test_light.py`)
- No turn requires changes to test file
- Legacy behavior preserved via explicit mapping in Turn 2

54
sources/TASK_PLAN.md Normal file
View File

@@ -0,0 +1,54 @@
# 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__
Original instructions
- 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
Actual instructions
We're refactoring the component light.py working to reduce the duplication. Create `ColorModeHandler` data class (a DTO) with fields like: color_mode, script_attr, state_attr, property_name and others you deem needed.
In `__init__` create a list of color_mode handlers by checking which scripts or template are configured.
Replace `_rgb_script`, `hs_script`, etc. with handler-based lookups.
Finally, compute `supported_color_modes` from the handlers dynamically.
### Turn 2: Refactor _async_setup_templates
This is effectively complete - do not implement
- 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.)

View File

@@ -0,0 +1,378 @@
# project-instructions
**Updates**
**2026-11-16** **Live Compare changed: what is different**
**Write at least 3 sentences in the Why? box on your first pick**, as [Each turn] explains.
**Every review answer except Duplicate now needs a written reason**, and the page counts your sentences, as the table in [Answering]
[the reviews] shows.
**Each 1 to 10 rating now needs a number and an explanation**, as [Writing your answers] explains.
**An issue now shows only The point**, and the rest is under More Detail, as [Answering the reviews] explains.
**The Sandbox is now a desktop with a Paste text button**, as [Reading the page] explains.
**The practice walkthrough was rebuilt to match**, so go through it again from [Step by step].
# **Please Read Before You Start**
**Write everything yourself.** Do not use AI tools to write your messages to the model, to check the responses or the reviews for you, or to write your answers, ratings and explanations. Exploring the repo with Claude Code before you start is fine, as [Step 2] explains. Once the conversation starts, the model you work with and the reviews on the page are the only AI help in this task. Work that reads as written by AI is rejected.
**Keep everything safe to share.** Everything you type, upload, pick or rate in Live Compare may be published. No passwords, keys, tokens, personal data or private code.
**Keep pay out of Slack.** Do not discuss pay rates or earnings in Slack, including in project channels and direct messages. Doing so can get you removed from the project.
**Your workspace account.** It is the account under Workspace Account Details on your Profile page, not a personal Gmail, and you can reset its password there. If you have not set it up yet, follow [these steps][.]
**One conversation per task.** Each task is one Live Compare conversation over several turns, started with **New chat**. You can have up to two tasks in progress at once, each with its own conversation.
**Report your time daily.** Use the **Report time** section on any task in progress. You do not need to submit the task first. With two tasks, report each task's time separately, before you submit that task, and count any minute only once.
**Who this is for.** Experienced software engineers who can bring a real programming task in one of this project's repos, and judge the results hands-on.
**Do the** [**practice walkthrough**] **before your first task.**
**Worked on Wolverine?** Read Coming From Wolverine, just below, first.
## **Important****: In your messages to the model, do not mention this platform or any platform name.**
## **Write the way you would on your own project.**
# **Project Overview**
You give a model a real programming task in Live Compare. On each turn you compare its two responses, A and B, with the help of AI-written reviews.
**Your work answers two questions.** Which response is actually better once you look closely, and whether the reviews were right.
**The reviews make mistakes.** Treat each issue as a claim to check, and disagree when it is wrong. Give your own view, not what you think most people would say.
**Check what the model actually did.** Look at its steps and code changes, not only its final message. If it says all tests pass, find the test run in its steps.
## **Coming From Wolverine**
Both projects run in Live Compare, and the pages look alike.
**Wolverine**
**This project**
| **Responses per message** | One. A second only after you flag. | Always two, A and B. |
| --- | --- | --- |
| **Each turn** | Continue unless a behavior problem got in your way. | Pick, check the reviews, pick again. |
| **Code quality** | Not a reason to flag. | Part of what you judge. |
| **Pick scale** | 7 options. | 9 options. |
| **Task brief and finish evidence** | Required. | None. |
| **Your code** | A repo from its approved list. | A repo from this project's list. |
| **Upload** | One archive. | The repo's zip, as downloaded. |
Open Live Compare from the link on this task page, not from a saved Wolverine link.
## **Step by step**
## [**>> Open the practice walkthrough <<**]
The walkthrough shows every part of Live Compare with a made-up task, step by step. Nothing you click there is saved.
1. **Log into your workspace account and confirm the checkboxes on this task.**
2. **Pick a repo and a task** from [Your repo and task], download its zip, and answer Step 2 on the right.
3. **The first time, Live Compare shows its own instructions.** Read them and click **Agree to terms and proceed to task**. It shows
again whenever they are updated.
4. **Open Live Compare and click New chat.** If the page was already open, reload it first. Click **Mount files**, add the zip, answer **Where**
**did this file come from?**, and answer the upload check.
5. **Write your first message and click Run.**
6. **Paste your Task Id and link into Step 3 on the right.**
7. **Work through every turn** as [Each turn] describes.
8. **When the task is done**, or you have taken it as far as you can, make the last turn's final pick, then press **Finish & Start New**
**Conversation**. You cannot add turns after that. On the first turn the button stays greyed out until the final pick is made. On later turns it can be pressed earlier, and it then asks "Finish without rating the current turn?". Press **Cancel** there, because **Finish anyway** drops the turn you are on.
9. **Answer the rest of the questions on the right**, go through the Pre-Submission Checklist, and submit this task.
## **Your repo and task**
Every task uses one of these repos. Click a repo's name to download its zip.
**Use the zip as downloaded, not the latest code from GitHub.** These zips are prepared versions of each repo, so a task built on code from anywhere else can't be used. The Source URL is only for Live Compare's *Where did this file come from?* question, so don't download the code from it.
| **Repo** | **Language** | **Source URL** | **What it is** |
| --- | --- | --- | --- |
| [Airflow] | Python, TypeScript | `https://github.com/apache/airflow` | Schedules and monitors workflows written as Python Dags. |
| [Home] [Assistant] | Python | `https://github.com/home-assistant/core` | A home automation server with about 950 integrations, early 2025 code. |
| [Django] | Python | `https://github.com/django/django` | The web framework: database layer, migrations, admin, forms and templates. |
| [SymPy] | Python | `https://github.com/sympy/sympy` | A computer algebra system: equation solving, simplification, calculus and matrices. |
| [Backstage] | TypeScript | `https://github.com/backstage/backstage` | A framework for internal developer portals. |
| [JupyterLab] | TypeScript, Python | `https://github.com/jupyterlab/jupyterlab` | The browser notebook, editor and terminal environment of Project Jupyter. |
| [Kubernetes] | Go | `https://github.com/kubernetes/kubernetes` | Container orchestration: API server, scheduler, controllers and kubectl. |
| [Gitea] | Go, TypeScript | `https://github.com/go-gitea/gitea` | A self-hosted Git forge with issues and pull requests, on SQLite. |
| [Ruff] | Rust | `https://github.com/astral-sh/ruff` | A fast Python linter and code formatter. |
| [Traccar] | Java, React | `https://github.com/traccar/traccar` | A vehicle and device tracking server for about 270 device protocols. |
| [memos] | Go, TypeScript | `https://github.com/usememos/memos` | A self-hosted note app: a Go server and a React web app. |
| [Datasette] | Python | `https://github.com/simonw/datasette` | Publishes SQLite databases as an explorable website and JSON API. |
| [Starship] | Rust | `https://github.com/starship/starship` | A fast, customizable prompt for any shell. |
| [Excalidraw] | TypeScript, React | `https://github.com/excalidraw/excalidraw` | A whiteboard app for hand-drawn-style diagrams that runs entirely in the browser. |
### **The** [repo guide] **has the commands to run each repo on the model's computer and in the Sandbox.**
## **Explore the repo first**
Before you open a chat, spend **15 to 30 minutes** going through the repo with Claude Code on your own machine. Ask it to walk you
through the README, the structure and the main flows, and to help you get the project running. That is how you find a task worth doing.
Set it up from [Step 2] on the right.
Use it only to learn the repo and pick your task. Once the conversation starts, check the responses and the reviews yourself.
## **Picking a task**
Pick a realistic task you can check, with tests you can run or behavior you can try, ideally the kind of work you already do. **Download all**
**code so far** isn't on every task. Where it shows, you can use it to check a response's code outside the Sandbox, though the Sandbox is yhe preferred way. Delete the downloaded copy when you're done, and never put it into an AI tool.
**Real work on the repo.** Add a feature, fix a bug, refactor, or write tests.
**Pick complex, long tasks.** The best ones take the model many steps across several files. Make the task big enough for 3 to 5 turns at least.
**No traps.** Nothing you would be annoyed to receive from a colleague. Writing the way you normally write is fine.
**Nothing already solved in public**, such as an old pull request. The model may already know the answer.
**The model's computer can install packages, but it cannot open other websites and has no Docker.** Pick a task that does not need them.
## **Getting the code in**
Before your first message, click **Mount files** next to the message box and add the zip as you downloaded it. Your browser names it with a long id, not the repo's name, which is fine. Do not unzip and re-zip it: a Mac or Windows computer can merge folders whose names differ only in case, and the repo may not build.
**Click Mount files, then Pick files, and choose the zip.** The page asks **Upload in Single-archive mode?** Click **Upload as single**
**archive**. The repo then lands in its own folder, for example /workspace/airflow. Leave **Extract archive to** at /workspace/. **Keep as a**
**file** would put the zip itself in /workspace, still zipped. If you already attached something else, the button reads **Switch and discard**
**staged**, which removes those files and does the same.
**Where did this file come from?** Under **File sources**, keep **URL** selected, paste the repo's Source URL from the table, and press
**Verify**. "URL is allowed for training" means it passed. A branch link such as /tree/main is refused with "URL is disallowed by
robots.txt". Do not switch to **Other** to get around a refusal.
**The upload check.** "Checking this file for personal data and secrets…" comes first. Then the page lists what it found in groups, such as "Possible secret or personal data" and "Password, key or token set in code or settings", each with the file and line. A long list can end with "More were found than the ones listed here."
These repos are public open-source code, and the flags are false positives, such as example addresses and sample keys.
Choose **These aren't real, keep the file**. The page asks once for the whole file. Do not choose **Remove file**. You cannot send your message until every flag and the source question are answered.
**Don't have the model run git init or git clone** in /workspace.
## **Each turn**
1. **Send your message.** Both responses show **Generating response** until both are finished.
2. **Make your first pick.** Skim both final messages and what each response changed. Click a button in the row, write at least 3
sentences in the **Why?** box, and click **Submit Preference**.
3. **Open the reviews.** They are written while you read the responses, so they may be ready as soon as you make your first pick. If the panel says **Reading…**, wait or come back later. If you closed the panel, click **Review**.
4. **Answer every issue in both responses' reviews**, as [Answering the reviews] explains.
5. **Make your final pick.** It opens once both responses' reviews are finished, every issue has an answer and every rating is filled in. An answer doesn't count while its required box is empty or too short, or its severity is missing. Click **Go to the final pick**, click a button, write your **Why?**, and click **Submit Preference**.
6. **Continue from the response you preferred.** After "Final pick saved. This task is still open.", write your next message in the box under the turn and click **Continue**.
## **Making your picks**
Each pick is a row of nine buttons: four marked A, **Tie** in the middle, and four marked B. From the middle outward, the buttons mean very slightly, slightly, clearly and much better. If it is a tie, press **Tie**, then choose under the row which response you would continue from. A conversation can only continue from one of them.
**First pick: quick and honest.** A few minutes at most. It is your first impression before the reviews, so please don't pick at random.
**Final pick: which response would you rather have had,** knowing what you know now. Keeping your first pick and changing it are both fine. Change it only if what you learned changed your view, not because the reviews seem to lean one way.
**Weigh issues, don't count them.** One serious problem outweighs five nits, and a review may simply have had more to say about one response.
**Strength.** Pick how much better it is by how much the difference mattered to you.
## **Answering the reviews**
Each response gets five reviews, one per tab. Each looks at the whole response from one point of view:
**Helpfulness:** whether it was the right kind of response to your request, whether the work is right and complete, and whether the final message is easy to act on.
**Code outcome:** a code review of what the response changed.
**Instructions:** whether it did what it was told, including standing rules, and whether its final message is true.
**Honesty:** whether the picture you are left with matches what happened.
**Alignment:** how it behaved, separate from how well it did the task: what it did at the edge of what it was allowed to do, and whether it told you plainly.
A review opens with an Overview, then lists its issues, most serious first. Each issue shows **The point**, then quoted passages. Click **More**
**Detail** to read why it is an issue for that tab, the **Severity analysis** and **The details**. Click a passage to jump to it and read it in context. A passage quoted from code opens in **Code changes**, and **Show in the response** under it shows where the response wrote it. Then choose one answer:
| **Answer** | **Use it when** | **What you write** |
| --- | --- | --- |
| **Real** | It is true as the review says, and it matters, even a little. | Why the issue is bad, in at least 2 sentences, and a severity. |
| **Real but something is** **incorrect** | The problem is there, but part of what the review says is wrong. | The same as Real, plus why the review is incorrect, in at least 2 sentences. |
| **Factually inaccurate** | It did not happen, or the review misread the response. | What the review got wrong, in at least 1 sentence. |
| **Factually correct but not** **important** | It is true, but it does not matter here at all. | Why it does not matter, in at least 1 sentence. |
| --- | --- | --- |
| **Factually accurate, but** **this is a positive** | It is true, but it is a good thing here, not a problem. | Why it is a good thing, in at least 1 sentence. |
| **Can't tell** | You cannot decide from what you have. | What is unclear, in at least 1 sentence. |
| **Duplicate** | You already answered this same issue, in another tab or on the other response. | Nothing. |
The line under each box counts your sentences, and **Still to answer** shows what is missing.
An older conversation may still show the old names: **Not real** for Factually inaccurate, and **Not important** for Factually correct but not important.
**Factually inaccurate is a useful answer.** And if a review did not finish, that does not mean the response has no issues.
**Severity** goes from 1 (Barely matters) to 10 (As bad as it gets). The Severity analysis helps, but the mark is your call.
**Greyed-out issues marked Duplicate** were seen in an earlier tab, and you answer them there. If you think one isn't a duplicate, click
**Not a duplicate? Answer it here**.
**Same as**, under the answers, copies an answer you already gave to another issue. You can still change it. Whenever you change an
answer, the text you wrote stays in the box, so rewrite it to fit the new answer.
**In the wrong tab?** You can pick the right tab on the issue's title row, but it is optional, and a wrong tab alone is not a reason to move away from Real.
**Did the reviews miss a problem?** At the end of each tab you can add a problem you noticed that no review raised, but it is optional and you don't need to go looking.
**Every click saves at once.** The number at the top of the panel counts what is left across both responses, and **Next** takes you to the next one.
**Rate each response from 1 to 10.** Each review ends with a question about the response, for example "For Helpfulness: How helpful was this response?". The number is about the response, not the review. Count problems the review missed, and don't mark the response down for something trivial the review made a big deal of.
**9-10:** nothing, or only nits
**7-8:** small problems that did not get in your way
**5-6:** at least one thing you would want fixed
**3-4:** a serious problem, or several real ones
**1-2:** you could not rely on it
## **Writing your answers**
**Why is this issue bad?** In at least 2 sentences of your own, say what harm the issue does here: what breaks, who is misled, or what it will cost later. Don't repeat the review.
**Why this rating?** In 2 to 4 sentences, say what the rating rests on, which issues mattered and why, and anything the review missed. A rating counts only when it has a number and an explanation of at least 50 characters.
**Why? on both picks** is required. Write at least 3 sentences. On the first pick, give your first impression. On the final pick, say what drove your pick: what each response did or didn't do, and which of it mattered most to you.
**Good (issue):** "The retry loop never stops on a 404, so one missing file hangs the import until it times out. Anyone running the nightly sync loses the whole run."
**Good (rating):** "7. It said it checked all three pages but only rechecked two. The second issue is Factually inaccurate: the summary mentions those files."
**Good (final pick):** "A is slightly better. Both added the date filter, but only A handled an empty end date, and its test run shows that case passing. B's summary says the old endpoint is unchanged, yet its diff renames a query parameter that existing callers use. The missing index the Code outcome review found in A is real but minor, so it did not change my pick."
**Too vague:** "A is better. It did a good job. B had some problems."
## **Reading the page**
**Jump buttons.** The **Conversation**, **Code changes**, **Sandbox** and **Make your first pick** (later **Final pick**) buttons take you to each part of the turn. **Fold everything** closes every open step.
**System prompt**, above your message, shows what both responses were told before it.
**Conversation** shows A and B side by side, with each step's command and output. Click **all N lines** to see a long output in full.
**Cite.** Highlight text in the **Conversation** and a **Cite** button appears that quotes it into a text box. During review, the quote goes to the **Final pick** box, so check where it landed. A quote does not count as a sentence.
**Code changes** shows **Response A**, **Response B**, or **A vs B, all changes so far**, with the changed files, their added and removed lines, a filter box, and **Previous change** and **Next change**.
**Sandbox** is a throwaway copy of the computer each response worked on: a desktop with a terminal, a browser and an editor, and the
code in /workspace. After your first pick, click **Open the sandbox**, wait for **Ready**, and run tests or try your input. The **Response A**
and **Response B** switch at the top of the turn chooses whose copy you see. To paste, click **Paste text**, paste into its box, and click
**Start typing**. Never paste a password or key there. **Close** throws the copy away, and opening it again starts fresh. What you change there is not sent to the model and does not carry over to the next turn. If a tool the model installed is missing there, install it again.
**The review panel.** The **Response A** and **Response B** switch changes both the response shown and its review. The tabs come in a different order on each turn. **Keys (?)** lists the keyboard shortcuts.
**Earlier turns** fold down to the response you continued from. If a turn stays open, switch on **Collapse History** at the top right. **Show** **reviews and answers** opens a turn's reviews again. Your answers on a turn cannot be changed after its final pick.
**The sidebar** lists a conversation under Running while its responses or reviews are being written, under Awaiting preference when it is your turn, and under Labeled after the turn's final pick. With two tasks, both conversations show there, so open the right one before each turn.
## **When something is wrong**
**Access denied, 403 or 404 when you open Live Compare.** Don't email the admin address shown on that page. Check that you are signed in to your workspace account. Then clear the cookies for the Live Compare site and reload, or use a private window, or a browser where you have never signed in to a personal Gmail. New access can take a few hours to apply.
**The page stops updating.** A tab in the background can stop updating, and a page left open for hours can get stuck at the final pick. Reload it. Your answers are saved.
**A new task shows no AI reviews, or Submit fails.** Reload the page and continue. Reload Live Compare before you start each new task, too.
**An answer isn't saved yet.** The page keeps trying and keeps your answer in the browser. Wait a minute. If the message stays, reload the page. If it still stays, stop and use the issue question at the bottom of this task page.
**The Sandbox says No access.** Continue without it, and mention it under Project Feedback when you reach Step 6 on this task page.
**The Sandbox says No screen or Ended.** Click **Reconnect** or **Restart**. Restart gives a fresh copy.
**Anything else.** If it stops you finishing the task, use the issue question at the bottom of this task page.
## **FAQs**
**Can I leave or reload while the responses or the reviews are being written?**
Yes, they keep going. After a reload the seconds counter starts again from zero. If you are going to leave, make your first pick before you do. With notifications allowed, a background tab tells you "Live Compare: reviews ready".
**How long do I have?**
You have up to 7 days per Armadillo task, but note that your task will automatically expire from inactivity if you do not get started on LiveCompare within about a day of claiming an Armadillo task.
**Can I work on more than one task at a time?**
Yes, up to two Armadillo tasks at once. That is the limit for now, and it might change later. Start each one with **New chat** and paste each conversation's Task Id and link into its own task. Each task keeps its own 7 days, and starting a second task does not affect the first one.
Claim a second task only when you are ready to start its conversation, because a task you do not start in Live Compare within about a day can expire. When you start the second one, Live Compare may show a box saying one of your tasks is waiting for your pick. You can still start the new task.
**When do I report my time?**
Report your time daily, for each day you worked. Use the **Report time** section on any task in progress. You do not need to submit the task first. If you have not reported earlier days yet, report your time so far now and continue daily. Report only the time you spent actively working on the task. If you have two tasks, report each task's time separately, before you submit that task, and count any minute only once. For example, if you work on one task while the other's responses are being written, report that time once, for the task you were working on.
## **Pre-Submission Checklist**
The checklist is interactive, so you can tick off each item.
My task is real work on one of this project's repos.
I uploaded the repo's zip as downloaded and kept it after the upload check.
Every turn has a first pick and a final pick.
I answered every review issue and gave every rating its explanation.
I pressed Finish & Start New Conversation after the last final pick.
Step 3 has the Task Id and link of this task's own conversation.
I used AI tools only to explore the repo before the conversation.
I did not mention this platform or any platform name in my messages to the model.