From a5aa06add46a55d90b33804f54dcb91f097e034c Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 20:38:53 +0100 Subject: [PATCH 01/49] docs: add HA Controller design spec and implementation plans Co-Authored-By: Claude Opus 5.5 --- .../2026-11-16-ha-controller-1-foundation.md | 336 +++++++ .../2026-11-16-ha-controller-2-integration.md | 587 ++++++++++++ .../plans/2026-11-16-ha-controller-3-panel.md | 433 +++++++++ .../2026-11-16-ha-controller-4-firmware.md | 875 ++++++++++++++++++ .../2026-11-16-ha-controller-5-release.md | 340 +++++++ .../specs/2026-11-16-ha-controller-design.md | 467 ++++++++++ .../specs/assets/editor-reference.png | Bin 0 -> 107510 bytes 7 files changed, 3038 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md create mode 100644 docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md create mode 100644 docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md create mode 100644 docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md create mode 100644 docs/superpowers/plans/2026-11-16-ha-controller-5-release.md create mode 100644 docs/superpowers/specs/2026-11-16-ha-controller-design.md create mode 100644 docs/superpowers/specs/assets/editor-reference.png diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md new file mode 100644 index 0000000..777617c --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md @@ -0,0 +1,336 @@ +# HA Controller — Plan 1: Foundation & Protocol Contract + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Set up the repository conventions, the documentation skeleton and the Claude Code guidance. Then write the cross-language protocol contract that plans 2–5 build on: the protocol doc, the emoji list and the shared fixtures. + +**Architecture:** Documentation and data only, plus Python tests that keep the docs linked and the fixtures well formed. The fixtures are the executable contract: plan 2 (Python), plan 3 (TypeScript) and plan 4 (C++) all test against them. + +**Tech Stack:** Markdown, JSON, Python 3.14, pytest, ruff, GitHub Actions. + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` + +## Global Constraints + +- Everything is written in English: code, comments, docs, UI strings and commit messages. +- Repository `pyxel-dev/HA-controller`. Product name "HA Controller". Integration domain `ha_controller`. ESPHome project `pyxel-dev.ha-controller`. +- Python 3.14, pytest, ruff. +- Layout model and protocol v1 exactly as spec §6–§7. Golden revisions: `c4aad3fa` (empty), `90538742` (reference), `5387d4ea` (emoji-variation). +- `3D_models/` and `files/` stay untouched. + +## Review Focus + +1. **Invalid fixtures that break more than one rule.** Plans 2–3 would then pass for the wrong reason. Each invalid fixture is the reference layout (or `single`/`empty`) plus exactly one mutation. Plans 2 and 3 assert the full error list equals exactly the one expected error. +2. **Emoji entries the firmware cannot render.** This means multi-code-point sequences: U+FE0F, ZWJ, skin tones. `test_emoji_list_is_well_formed` asserts one code point per entry. +3. **Non-UTF-8 or BOM-prefixed fixture files** (they hold `°`, `—` and emoji). `test_all_fixtures_are_utf8_json` rejects them. +4. **A golden `rev` that drifts from the canonical hash.** `test_payload_revisions_match_canonical_hash` recomputes it. +5. **Docs linking to files that do not exist yet.** Later plans add docs. `test_relative_links_resolve` keeps every relative link valid at each commit. + +--- + +### Task 1: Repository conventions, docs skeleton and CI + +**Files:** +- Create: `CLAUDE.md`, `docs/README.md`, `docs/architecture.md`, `pyproject.toml`, `requirements_test.txt`, `tests/__init__.py`, `tests/docs/__init__.py`, `tests/docs/test_links.py`, `.github/workflows/ci.yml` +- Modify: `README.md` (rewrite in English), `.gitignore` + +**Interfaces:** +- Produces: + - `pyproject.toml` with `[tool.pytest.ini_options] testpaths = ["tests"]`, `asyncio_mode = "auto"`, and `[tool.ruff] target-version = "py314"`, `line-length = 100`, lint rules `E,F,I,UP,B`. + - `requirements_test.txt` (`pytest`, `ruff`). Plan 2 replaces `pytest` with the Home Assistant test harness. + - `.github/workflows/ci.yml` with a single job `python`. Later plans add jobs. + - `docs/README.md` as the docs index. Later plans add links. + - `CLAUDE.md` with a `## Commands` table and a `## Skills and agents` section. Later plans append rows. + +- [ ] **Step 1: Write the failing tests** in `tests/docs/test_links.py`. + +```python +DOC_ROOTS = ["README.md", "CLAUDE.md", "docs"] # docs/superpowers/** is excluded + +def test_relative_links_resolve(): + # For every markdown link [text](target) whose target does not start with + # http://, https://, mailto: or '#': strip the '#anchor' and assert + # (md_file.parent / target).resolve().exists(); report every broken link. + ... + +def test_docs_index_lists_every_doc(): + # Every docs/*.md file except docs/README.md is linked from docs/README.md. + ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/docs -v` +Expected: FAIL (`docs/README.md` is missing). + +- [ ] **Step 3: Write the docs and config** + - **`README.md`:** + - Keep the title "HA Controller". + - One paragraph pitch, then feature bullets: + - block map editor in Home Assistant; + - edge-swipe navigation; + - light and thermostat knobs; + - custom blocks; + - automatic firmware updates. + - Status line "Under active development". + - Relative link `docs/README.md`. + - Keep the 3D-models section and fix its link to `3D_models/`. + - **`docs/README.md`:** title "HA Controller documentation", one bullet per doc (`architecture.md` for now) and a link to the design spec under `superpowers/specs/`. + - **`docs/architecture.md`:** spec §3 rewritten for contributors. Include the diagram, the subsystems and the repository layout table, plus one paragraph each on: + - the hello → layout/states handshake; + - controls → service calls; + - firmware updates. + - **`CLAUDE.md`:** + - Title "HA Controller — guidance for Claude Code" and a two-line purpose. + - `## Rules`: + - English only. + - One version for the whole repo; change it only with `python scripts/versioning.py bump X.Y.Z` (added in plan 5). + - The protocol is defined in `docs/protocol.md` and pinned by `protocol/fixtures/`. + - TDD. + - Never commit `esphome/secrets.yaml`. + - Specs and plans live in `docs/superpowers/`. + - `## Repository map`: the spec §3 table. + - `## Commands`: `pytest`, `ruff check .`. + - `## Skills and agents`: empty list. + - **`.gitignore`:** keep `.DS_Store`. Add `__pycache__/`, `.pytest_cache/`, `.ruff_cache/`, `.venv*/`, `node_modules/`, `frontend/coverage/`, `custom_components/ha_controller/frontend/*.js`, `esphome/.esphome/`, `esphome/secrets.yaml`, `build/`, `dist/`, `site/`. + +- [ ] **Step 4: Run the tests and lint** + +Run: `pytest tests/docs -v && ruff check .` +Expected: PASS, no lint findings. + +- [ ] **Step 5: Add CI.** In `.github/workflows/ci.yml`, workflow `CI`: + - Triggers: `push` to `main` and `pull_request`. + - Job `python` on `ubuntu-latest`: `actions/checkout@v4`, `actions/setup-python@v5` with `python-version: "3.14"`, `pip install -r requirements_test.txt`, `ruff check .`, `pytest`. + +- [ ] **Step 6: Commit** + +```bash +git add README.md CLAUDE.md docs/README.md docs/architecture.md pyproject.toml requirements_test.txt tests .gitignore .github/workflows/ci.yml +git commit -m "chore: add repository conventions, docs skeleton and CI" +``` + +--- + +### Task 2: Protocol contract — protocol doc, emoji list, fixtures and Claude guidance + +**Files:** +- Create: + - `docs/protocol.md`, `protocol/README.md`, `custom_components/ha_controller/emoji.json` + - `protocol/fixtures/**` (see the tables below) + - `tests/protocol/__init__.py`, `tests/protocol/test_fixtures.py` + - `.claude/skills/protocol-change/SKILL.md`, `.claude/agents/protocol-guardian.md` +- Modify: `docs/README.md` (link `protocol.md`), `CLAUDE.md` (skills and agents list) + +**Interfaces:** +- Produces (consumed by plans 2, 3 and 4). All fixture files are UTF-8 JSON without a BOM. + - `custom_components/ha_controller/emoji.json`: a JSON array of the 64 strings below, in this order: + `💡 🔥 ❄ 🌡 💧 🌬 ☀ 🌙 ⭐ ☁ ⛅ 🌧 ⚡ 🔋 🔌 🏠 🛋 🛏 🛁 🚿 🍳 🍽 ☕ 🍷 🧺 🪴 🚪 🪟 🔒 🔓 🔑 🔔 🔕 🔊 🔇 🎵 📺 🎮 💻 📱 ⏰ 📅 🚗 🚲 🐶 🐱 👶 👋 👍 ❤ 😀 😴 🎉 🎄 ✅ ❌ ⚠ ℹ ▶ ⏸ ♻ 🌀 🧊 🏡` + - `protocol/fixtures/layouts/valid/.json`: a stored layout. + - `protocol/fixtures/layouts/invalid/.json`: `{"expect": {"code": str, "ref": str | null}, "layout": {...}}`. The stem equals `code` or starts with `code-`. + - `protocol/fixtures/payloads/valid/.json`: `{"layout": "", "payload": {...}}`. + - `protocol/fixtures/payloads/invalid/.json`: `{"expect": "bad_json" | "unsupported_version" | "invalid_payload", "text": ""}`. + - `protocol/fixtures/states/.json`: + + ```json + { + "layout": "reference", + "unit": "°C", + "entity_ids": ["…"] | null, + "hass_states": {"": {"state": "…", "attributes": {}}}, + "registry_options": {"": {}}, + "updates": [] + } + ``` + + `registry_options` is optional; `updates` lists the expected update objects. + - `protocol/fixtures/controls/.json`: `{"layout": "reference", "hass_states": {...}, "event": {"block", "item", "op", "value"}, "expect_call": {"domain", "service", "data"} | null}`. + - `protocol/fixtures/colors.json`: `[{"bg": "#RRGGBB", "text": "#000000" | "#FFFFFF"}]`. + +- [ ] **Step 1: Write the failing tests** in `tests/protocol/test_fixtures.py`. Local helpers: `canonical_rev(payload) -> str` and `luminance(hex) -> float` (spec §5.5/§7.3). + +```python +def test_emoji_list_is_well_formed(): + emoji = json.loads(EMOJI.read_text("utf-8")) + assert len(emoji) == 64 and len(set(emoji)) == 64 + assert all(len(e) == 1 for e in emoji) # one code point each + assert "️" not in "".join(emoji) + assert {"💡", "🔋", "⚡", "☀", "👋"} <= set(emoji) and "🦄" not in emoji + +def test_all_fixtures_are_utf8_json(): ... # every protocol/fixtures/**/*.json: no BOM, json.loads ok + +def test_invalid_layout_fixtures_declare_known_codes(): + # expect.code in the 18 codes of spec §6 except payload_too_large + # expect.ref is str or None; stem == code or stem.startswith(code + "-") + +def test_payload_revisions_match_canonical_hash(): + revs = {p.stem: json.loads(p.read_text("utf-8"))["payload"]["rev"] for p in VALID_PAYLOADS} + assert revs == {"empty": "c4aad3fa", "reference": "90538742", "emoji-variation": "5387d4ea"} + # and canonical_rev(payload) == payload["rev"] for each file + +def test_fixtures_reference_existing_layouts(): ... # "layout" fields of payloads/states/controls exist in layouts/valid + +def test_color_fixture_matches_luminance_rule(): + for case in COLORS: + assert case["text"] == ("#000000" if luminance(case["bg"]) > 0.30 else "#FFFFFF") +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/protocol -v` +Expected: FAIL (the files are missing). + +- [ ] **Step 3: Write `emoji.json` and the fixtures.** + +**Valid layouts:** +- **`empty.json`:** `{"version": 1, "start": null, "settings": {"sleep_timeout": 20}, "blocks": []}`. +- **`reference.json`:** the JSON of spec §6, verbatim (it includes `"settings": {"sleep_timeout": 20}`). +- **`single.json`:** `{"version": 1, "start": "b1", "settings": {"sleep_timeout": 0}, "blocks": [{"id": "b1", "x": 3, "y": -2, "name": "Solo", "background": "#000000", "font_size": "s", "type": "custom", "items": []}]}`. +- **`emoji-variation.json`:** `{"version": 1, "start": "b1", "settings": {"sleep_timeout": 3600}, "blocks": [{"id": "b1", "x": 0, "y": 0, "name": "Snow", "background": "#FFFFFF", "font_size": "xl", "type": "custom", "items": [{"id": "i1", "kind": "emoji", "emoji": "❄️", "font_size": null}]}]}`. The emoji is U+2744 followed by U+FE0F. + +**Invalid layouts.** Each is a single mutation of the base layout: + +| File | Base | Mutation | expect | +|---|---|---|---| +| `invalid_structure.json` | reference | `"blocks": {}` | `invalid_structure`, `null` | +| `invalid_structure-version.json` | reference | `"version": 2` | `invalid_structure`, `null` | +| `invalid_structure-settings.json` | reference | `"settings": 20` | `invalid_structure`, `null` | +| `too_many_blocks.json` | — | 33 blocks: block N is `{"id": "bN", "x": N-1, "y": 0, "name": "Block N", "background": "#000000", "font_size": "m", "type": "custom", "items": []}` for N = 1…33, start `b1`, `"settings": {"sleep_timeout": 20}` | `too_many_blocks`, `null` | +| `invalid_sleep_timeout.json` | reference | `"settings": {"sleep_timeout": 3}` | `invalid_sleep_timeout`, `null` | +| `invalid_id.json` | reference | b4 id → `"B4"` | `invalid_id`, `"B4"` | +| `duplicate_id.json` | reference | item i5 id → `"b1"` | `duplicate_id`, `"b1"` | +| `coordinate_out_of_range.json` | single | b1 `x: 33` | `coordinate_out_of_range`, `"b1"` | +| `duplicate_position.json` | reference | b4 → `x: 0, y: 0` | `duplicate_position`, `"b4"` | +| `invalid_start.json` | reference | `"start": "zz"` | `invalid_start`, `null` | +| `invalid_start-empty.json` | empty | `"start": "b1"` | `invalid_start`, `null` | +| `disconnected.json` | reference | b4 → `y: 2` | `disconnected`, `"b4"` | +| `invalid_name.json` | reference | b2 name → `" "` | `invalid_name`, `"b2"` | +| `invalid_background.json` | reference | b2 background → `"red"` | `invalid_background`, `"b2"` | +| `invalid_font_size.json` | reference | b2 font_size → `"xxl"` | `invalid_font_size`, `"b2"` | +| `invalid_font_size-item.json` | reference | i1 font_size → `"huge"` | `invalid_font_size`, `"i1"` | +| `invalid_type.json` | reference | b2 type → `"gauge"` | `invalid_type`, `"b2"` | +| `invalid_entity.json` | reference | b1 entity_id → `"switch.kettle"` | `invalid_entity`, `"b1"` | +| `invalid_entity-item.json` | reference | i3 entity_id → `"not an entity"` | `invalid_entity`, `"i3"` | +| `too_many_items.json` | reference | b3 items + `{"id": "i6", "kind": "text", "text": "A", "font_size": null}`, `{"id": "i7", …"B"…}` | `too_many_items`, `"b3"` | +| `invalid_item.json` | reference | i4 kind → `"image"` | `invalid_item`, `"i4"` | +| `invalid_text.json` | reference | i1 text → 65 × `"a"` | `invalid_text`, `"i1"` | +| `unsupported_emoji.json` | reference | i2 emoji → `"🦄"` | `unsupported_emoji`, `"i2"` | + +**Valid payloads.** Write each `payload` by hand from spec §7.3: +- **`empty.json`:** layout `empty`, payload `{"v": 1, "rev": "c4aad3fa", "start": null, "sleep": 20, "blocks": []}`. +- **`reference.json`:** layout `reference`, payload: + +```json +{"v": 1, "rev": "90538742", "start": "b1", "sleep": 20, "blocks": [ + {"id": "b1", "x": 0, "y": 0, "name": "Kitchen", "bg": "5B9E4D", "font": "m", "widget": "light"}, + {"id": "b2", "x": 0, "y": -1, "name": "Lights", "bg": "C94F3D", "font": "m", "widget": "light"}, + {"id": "b3", "x": -1, "y": 0, "name": "Hello World", "bg": "4F86DD", "font": "l", "widget": "custom", "items": [ + {"id": "i1", "kind": "text", "text": "Hello World", "font": "l"}, + {"id": "i2", "kind": "emoji", "text": "👋", "font": "xl"}, + {"id": "i3", "kind": "entity", "font": "s"}, + {"id": "i4", "kind": "battery", "font": "s"}, + {"id": "i5", "kind": "brightness", "font": "l"}]}, + {"id": "b4", "x": -1, "y": 1, "name": "Bedroom", "bg": "7B2FA0", "font": "m", "widget": "climate"}]} +``` + +- **`emoji-variation.json`:** layout `emoji-variation`, payload `{"v": 1, "rev": "5387d4ea", "start": "b1", "sleep": 3600, "blocks": [{"id": "b1", "x": 0, "y": 0, "name": "Snow", "bg": "FFFFFF", "font": "xl", "widget": "custom", "items": [{"id": "i1", "kind": "emoji", "text": "❄", "font": "xl"}]}]}`. + +**Invalid payloads** (`text` values): + +| File | text | expect | +|---|---|---| +| `bad_json.json` | `{"v":1,` | `bad_json` | +| `bad_json-array.json` | `[1,2]` | `bad_json` | +| `unsupported_version.json` | `{"v":2,"rev":"x","start":null,"blocks":[]}` | `unsupported_version` | +| `invalid_payload.json` | `{"v":1,"rev":"x","start":"b1","blocks":[{"id":"b1"}]}` | `invalid_payload` | +| `invalid_payload-widget.json` | `{"v":1,"rev":"x","start":"b1","sleep":20,"blocks":[{"id":"b1","x":0,"y":0,"name":"A","bg":"000000","font":"m","widget":"gauge"}]}` | `invalid_payload` | +| `invalid_payload-sleep.json` | `{"v":1,"rev":"x","start":null,"sleep":-1,"blocks":[]}` | `invalid_payload` | + +**States.** All use layout `reference` and unit `°C`: + +| File | entity_ids | hass_states | updates | +|---|---|---|---| +| `light-dimmable-on.json` | `["light.kitchen"]` | `light.kitchen`: `on`, `{"brightness": 128, "supported_color_modes": ["brightness"]}` | `[{"id": "b1", "available": true, "on": true, "brightness": 50}]` | +| `light-dimmable-off.json` | `["light.living_room"]` | `light.living_room`: `off`, `{"supported_color_modes": ["color_temp"]}` | `[{"id": "b2", "available": true, "on": false, "brightness": 0}]` | +| `light-onoff.json` | `["light.kitchen"]` | `on`, `{"supported_color_modes": ["onoff"]}` | `[{"id": "b1", "available": true, "on": true, "brightness": null}]` | +| `light-unavailable.json` | `["light.kitchen"]` | `unavailable`, `{}` | `[{"id": "b1", "available": false}]` | +| `climate-heating.json` | `["climate.bedroom"]` | `heat`, `{"temperature": 20.5, "current_temperature": 19.8, "min_temp": 7, "max_temp": 35, "target_temp_step": 0.5, "hvac_action": "heating"}` | `[{"id": "b4", "available": true, "target": 20.5, "min": 7, "max": 35, "step": 0.5, "unit": "°C", "current": "19.8 °C", "action": "Heating"}]` | +| `climate-defaults.json` | `["climate.bedroom"]` | `off`, `{"temperature": null, "current_temperature": null}` | `[{"id": "b4", "available": true, "target": null, "min": 7, "max": 35, "step": 0.5, "unit": "°C", "current": "—", "action": "Off"}]` | +| `entity-precision.json` | `["sensor.outdoor_temperature"]` | `"12.345"`, `{"unit_of_measurement": "°C"}`; registry_options `{"sensor.outdoor_temperature": {"sensor": {"display_precision": 1}}}` | `[{"id": "i3", "text": "12.3 °C"}]` | +| `entity-missing.json` | `["sensor.outdoor_temperature"]` | `{}` | `[{"id": "i3", "text": "—"}]` | +| `all-missing.json` | `null` | `{}` | `[{"id": "b1", "available": false}, {"id": "b2", "available": false}, {"id": "i3", "text": "—"}, {"id": "b4", "available": false}]` | + +**Controls.** All use layout `reference`. `item` is `""` everywhere: + +| File | hass_states | event (block, op, value) | expect_call | +|---|---|---|---| +| `light-toggle.json` | `{}` | `b1`, `toggle`, `"0.00"` | `light.toggle` `{"entity_id": "light.kitchen"}` | +| `light-set.json` | `{}` | `b1`, `set`, `"42.40"` | `light.turn_on` `{"entity_id": "light.kitchen", "brightness_pct": 42}` | +| `light-set-zero.json` | `{}` | `b1`, `set`, `"0.00"` | `light.turn_off` `{"entity_id": "light.kitchen"}` | +| `light-set-over.json` | `{}` | `b2`, `set`, `"150"` | `light.turn_on` `{"entity_id": "light.living_room", "brightness_pct": 100}` | +| `climate-set.json` | `climate.bedroom`: `heat`, `{"min_temp": 7, "max_temp": 35}` | `b4`, `set`, `"21.50"` | `climate.set_temperature` `{"entity_id": "climate.bedroom", "temperature": 21.5}` | +| `climate-clamp.json` | same as above | `b4`, `set`, `"50.00"` | `climate.set_temperature` `{"entity_id": "climate.bedroom", "temperature": 35}` | +| `ignored-unknown-block.json` | `{}` | `zz`, `set`, `"1"` | `null` | +| `ignored-custom-block.json` | `{}` | `b3`, `set`, `"1"` | `null` | +| `ignored-bad-value.json` | `{}` | `b1`, `set`, `"abc"` | `null` | +| `ignored-climate-toggle.json` | `{}` | `b4`, `toggle`, `"0.00"` | `null` | + +**`colors.json`:** + +| bg | text | +|---|---| +| `#FFFFFF` | `#000000` | +| `#000000` | `#FFFFFF` | +| `#5B9E4D` | `#FFFFFF` | +| `#4F86DD` | `#FFFFFF` | +| `#C94F3D` | `#FFFFFF` | +| `#7B2FA0` | `#FFFFFF` | +| `#F1C40F` | `#000000` | +| `#9E9E9E` | `#000000` | +| `#8C8C8C` | `#FFFFFF` | + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/protocol -v` +Expected: PASS. + +- [ ] **Step 5: Write the protocol doc and guidance** + - **`docs/protocol.md`:** spec §6 and §7, verbatim, under the heading "Device protocol v1". Add a closing "Fixtures" section with the relative link `../protocol/README.md`. + - **`protocol/README.md`:** + - Who reads each fixture folder: pytest in `tests/integration`, vitest in `frontend/test`, doctest in `esphome/tests`. + - The rule "one broken rule per invalid fixture". + - The canonical-revision snippet: + + ```python + hashlib.sha256(json.dumps(p, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()[:8] + ``` + - **`.claude/skills/protocol-change/SKILL.md`:** + - Frontmatter `name: protocol-change`. + - `description:` "Use when changing anything that crosses the Home Assistant ↔ screen boundary: layout fields, validation rules, payload keys, state update fields, events, actions, emoji list or limits." + - Body, a numbered checklist: + 1. Classify the change. The C++ parser rejects unknown `widget`/`kind`/`font` values, so any new value is breaking: bump `PROTOCOL_VERSION` in `custom_components/ha_controller/const.py` and in the firmware's `ha_controller.h`. + 2. Edit `docs/protocol.md` first. + 3. Update `protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet. + 4. Update the Python code (`layout.py`, `compiler.py`, `states.py`, `controls.py`), the TypeScript model (`frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). + 5. Run `pytest`, `npm --prefix frontend test`, the host C++ tests and `esphome compile`. + 6. Ask the `protocol-guardian` agent to review. + - **`.claude/agents/protocol-guardian.md`:** + - Frontmatter `name: protocol-guardian`, `tools: Read, Grep, Glob, Bash`. + - `description:` "Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol.md, protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging." + - Body: + - A checklist: field names, error codes, limits and constants identical in all places; fixtures updated; golden revs recomputed; `PROTOCOL_VERSION` bumped on breaking changes; docs updated. + - Output: a list of `file:line — inconsistency — fix`, or "Protocol consistent". + - **`docs/README.md`:** add a `protocol.md` bullet. + - **`CLAUDE.md`:** list the skill and the agent under `## Skills and agents`. + +- [ ] **Step 6: Run the whole suite** + +Run: `pytest -v && ruff check .` +Expected: PASS. + +- [ ] **Step 7: Commit** + +```bash +git add docs/protocol.md docs/README.md protocol custom_components/ha_controller/emoji.json tests/protocol .claude CLAUDE.md +git commit -m "feat(protocol): add protocol v1 contract, shared fixtures and guidance" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md new file mode 100644 index 0000000..665b399 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md @@ -0,0 +1,587 @@ +# HA Controller — Plan 2: Home Assistant Integration + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build the `ha_controller` custom integration: config flow, layout validation and compilation, state builders, the sync engine that talks to the screen through ESPHome actions and events, control mapping, the websocket API and the sidebar panel registration. + +**Architecture:** +- **Pure modules:** `layout.py`, `compiler.py`, `states.py` and `controls.py` hold the protocol logic. They are tested against `protocol/fixtures/`. +- **`ScreenController`:** one per config entry. It wires those modules to Home Assistant: storage, event listeners filtered by `device_id`, entity tracking, and calls to the screen's `esphome._` services. +- **`websocket.py` and `panel.py`:** expose the controller to the panel built in plan 3. + +**Tech Stack:** Python 3.14, Home Assistant ≥ 2026.10, `pytest-homeassistant-custom-component==0.13.375` (pins Home Assistant 2026.10.4), ruff, Pillow (brand icon script only). + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§6–§8, §15) + +## Global Constraints + +- Domain `ha_controller`, name "HA Controller", `MANUFACTURER = "pyxel-dev"`, `MODEL = "ha-controller"`. +- Minimum Home Assistant 2026.10.0. Python 3.14. +- Protocol v1 and constants exactly as spec §6, §7 and §15, defined once in `const.py`. +- Events: `esphome.ha_controller_hello` and `esphome.ha_controller_control`. Services: `esphome._`. The integration never registers its own services. +- No blocking I/O in the event loop. Read `emoji.json` with `hass.async_add_executor_job`. +- Time comparisons use `homeassistant.util.dt.utcnow()`, so tests can drive them with `freezer`. +- All user-facing strings are in English. + +## Review Focus + +1. **Screen reboot, Home Assistant restart or Wi-Fi drop.** The layout and states resync with no user action: hello `connected` → states; revision `none` → layout + states. A screen that keeps rejecting a layout gets at most one push per 300 s. Owner: Task 5 tests. +2. **An entity that is missing, unavailable or renamed.** Updates mark it unavailable, controls for it are ignored, and a failing service call never raises. Owner: Task 4 fixtures, Task 6 `test_service_error_is_swallowed`. +3. **Several screens configured.** A hello or control from one screen never affects another. Owner: Task 5 `test_hello_from_other_device_is_ignored`, Task 6 `test_control_from_other_device_is_ignored`. +4. **Saving while the screen is offline.** The save succeeds with `pushed: false` and no exception, and the next hello delivers the layout. Owner: Task 5 `test_save_layout_offline_returns_not_pushed`. +5. **A stored layout that no longer validates** (hand-edited storage, future downgrade). Setup must not fail; the controller uses an empty layout and logs a warning. Owner: Task 5 `test_invalid_stored_layout_falls_back_to_empty`. + +--- + +### Task 1: Integration skeleton and config flow + +**Files:** +- Create: + - `custom_components/ha_controller/`: `__init__.py`, `const.py`, `config_flow.py`, `manifest.json`, `strings.json`, `translations/en.json`, `brand/icon.png`, `brand/icon@2x.png` + - `scripts/make_brand_icon.py`, `hacs.json` + - `tests/conftest.py`, `tests/integration/__init__.py`, `tests/integration/helpers.py`, `tests/integration/test_config_flow.py` + - `.github/workflows/validate.yml` +- Modify: `requirements_test.txt`, `CLAUDE.md` (commands) + +**Interfaces:** +- Produces: + - **`const.py`:** + - Identity and limits: `DOMAIN`, `MANUFACTURER`, `MODEL`, `CONF_DEVICE_ID = "device_id"`, `CONF_AUTO_UPDATE = "auto_update"`, `PROTOCOL_VERSION = 1`. + - Events and actions: `EVENT_HELLO = "esphome.ha_controller_hello"`, `EVENT_CONTROL = "esphome.ha_controller_control"`, `ACTION_SET_LAYOUT = "set_layout"`, `ACTION_SET_STATES = "set_states"`, `ACTION_INSTALL_FIRMWARE = "install_firmware"`. + - Layout limits: `MAX_BLOCKS = 32`, `MAX_ITEMS = 6`, `MAX_NAME_LEN = 32`, `MAX_TEXT_LEN = 64`, `COORD_LIMIT = 32`, `MAX_PAYLOAD_BYTES = 24576`, `STATE_CHUNK_BYTES = 8192`. + - Allowed values: `FONT_SIZES = ("s", "m", "l", "xl")`, `ENTITY_BLOCK_DOMAINS = ("light", "climate")`, `ITEM_KINDS = ("text", "emoji", "entity", "battery", "brightness")`. + - Screen sleep (seconds, `0` = never): `DEFAULT_SLEEP_TIMEOUT = 20`, `MIN_SLEEP_TIMEOUT = 5`, `MAX_SLEEP_TIMEOUT = 3600`. + - Timings: `ONLINE_TIMEOUT = timedelta(seconds=150)`, `PUSH_RETRY = timedelta(seconds=300)`, `STATE_COALESCE_SECONDS = 0.2`, `INSTALL_TIMEOUT = 300`, `AUTO_UPDATE_RETRY = timedelta(seconds=3600)`. + - Panel: `PANEL_URL_PATH = "ha-controller"`, `PANEL_COMPONENT = "ha-controller-panel"`, `PANEL_TITLE = "HA Controller"`, `PANEL_ICON = "mdi:remote"`, `STATIC_URL = "/ha_controller_static"`. + - Release URLs: `FIRMWARE_BASE_URL = "https://pyxel-dev.github.io/HA-controller/firmware"`, `RELEASE_URL = "https://github.com/pyxel-dev/HA-controller/releases/tag/v{version}"`. + - **`tests/integration/helpers.py`:** + - `async def register_screen(hass, *, name="HA Controller", manufacturer=MANUFACTURER, model=MODEL, mac="aa:bb:cc:dd:ee:ff") -> dr.DeviceEntry`. It adds an `esphome` `MockConfigEntry` and a device with `connections={(dr.CONNECTION_NETWORK_MAC, mac)}`. + - `async def setup_screen(hass, device) -> MockConfigEntry`. It adds the `ha_controller` entry with `data={"device_id": device.id}` and `unique_id=device.id`, sets it up, and waits. + - `NODE = "ha-controller-aabbcc"`. + - `def hello(device, **overrides) -> dict`: a default hello for `NODE`, version `"0.1.0"`, protocol `"1"`, revision `"none"`, reason `"connected"`. + - `def load_fixture(*parts) -> Any`: reads `protocol/fixtures/...`. + +- [ ] **Step 1: Write the failing tests** in `tests/integration/test_config_flow.py`, plus `tests/conftest.py` with an autouse `auto_enable_custom_integrations(enable_custom_integrations)` fixture. + +```python +async def test_user_step_shows_device_selector(hass): ... # form, step_id "user", errors {} +async def test_user_step_creates_entry(hass): + device = await register_screen(hass) + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "HA Controller" and result["data"] == {"device_id": device.id} + assert result["result"].unique_id == device.id +async def test_user_step_rejects_other_device(hass): # model="other" → errors {"base": "not_ha_controller"} +async def test_user_step_aborts_when_already_configured(hass): # reason "already_configured" +async def test_setup_and_unload_entry(hass): # LOADED, then NOT_LOADED +async def test_strings_match_english_translation(): # strings.json == translations/en.json +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pip install -r requirements_test.txt && pytest tests/integration/test_config_flow.py -v` +Expected: FAIL (`ModuleNotFoundError` / integration not found). + +- [ ] **Step 3: Implement the skeleton.** + - **`requirements_test.txt`:** `pytest-homeassistant-custom-component==0.13.375`, `ruff`, `pillow`. + - **`manifest.json`**, keys in hassfest order: + + ```json + { + "domain": "ha_controller", + "name": "HA Controller", + "after_dependencies": ["esphome"], + "codeowners": ["@pyxel-dev"], + "config_flow": true, + "dependencies": ["frontend", "http", "panel_custom", "websocket_api"], + "documentation": "https://github.com/pyxel-dev/HA-controller/tree/main/docs", + "integration_type": "device", + "iot_class": "local_push", + "issue_tracker": "https://github.com/pyxel-dev/HA-controller/issues", + "requirements": [], + "version": "0.1.0" + } + ``` + + - **`__init__.py`:** + - `CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)`. + - `async_setup` returns `True`. + - `async_setup_entry` and `async_unload_entry` return `True`; they are filled in Task 5. + - **`config_flow.py`:** `HaControllerConfigFlow(ConfigFlow, domain=DOMAIN)`, `VERSION = 1`, with step `user`: + - The schema has one field, `vol.Required(CONF_DEVICE_ID)`: + + ```python + selector.DeviceSelector(selector.DeviceSelectorConfig(filter=[ + selector.DeviceFilterSelectorConfig(integration="esphome", manufacturer=MANUFACTURER, model=MODEL) + ])) + ``` + + - On submit, accept the device only if it exists, belongs to a config entry of domain `esphome`, and has `manufacturer == MANUFACTURER` and `model == MODEL`. Otherwise set error `not_ha_controller`. + - Then `async_set_unique_id(device.id)`, `_abort_if_unique_id_configured()`, and create the entry with title `device.name_by_user or device.name`. + - **`strings.json` = `translations/en.json`:** + - User step: title "Add an HA Controller screen"; description "Pick the screen. It must already be added to Home Assistant with the ESPHome integration."; field `device_id` "Screen". + - Error: `not_ha_controller` "This device is not an HA Controller screen." + - Abort: `already_configured` "This screen is already set up." + - **`hacs.json`:** `{"name": "HA Controller", "homeassistant": "2026.10.0"}`. + - **`scripts/make_brand_icon.py`:** a Pillow script that writes `brand/icon.png` (256×256) and `brand/icon@2x.png` (512×512), scaled from a 512 design: + - transparent background; + - a filled circle `#111827` with radius 240; + - a ring `#374151`, width 36, radius 170; + - an arc `#F59E0B`, width 36, radius 170, from 135° to 315°; + - a centre dot `#F9FAFB` with radius 40. + + Run it once and commit both PNGs. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/integration/test_config_flow.py -v && ruff check .` +Expected: PASS. + +- [ ] **Step 5: Add validation CI** in `.github/workflows/validate.yml`: + - Triggers: `push`, `pull_request`, `schedule` (`cron: "0 0 * * *"`) and `workflow_dispatch`. + - Job `hassfest`: checkout, then `home-assistant/actions/hassfest@master`. + - Job `hacs`: `hacs/action@main` with `category: integration`. + - If HACS reports the repository description or topics checks, the owner sets them once on GitHub. Description: "Home Assistant remote on the Waveshare ESP32-S3 1.75\" round AMOLED". Topics: `home-assistant`, `hacs`, `esphome`, `integration`. + - Add to the `CLAUDE.md` commands: `pytest tests/integration` and `python scripts/make_brand_icon.py`. + +- [ ] **Step 6: Commit** + +```bash +git add custom_components/ha_controller scripts/make_brand_icon.py hacs.json requirements_test.txt tests .github/workflows/validate.yml CLAUDE.md +git commit -m "feat(integration): add integration skeleton and config flow" +``` + +--- + +### Task 2: Layout validation + +**Files:** +- Create: `custom_components/ha_controller/layout.py`, `tests/integration/test_layout.py` + +**Interfaces:** +- Produces: + - `class LayoutError(NamedTuple): code: str; ref: str | None` + - `def validate_layout(layout: Any, emoji: frozenset[str]) -> list[LayoutError]` + - `def empty_layout() -> dict[str, Any]`, which returns `{"version": 1, "start": None, "settings": {"sleep_timeout": DEFAULT_SLEEP_TIMEOUT}, "blocks": []}` + - `def normalize_emoji(text: str) -> str`, which removes U+FE0F + - `def bound_entities(layout: dict) -> dict[str, list[str]]`: entity_id → binding ids (block ids for entity blocks, item ids for entity items), in layout order + - `def load_emoji_file(path: Path) -> frozenset[str]` (sync) and `async def async_load_emoji(hass) -> frozenset[str]` + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(VALID_LAYOUTS), ids=stem) +def test_valid_fixtures(path): assert validate_layout(load(path), EMOJI) == [] + +@pytest.mark.parametrize("path", sorted(INVALID_LAYOUTS), ids=stem) +def test_invalid_fixtures(path): + case = load(path) + assert validate_layout(case["layout"], EMOJI) == [LayoutError(case["expect"]["code"], case["expect"]["ref"])] + +def test_connectivity_is_skipped_when_fields_are_invalid(): ... # disconnected block + bad name → only invalid_name +def test_normalize_emoji_strips_variation_selector(): assert normalize_emoji("❄️") == "❄" +def test_bound_entities_reference(): + assert bound_entities(load_layout("reference")) == { + "light.kitchen": ["b1"], "light.living_room": ["b2"], + "sensor.outdoor_temperature": ["i3"], "climate.bedroom": ["b4"]} +def test_bool_is_not_a_coordinate(): ... # x = True → coordinate_out_of_range +@pytest.mark.parametrize("value,ok", [(0, True), (5, True), (3600, True), (4, False), (3601, False), (True, False), ("20", False)]) +def test_sleep_timeout_bounds(value, ok): ... # reference with settings.sleep_timeout = value → [] or [LayoutError("invalid_sleep_timeout", None)] +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_layout.py -v` +Expected: FAIL (`ImportError`). + +- [ ] **Step 3: Implement `validate_layout`.** It runs in three phases, following spec §6. + - **Phase 1 — containers only.** Stop at the first error. The checks: + - the layout is a dict; + - `version == 1`; + - `settings` is a dict; + - `blocks` is a list of dicts; + - every block with `type == "custom"` has `items` as a list of dicts. + + Each failure produces `invalid_structure` with ref `None`. + - **Phase 2 — per field, all errors collected.** The checks run in this order: + 1. `too_many_blocks`, then `invalid_sleep_timeout`. `settings.sleep_timeout` must be an `int` that is not a `bool`, either `0` or within 5–3600. + 2. For each block: `invalid_id`, `duplicate_id`, `coordinate_out_of_range` (an `int` that is not a `bool`, within ±32), `duplicate_position`, `invalid_name`, `invalid_background`, `invalid_font_size`, `invalid_type`, then the type-specific checks. The type-specific checks are skipped when the type is invalid: + - entity blocks: `invalid_entity`; + - custom blocks: `too_many_items`, then for each item `invalid_id`, `duplicate_id`, `invalid_item`, `invalid_font_size`, and the kind-specific check (`invalid_text`, `unsupported_emoji` or `invalid_entity`). + 3. `invalid_start`, last. + + A field of the wrong JSON type yields that field's code. + - **Phase 3 — connectivity.** Runs only when phases 1–2 found nothing: a BFS from `start` over 4-neighbour cells. Each unreachable block yields `disconnected`, in layout order. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/integration/test_layout.py -v` +Expected: PASS (all 4 valid and 23 invalid fixtures, plus the unit tests). + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/layout.py tests/integration/test_layout.py +git commit -m "feat(integration): validate layouts against protocol rules" +``` + +--- + +### Task 3: Layout compiler + +**Files:** +- Create: `custom_components/ha_controller/compiler.py`, `tests/integration/test_compiler.py` + +**Interfaces:** +- Consumes: `normalize_emoji` (Task 2). +- Produces: + - `def compile_layout(layout: dict) -> dict`. It expects a valid layout and returns the payload with `rev` (spec §7.3). Names are trimmed. + - `def payload_revision(payload: dict) -> str`. It ignores any `rev` key. + - `def encode_payload(payload: dict) -> str`. Compact output, with `ensure_ascii=False`. + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(VALID_PAYLOADS), ids=stem) +def test_golden_payloads(path): + case = load(path) + assert compile_layout(load_layout(case["layout"])) == case["payload"] + +def test_revision_ignores_rev_key(): + assert payload_revision({"v": 1, "rev": "zzz", "start": None, "sleep": 20, "blocks": []}) == "c4aad3fa" +def test_encode_payload_is_compact_utf8(): + text = encode_payload(compile_layout(load_layout("reference"))) + assert ", " not in text and ": " not in text and "👋" in text +def test_huge_layout_exceeds_payload_limit(): + # 32 custom blocks in a row, each with 6 text items of 64 × "é" + assert len(encode_payload(compile_layout(huge)).encode()) > MAX_PAYLOAD_BYTES +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_compiler.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the three functions in `compiler.py`, following spec §7.3.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/integration/test_compiler.py -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/compiler.py tests/integration/test_compiler.py +git commit -m "feat(integration): compile layouts into device payloads" +``` + +--- + +### Task 4: State builders + +**Files:** +- Create: `custom_components/ha_controller/states.py`, `tests/integration/test_states.py` + +**Interfaces:** +- Produces: + - `def build_updates(hass, layout: dict, entity_ids: Collection[str] | None = None) -> list[dict]`. Returns updates in layout order (spec §7.4, §7.7); `None` means all bound entities. + - `def format_entity_text(hass, entity_id: str, attribute: str | None) -> str` + - `def chunk_updates(updates: list[dict], max_bytes: int = STATE_CHUNK_BYTES) -> list[str]`. Each chunk is an encoded JSON array of at most `max_bytes` bytes, unless a single update is larger; in that case it is sent alone. + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(STATE_FIXTURES), ids=stem) +async def test_state_fixtures(hass, path): + case = load(path) + hass.config.units = METRIC_SYSTEM + for entity_id, s in case["hass_states"].items(): + hass.states.async_set(entity_id, s["state"], s["attributes"]) + registry = er.async_get(hass) + for entity_id, options in case.get("registry_options", {}).items(): + domain, object_id = entity_id.split(".", 1) + entry = registry.async_get_or_create(domain, "test", object_id, suggested_object_id=object_id) + assert entry.entity_id == entity_id + for option_domain, value in options.items(): + registry.async_update_entity_options(entity_id, option_domain, value) + assert build_updates(hass, load_layout(case["layout"]), case["entity_ids"]) == case["updates"] + +async def test_entity_text_truncated_to_64(hass): ... # 100-char state → len == 64 +async def test_entity_text_uses_attribute(hass): ... # attribute "battery" = 80 → "80" +def test_chunk_updates_splits_by_size(): ... # 300 updates, max 8192 → every chunk ≤ 8192 and the union equals the input +def test_chunk_updates_keeps_oversize_update_alone(): ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_states.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the builders in `states.py`, following spec §7.7.** `—` is U+2014. The climate unit is `hass.config.units.temperature_unit`. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/integration/test_states.py -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/states.py tests/integration/test_states.py +git commit -m "feat(integration): build screen state updates" +``` + +--- + +### Task 5: Layout store and ScreenController sync engine + +**Files:** +- Create: `custom_components/ha_controller/store.py`, `custom_components/ha_controller/controller.py`, `tests/integration/test_controller.py` +- Modify: `custom_components/ha_controller/__init__.py` + +**Interfaces:** +- Consumes: Tasks 2–4. +- Produces: + - **`class LayoutStore`:** `__init__(hass, entry_id)` with Home Assistant `Store` version 1 and key `f"{DOMAIN}.layout.{entry_id}"`, plus `async_load() -> dict | None`, `async_save(layout) -> None` and `async_remove() -> None`. + - **`@dataclass class DeviceStatus`:** fields `node`, `version`, `revision` (`str | None`), `protocol: int | None`, `last_seen: datetime | None`, and `def online(self) -> bool`, which compares `last_seen` with `utcnow()` and `ONLINE_TIMEOUT`. + - **`class InvalidLayout(HomeAssistantError)`:** attribute `errors: list[LayoutError]`. + - **`class ScreenController`:** + - `__init__(hass, entry, store, emoji: frozenset[str], integration_version: str)` + - properties: `device_id`, `layout`, `revision`, `device: DeviceStatus`, `integration_version` + - lifecycle: `async_start()` (load the layout, subscribe to the hello event, the control event and entity tracking) and `async_stop()` + - layout: `async_save_layout(layout) -> tuple[str, bool]`, returning `(revision, pushed)` + - sync: `async_handle_hello(data) -> None`, `async_push_layout() -> bool`, `async_push_states(entity_ids: Collection[str] | None = None) -> bool` + - `async_call_device(action: str, data: dict) -> bool` + - `status() -> dict`, shaped like one `ha_controller/screens` item (spec §8) + - `@callback async_add_listener(cb) -> CALLBACK_TYPE`, which notifies on every device status change + - **`__init__.py`:** `type HaControllerConfigEntry = ConfigEntry[ScreenController]`. `async_setup_entry` builds and starts the controller and stores it in `entry.runtime_data`. `async_unload_entry` stops it. `async_remove_entry` calls `LayoutStore.async_remove()`. + +- [ ] **Step 1: Write the failing tests.** Mock the screen's services with `async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_layout")` and `async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_states")`. Drive time with `freezer`, `async_fire_time_changed` and `async_block_till_done`. + +```python +async def test_hello_with_unknown_revision_pushes_layout_and_states(hass): ... + # saved reference layout, hello(revision="none", reason="heartbeat") + # → one set_layout call (json.loads(layout)["rev"] == "90538742"), then ≥1 set_states call +async def test_hello_connected_with_current_revision_pushes_states_only(hass): ... +async def test_heartbeat_with_current_revision_pushes_nothing(hass): ... +async def test_stale_revision_is_retried_at_most_every_300s(hass, freezer): ... + # heartbeat ×2 within 299 s → 1 push; after +301 s → 2 pushes; reason "connected" always pushes +async def test_hello_with_other_protocol_pushes_nothing(hass): ... # protocol "2" +async def test_hello_from_other_device_is_ignored(hass): ... # second screen registered; its hello leaves screen 1 untouched +async def test_state_changes_are_coalesced(hass): ... # 2 changes < 200 ms → one set_states with b1 and b2 +async def test_state_change_not_pushed_when_offline(hass, freezer): ... # last hello 151 s ago → no call +async def test_save_layout_pushes_when_online(hass): ... # returns ("90538742", True) +async def test_save_layout_offline_returns_not_pushed(hass): ... # no hello yet → ("90538742", False); still persisted +async def test_save_invalid_layout_raises(hass): ... # InvalidLayout, errors == [LayoutError("invalid_name", "b2")] +async def test_save_too_large_layout_raises_payload_too_large(hass): ... # errors == [LayoutError("payload_too_large", None)] +async def test_push_failure_is_logged_not_raised(hass, caplog): ... # set_layout service raises HomeAssistantError → False +async def test_invalid_stored_layout_falls_back_to_empty(hass, hass_storage): ... +async def test_layout_survives_reload(hass): ... +async def test_status_reports_device(hass): ... # status() fields after a hello +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_controller.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the controller, following spec §7.5.** + - **Hello and control events:** `hass.bus.async_listen(EVENT_…, handler, event_filter=…)`. The filter is a `@callback` that compares `event_data.get("device_id")` with the configured device id. + - **Entity tracking:** `async_track_state_change_event` over `bound_entities(layout)`. It is re-subscribed when the layout changes. + - **State coalescing:** a pending entity-id set, flushed by `async_call_later(hass, STATE_COALESCE_SECONDS, …)`. + - **Device calls:** `hass.services.async_call("esphome", f"{node.replace('-', '_')}_{action}", data, blocking=True)`. On `HomeAssistantError`, log a warning and return `False`. Return `False` when the node is unknown. + - **Push retry:** remember `(revision, utcnow())` of the last layout push. Skip a non-`connected` push of the same revision within `PUSH_RETRY`. + - **Saving a layout:** + 1. Validate, then compile and encode. If the encoded size exceeds `MAX_PAYLOAD_BYTES`, raise `InvalidLayout([LayoutError("payload_too_large", None)])`. + 2. Store the layout and re-track entities. + 3. Push if the screen is online with protocol 1, bypassing the retry limit. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/integration -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller tests/integration/test_controller.py +git commit -m "feat(integration): sync layouts and states with the screen" +``` + +--- + +### Task 6: Control events + +**Files:** +- Create: `custom_components/ha_controller/controls.py`, `tests/integration/test_controls.py` +- Modify: `custom_components/ha_controller/controller.py` + +**Interfaces:** +- Produces: + - `class ControlCall(NamedTuple): domain: str; service: str; data: dict` + - `def resolve_control(layout: dict, hass, data: Mapping[str, Any]) -> ControlCall | None` (spec §7.6). A non-finite or unparsable value returns `None`. + - `ScreenController.async_handle_control(data) -> None`, subscribed to `EVENT_CONTROL` in `async_start`. It calls the service with `blocking=True` and logs a `HomeAssistantError` instead of raising it. + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(CONTROL_FIXTURES), ids=stem) +async def test_control_fixtures(hass, path): + case = load(path) # set hass_states, then: + call = resolve_control(load_layout(case["layout"]), hass, case["event"]) + assert (call and call._asdict()) == case["expect_call"] # None ↔ null + +async def test_control_event_calls_service(hass): ... # fire EVENT_CONTROL with device_id → light.toggle mock receives entity_id light.kitchen +async def test_control_from_other_device_is_ignored(hass): ... +async def test_service_error_is_swallowed(hass, caplog): ... # registered light.turn_on raises HomeAssistantError → no exception, warning logged +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_controls.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `resolve_control` and the controller handler.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/integration -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller tests/integration/test_controls.py +git commit -m "feat(integration): map screen controls to service calls" +``` + +--- + +### Task 7: Websocket API + +**Files:** +- Create: `custom_components/ha_controller/websocket.py`, `tests/integration/test_websocket.py` +- Modify: `custom_components/ha_controller/__init__.py` (call `async_register_websocket(hass)` in `async_setup`) + +**Interfaces:** +- Consumes: `ScreenController.status`, `.layout` and `.async_save_layout` (Task 5). +- Produces (used by plan 3): + - `ha_controller/screens` → `{"screens": [status, …]}`, covering loaded entries in title order. + - `ha_controller/layout/get` `{entry_id}` → `{"layout": layout}`. + - `ha_controller/layout/save` `{entry_id, layout}` → `{"revision": str, "pushed": bool}`. + - Errors: `not_found`, which happens when the entry is missing or not loaded; and `invalid_layout`, whose message is the `", "`-joined `f"{code}@{ref or ''}"` list. + - All three commands are admin-only: `@websocket_api.websocket_command`, then `@websocket_api.require_admin`, then `@websocket_api.async_response` for the save command or `@callback` for the others. + +- [ ] **Step 1: Write the failing tests** with `hass_ws_client` and `hass_admin_user`. + +```python +async def test_screens_lists_entries(hass, hass_ws_client): ... +async def test_layout_get_returns_stored_layout(hass, hass_ws_client): ... +async def test_layout_get_unknown_entry_returns_not_found(hass, hass_ws_client): ... +async def test_layout_save_valid(hass, hass_ws_client): ... # result {"revision": "90538742", "pushed": False} +async def test_layout_save_invalid(hass, hass_ws_client): ... # error code "invalid_layout", message "invalid_name@b2" +async def test_commands_require_admin(hass, hass_ws_client, hass_admin_user): ... # remove the admin group → error code "unauthorized" +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_websocket.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `websocket.py`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/integration -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller tests/integration/test_websocket.py +git commit -m "feat(integration): add websocket API for the panel" +``` + +--- + +### Task 8: Sidebar panel registration, developer docs and reviewer agent + +**Files:** +- Create: + - `custom_components/ha_controller/panel.py`, `custom_components/ha_controller/frontend/.gitkeep` + - `tests/integration/test_panel.py` + - `docs/development.md`, `.claude/agents/ha-integration-reviewer.md` +- Modify: `custom_components/ha_controller/__init__.py`, `docs/README.md`, `CLAUDE.md` + +**Interfaces:** +- Consumes: the plan 3 bundle path `custom_components/ha_controller/frontend/ha-controller-panel.js`. +- Produces: + - `async def async_register_panel(hass, version: str) -> None`. It registers `StaticPathConfig(STATIC_URL, /frontend, True)` once per Home Assistant run, guarded by a `hass.data` flag. If `PANEL_URL_PATH` is not already in `hass.data[frontend.DATA_PANELS]`, it registers the panel with: + + ```python + await panel_custom.async_register_panel( + hass, + frontend_url_path=PANEL_URL_PATH, + webcomponent_name=PANEL_COMPONENT, + sidebar_title=PANEL_TITLE, + sidebar_icon=PANEL_ICON, + module_url=f"{STATIC_URL}/ha-controller-panel.js?v={version}", + require_admin=True, + config={}, + ) + ``` + + It logs a warning when the bundle file is missing. + - `@callback def async_unregister_panel(hass) -> None`, which calls `frontend.async_remove_panel(hass, PANEL_URL_PATH, warn_if_unknown=False)`. `async_unload_entry` calls it only when no other `ha_controller` entry is still loaded. + +- [ ] **Step 1: Write the failing tests** + +```python +async def test_panel_registered_on_setup(hass): ... # "ha-controller" in hass.data[frontend.DATA_PANELS], require_admin True +async def test_panel_kept_while_another_entry_is_loaded(hass): ... +async def test_panel_removed_when_last_entry_unloaded(hass): ... +async def test_static_path_registered_once(hass): ... # patch hass.http.async_register_static_paths → awaited once for two entries +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_panel.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `panel.py` and wire it into `async_setup_entry` / `async_unload_entry`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest -v && ruff check .` +Expected: PASS. + +- [ ] **Step 5: Write the docs and the reviewer agent.** + - **`docs/development.md`:** create it with sections "Prerequisites" (Python 3.14, Node 24, ESPHome; the later plans fill these in) and "Home Assistant integration". The integration section covers: + - venv setup and `pip install -r requirements_test.txt`; + - `pytest`; + - running a development Home Assistant, by symlinking `custom_components/ha_controller` into `/custom_components/`; + - how hello / set_layout traffic shows up under Developer tools › Events (`esphome.ha_controller_hello`). + - **`docs/README.md`:** link the new doc. + - **`.claude/agents/ha-integration-reviewer.md`:** + - Frontmatter `name: ha-integration-reviewer`, `tools: Read, Grep, Glob, Bash`. + - `description:` "Reviews changes under custom_components/ha_controller and tests/integration against Home Assistant development rules. Use before merging integration changes." + - Checklist: + - async only, with no blocking I/O in the loop; + - `entry.runtime_data`, with no new `hass.data` globals beyond the panel flags; + - listeners and timers removed on unload; + - event filters by `device_id`; + - service errors caught; + - constants come from `const.py`; + - English strings in `strings.json` and `translations/en.json`; + - every branch tested; + - protocol changes routed to the `protocol-change` skill. + - Output: findings as `file:line — issue — fix`. + - **`CLAUDE.md`:** list the agent. + +- [ ] **Step 6: Commit** + +```bash +git add custom_components/ha_controller tests/integration/test_panel.py docs .claude CLAUDE.md +git commit -m "feat(integration): register the sidebar panel" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md new file mode 100644 index 0000000..c214665 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md @@ -0,0 +1,433 @@ +# HA Controller — Plan 3: Sidebar Panel (Block Map Editor) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build the Home Assistant sidebar panel where the user edits each screen's block map. The map is laid out exactly the way navigation works on the screen ([reference screenshot](../specs/assets/editor-reference.png)). + +**Architecture:** A Lit + TypeScript web component bundled by Vite into one ES module. Vite writes it to `custom_components/ha_controller/frontend/ha-controller-panel.js`, which plan 2's `panel.py` serves. +- **Model:** pure functions in `src/model/` hold all editing logic (grid, validation, edits, colours, emoji). Vitest tests them against `protocol/fixtures/`. +- **Components:** they only render and emit events. +- **Websocket:** the panel talks to the integration through plan 2's commands. +- **Dev harness:** `npm run dev` runs the panel against an in-memory mock `hass`. + +**Tech Stack:** Node 24, TypeScript 5 (strict), Lit 3, Vite, Vitest with happy-dom. Use the current stable releases of the build and test tools, and commit `package-lock.json`. + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§5.1, §5.5, §6, §9) + +## Global Constraints + +- **Rules and codes:** the validation rules and error codes are identical to plan 2 (spec §6). Both suites read the same fixtures. +- **Orientation:** grid `x` grows to the right and `y` grows downwards, matching the screen. +- **No Home Assistant internals:** use no HA-internal custom elements except `ha-menu-button` (optional, narrow mode). Entity pickers are built from `hass.states`. +- **Theme:** use Home Assistant theme variables with fallbacks: + - `--primary-color` (fallback `#03a9f4`) + - `--primary-text-color` (fallback `#212121`) + - `--secondary-text-color` (fallback `#727272`) + - `--card-background-color` (fallback `#fff`) + - `--divider-color` (fallback `rgba(0,0,0,.12)`) + - `--error-color` (fallback `#db4437`) +- **Strings:** all UI strings are in English and live in `src/messages.ts`. +- **Versioning:** `frontend/package.json` `version` is `0.1.0`; plan 5's versioning script keeps it in sync. + +## Review Focus + +1. **Deleting a block that would strand others**, e.g. deleting "Hello World" in the reference layout strands "Bedroom". Expected: refused, with the reason shown. Owner: Task 1 `canDelete` tests, Task 4 editor test. +2. **Map with a start block away from `(0,0)`, negative coordinates, or one row/column.** The map must still render every block at the right relative place, and placeholders must stay inside ±32. Owner: Task 1 placeholder tests on `single.json`, Task 3 grid test. +3. **Websocket save rejected** (`invalid_layout`, connection lost). The working copy must be kept and the error shown, never silently dropped. Owner: Task 5 `test_save_error_keeps_changes`. +4. **Emoji typed or pasted with U+FE0F.** It must be normalised so local validation and the screen agree. Owner: Task 2 `normalizeEmoji` and Task 4 emoji picker test. +5. **`hass` updates arriving every few seconds** while the user edits. Unsaved edits must never be overwritten by a refresh. Owner: Task 5 `test_refresh_does_not_reset_working_copy`. + +--- + +### Task 1: Tooling, types, grid model and validation + +**Files:** +- Create: + - `frontend/package.json`, `frontend/package-lock.json`, `frontend/tsconfig.json`, `frontend/vite.config.ts` + - `frontend/src/types.ts`, `frontend/src/model/grid.ts`, `frontend/src/model/validate.ts`, `frontend/src/model/emoji.ts` + - `frontend/test/fixtures.ts`, `frontend/test/grid.test.ts`, `frontend/test/validate.test.ts` +- Modify: `.github/workflows/ci.yml` (job `frontend`), `CLAUDE.md` (commands) + +**Interfaces:** +- Produces: + - **`types.ts`:** + - `FontSize = "s" | "m" | "l" | "xl"` + - `ItemKind = "text" | "emoji" | "entity" | "battery" | "brightness"` + - `Item {id, kind, font_size: FontSize | null, text?, emoji?, entity_id?, attribute?: string | null}` + - `Block {id, x, y, name, background, font_size, type: "entity" | "custom", entity_id?, items?: Item[]}` + - `Layout {version: 1, start: string | null, settings: {sleep_timeout: number}, blocks: Block[]}` + - `LayoutError {code: string, ref: string | null}` + - `Cell {x, y}` + - `ScreenInfo`: the spec §8 fields + - `HassEntity {entity_id, state, attributes}` + - `Hass {states: Record, callWS(msg): Promise}` + - **`model/grid.ts`:** + - `placeholders(layout: Layout): Cell[]`, sorted by `y` then `x` + - `reachable(blocks: Block[], start: string | null): Set` + - `canDelete(layout, id): {ok: true} | {ok: false, reason: "start" | "disconnects"}` + - `gridBounds(cells: Cell[]): {minX, maxX, minY, maxY}` + - **`model/validate.ts`:** `validateLayout(layout: unknown, emoji: ReadonlySet): LayoutError[]`. Same phases and order as plan 2 Task 2. + - **`model/emoji.ts`:** `SUPPORTED_EMOJI: readonly string[]` imported from `../../../custom_components/ha_controller/emoji.json`, `EMOJI_SET`, `normalizeEmoji(text): string`. + - **`test/fixtures.ts`:** `validLayouts`, `invalidLayouts` and `colors`, loaded with `import.meta.glob("../../protocol/fixtures/…", {eager: true, import: "default"})`. + +- [ ] **Step 1: Scaffold the tooling.** + - **`package.json`:** `"type": "module"`, `"private": true`, `"version": "0.1.0"`. + - Scripts: `dev` (`vite --open dev/index.html`), `build` (`tsc --noEmit && vite build`), `test` (`vitest run`), `typecheck` (`tsc --noEmit`). + - Dependency: `lit`. Dev dependencies: `typescript`, `vite`, `vitest`, `happy-dom`. + - **`tsconfig.json`:** `strict`, `target` and `lib` ES2022 + DOM, `module: ESNext`, `moduleResolution: Bundler`, `experimentalDecorators: true`, `useDefineForClassFields: false`, `resolveJsonModule: true`, `noEmit: true`. + - **`vite.config.ts`:** + - Library mode: entry `src/ha-controller-panel.ts`, format `es`, file name `ha-controller-panel.js`. + - `outDir: "../custom_components/ha_controller/frontend"`, `emptyOutDir: false`, `target: "es2022"`, with `lit` bundled. + - `server.fs.allow: [".."]`. + - `test.environment: "happy-dom"`. + + Run `npm install`. + +- [ ] **Step 2: Write the failing tests** + +```ts +// grid.test.ts +expect(placeholders(validLayouts.empty)).toEqual([{x: 0, y: 0}]); +expect(placeholders(validLayouts.reference)).toEqual([ + {x: 0, y: -2}, {x: -1, y: -1}, {x: 1, y: -1}, {x: -2, y: 0}, + {x: 1, y: 0}, {x: -2, y: 1}, {x: 0, y: 1}, {x: -1, y: 2}]); // the 8 "+" of the screenshot +expect(placeholders(rowOf32Blocks)).toEqual([]); +expect(placeholders(blockAt(32, 0))).not.toContainEqual({x: 33, y: 0}); +expect(canDelete(validLayouts.reference, "b1")).toEqual({ok: false, reason: "start"}); +expect(canDelete(validLayouts.reference, "b3")).toEqual({ok: false, reason: "disconnects"}); +expect(canDelete(validLayouts.reference, "b2")).toEqual({ok: true}); +expect(canDelete(validLayouts.single, "b1")).toEqual({ok: true}); +expect(gridBounds(cellsOf(validLayouts.single))).toEqual({minX: 3, maxX: 3, minY: -2, maxY: -2}); + +// validate.test.ts +for (const [name, layout] of Object.entries(validLayouts)) expect(validateLayout(layout, EMOJI_SET), name).toEqual([]); +for (const [name, c] of Object.entries(invalidLayouts)) expect(validateLayout(c.layout, EMOJI_SET), name).toEqual([c.expect]); +``` + +- [ ] **Step 3: Run the tests to verify they fail** + +Run: `npm --prefix frontend test` +Expected: FAIL (modules missing). + +- [ ] **Step 4: Implement `types.ts`, `grid.ts`, `validate.ts` and `emoji.ts`.** + - `placeholders` collects the empty 4-neighbours of every block within ±32, deduplicated. With no blocks it returns `[(0,0)]`; with 32 blocks it returns `[]`. + - `canDelete` refuses the start block of a multi-block layout. It also refuses any block whose removal leaves another block unreachable from the start block. + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `npm --prefix frontend test && npm --prefix frontend run typecheck` +Expected: PASS. + +- [ ] **Step 6: Add the CI job.** Add job `frontend` to `.github/workflows/ci.yml`: + - `actions/setup-node@v4` with `node-version: 24`, `cache: npm`, `cache-dependency-path: frontend/package-lock.json`. + - Working directory `frontend`: `npm ci`, `npm test`, `npm run build`. + + Add the `npm --prefix frontend …` commands to `CLAUDE.md`. + +- [ ] **Step 7: Commit** + +```bash +git add frontend .github/workflows/ci.yml CLAUDE.md +git commit -m "feat(panel): add panel tooling, grid model and validation" +``` + +--- + +### Task 2: Edit operations, colours and emoji + +**Files:** +- Create: `frontend/src/model/edit.ts`, `frontend/src/model/color.ts`, `frontend/test/edit.test.ts`, `frontend/test/color.test.ts`, `frontend/test/emoji.test.ts` + +**Interfaces:** +- Consumes: `canDelete` (Task 1). +- Produces. Every function is pure and returns a new `Layout` without mutating its input. + - `PALETTE = ["#C94F3D", "#4F86DD", "#5B9E4D", "#7B2FA0", "#E08A2E", "#2E9E8F", "#D2477A", "#5C6BC0"]` + - `nextId(layout, prefix: "b" | "i"): string`: one plus the highest numeric suffix among block and item ids with that prefix. + - `addBlock(layout, cell): {layout, id}`. The new block gets name `Block ` (n = the numeric part of its id), background `PALETTE[blocks.length % 8]`, font `m`, type `custom` and `items: []`. If `start` was null, it becomes the start block. + - `deleteBlock(layout, id)`. Throws if `canDelete` refuses. Deleting the last block sets `start` to `null`. + - `setStart(layout, id)` and `updateBlock(layout, id, patch: Partial)`. + - `setSleepTimeout(layout, seconds: number)`: replaces `settings.sleep_timeout`. + - `addItem(layout, blockId, kind): {layout, id}`. Defaults: text `{text: "Text"}`, emoji `{emoji: "💡"}`, entity `{entity_id: "", attribute: null}`. Every kind gets `font_size: null`. + - `updateItem(layout, blockId, itemId, patch)`, `removeItem(layout, blockId, itemId)` and `moveItem(layout, blockId, itemId, delta: -1 | 1)`. `moveItem` is a no-op at either end. + - `textColorFor(bg: string): "#000000" | "#FFFFFF"`: `#000000` if WCAG relative luminance > 0.30 (spec §5.5). + +- [ ] **Step 1: Write the failing tests** + +```ts +const r = addBlock(validLayouts.reference, {x: 1, y: 0}); +expect(r.id).toBe("b5"); +expect(r.layout.blocks.at(-1)).toMatchObject({name: "Block 5", background: "#E08A2E", font_size: "m", type: "custom", items: []}); +expect(r.layout.start).toBe("b1"); +expect(addBlock(validLayouts.empty, {x: 0, y: 0}).layout).toMatchObject({start: "b1", blocks: [{id: "b1", background: "#C94F3D"}]}); +expect(nextId(validLayouts.reference, "i")).toBe("i6"); +expect(deleteBlock(validLayouts.single, "b1")).toEqual({version: 1, start: null, settings: {sleep_timeout: 0}, blocks: []}); +expect(setSleepTimeout(validLayouts.reference, 45).settings).toEqual({sleep_timeout: 45}); +expect(() => deleteBlock(validLayouts.reference, "b3")).toThrow(); +expect(itemIds(moveItem(validLayouts.reference, "b3", "i1", 1), "b3")).toEqual(["i2", "i1", "i3", "i4", "i5"]); +expect(itemIds(moveItem(validLayouts.reference, "b3", "i1", -1), "b3")).toEqual(["i1", "i2", "i3", "i4", "i5"]); +const copy = structuredClone(validLayouts.reference); updateBlock(copy, "b2", {name: "X"}); expect(copy).toEqual(validLayouts.reference); +for (const c of colors) expect(textColorFor(c.bg)).toBe(c.text); +expect(SUPPORTED_EMOJI).toHaveLength(64); expect(normalizeEmoji("❄️")).toBe("❄"); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement `edit.ts` and `color.ts`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `npm --prefix frontend test` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add frontend/src/model frontend/test +git commit -m "feat(panel): add pure layout edit operations" +``` + +--- + +### Task 3: Block map component (`hc-grid`) + +**Files:** +- Create: `frontend/src/components/hc-grid.ts`, `frontend/test/hc-grid.test.ts` + +**Interfaces:** +- Consumes: `placeholders`, `gridBounds` and `textColorFor`. +- Produces: a `` element. + - **Properties:** `layout: Layout`, `selectedId: string | null`, `errorRefs: ReadonlySet`. + - **Rendering:** a CSS grid with 96 px cells, a 12 px gap and a 16 px radius. Each cell is placed with `grid-column: x - minX + 1` and `grid-row: y - minY + 1`. + - Blocks: `button.block[data-id]`, filled with their background, showing the name in `textColorFor(background)`. + - The start block carries a 3 px outline and a `span.start-badge` with the text `start`. + - Placeholders: `button.placeholder[data-x][data-y]`, with a 2 px dashed `--divider-color` border and a `+`. + - State classes: `.selected` (ring in `--primary-color`) and `.has-error` (ring in `--error-color`). + - **Events:** `hc-add-block` `{detail: {x, y}}` and `hc-select-block` `{detail: {id}}`. Both bubble and are composed. + +- [ ] **Step 1: Write the failing tests** + +```ts +const el = await mount(html``); +expect(all(el, ".block")).toHaveLength(4); +expect(all(el, ".placeholder")).toHaveLength(8); +expect(one(el, '.block[data-id="b1"] .start-badge')?.textContent).toBe("start"); +expect(one(el, '.block[data-id="b4"]')!.classList.contains("has-error")).toBe(true); +const added = nextEvent(el, "hc-add-block"); one(el, '.placeholder[data-x="1"][data-y="0"]')!.click(); +expect((await added).detail).toEqual({x: 1, y: 0}); +// grid placement: b3 (-1, 0) → column 2, row 3 with bounds minX -2, minY -2 +expect(one(el, '.block[data-id="b3"]')!.style.gridColumn).toBe("2"); expect(one(el, '.block[data-id="b3"]')!.style.gridRow).toBe("3"); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement `hc-grid.ts`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `npm --prefix frontend test` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add frontend/src/components/hc-grid.ts frontend/test/hc-grid.test.ts +git commit -m "feat(panel): render the block map" +``` + +--- + +### Task 4: Block editor components + +**Files:** +- Create: + - `frontend/src/messages.ts` + - `frontend/src/components/`: `hc-block-editor.ts`, `hc-item-editor.ts`, `hc-entity-input.ts`, `hc-emoji-picker.ts`, `hc-preview.ts` + - `frontend/test/hc-block-editor.test.ts`, `frontend/test/hc-item-editor.test.ts` + +**Interfaces:** +- Consumes: the Task 2 edit operations and `canDelete`. +- Produces: + - **`messages.ts`:** + - `errorMessage(code: string): string`, keyed by error code: + + | code | Message | + |---|---| + | `invalid_structure` | "The layout is malformed." | + | `too_many_blocks` | "A screen holds at most 32 blocks." | + | `invalid_id` | "Invalid identifier." | + | `duplicate_id` | "Duplicate identifier." | + | `coordinate_out_of_range` | "This block is too far from the centre of the map." | + | `duplicate_position` | "Two blocks share the same cell." | + | `invalid_start` | "Choose a start block." | + | `disconnected` | "This block can't be reached from the start block." | + | `invalid_name` | "Names need 1 to 32 characters." | + | `invalid_background` | "Pick a background colour." | + | `invalid_font_size` | "Pick a font size." | + | `invalid_type` | "Pick a block type." | + | `invalid_entity` | "Pick a valid entity." | + | `too_many_items` | "A custom block holds at most 6 items." | + | `invalid_item` | "Unknown item type." | + | `invalid_text` | "Text needs 1 to 64 characters." | + | `unsupported_emoji` | "This emoji is not available on the screen." | + | `payload_too_large` | "The layout is too large for the screen. Remove blocks or shorten texts." | + | `invalid_sleep_timeout` | "The sleep delay must be 0 (never) or between 5 and 3600 seconds." | + | any other code | "Invalid layout." | + + - `deleteReason`: `start` → "Choose another start block first."; `disconnects` → "Other blocks would become unreachable." + - **``:** properties `hass`, `layout` and `blockId`. It emits `hc-layout-change` `{detail: {layout}}` and contains: + - a name input and a background colour input with 8 palette swatches; + - font size buttons `S M L XL`; + - a type select (`Entity` / `Custom`) that switches with `updateBlock` and keeps the other type's fields; + - for entity blocks, ``; + - for custom blocks, the item list with an "Add item" select (Text, Emoji, Entity state, Battery, Screen brightness); + - a `Set as start block` button, disabled for the start block; + - a `Delete block` button, disabled with `deleteReason` text when `canDelete` refuses; + - ``. + - **``:** + - Properties: `hass`, `item`, `index` and `count`. + - Kind-specific fields: + - text: an input; + - emoji: ``; + - entity: `` (all domains) plus an optional attribute input. + - A font size select (Inherit/S/M/L/XL) and up/down/remove buttons. + - Events: `hc-item-change {patch}`, `hc-item-move {delta}` and `hc-item-remove`. + - **``:** properties `hass`, `value` and `domains?: string[]`. It renders an `` with a `` of matching entity ids, sorted, labelled by `friendly_name`, and emits `hc-value-change {value}`. + - **``:** property `value`. It renders 64 `button.emoji` elements and emits `hc-value-change {value: normalizeEmoji(...)}`. + - **``:** properties `block` and `hass`. It renders a 220 px circle in the block background with contrast text, showing the name and a content summary: + - entity blocks: the entity's state; + - custom blocks: one line per item. + +- [ ] **Step 1: Write the failing tests** + +```ts +// hc-block-editor +const changed = nextEvent(el, "hc-layout-change"); type(one(el, "input[name=name]")!, "Kitchen 2"); +expect((await changed).detail.layout.blocks[0].name).toBe("Kitchen 2"); +expect(options(el, "hc-entity-input datalist option")).toEqual(["climate.bedroom", "light.kitchen", "light.living_room"]); // hass has sensor.* too +expect(one(el, "button.delete")!.hasAttribute("disabled")).toBe(true); // start block of the reference layout +expect(el.shadowRoot!.textContent).toContain("Choose another start block first."); +// switching b1 to Custom keeps entity_id, adds items [] +// hc-item-editor / emoji picker +expect(all(picker, "button.emoji")).toHaveLength(64); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement the five components and `messages.ts`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `npm --prefix frontend test && npm --prefix frontend run typecheck` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add frontend/src frontend/test +git commit -m "feat(panel): add block and item editors" +``` + +--- + +### Task 5: Panel root, websocket API, dev harness, build and docs + +**Files:** +- Create: + - `frontend/src/ha-controller-panel.ts`, `frontend/src/api.ts` + - `frontend/dev/index.html`, `frontend/dev/mock-hass.ts` + - `frontend/test/panel.test.ts` + - `docs/configuration.md` +- Modify: `docs/README.md`, `docs/development.md` ("Panel" section), `CLAUDE.md` + +**Interfaces:** +- Consumes: plan 2's websocket commands `ha_controller/screens`, `ha_controller/layout/get` and `ha_controller/layout/save`; Tasks 1–4. +- Produces: + - **`api.ts`:** `listScreens(hass): Promise`, `getLayout(hass, entryId): Promise` and `saveLayout(hass, entryId, layout): Promise<{revision: string, pushed: boolean}>`. + - **``:** + - Properties: `hass`, `narrow`, `panel`, `route`. + - Internal state: `screens`, `entryId`, `saved`, `layout` (working copy), `selectedId`, `notice`, `saving`. + - Lifecycle: + - On the first `hass` assignment, load the screens and select the first one. A user selection is kept. + - Refresh only `screens` every 10 s (an interval started in `connectedCallback` and cleared in `disconnectedCallback`). + - Later `hass` changes never reload the layout. + - Header: + - `ha-menu-button` when `narrow`; + - the title "HA Controller"; + - a screen select, shown when there is more than one screen; + - the status line, one of: + - `Offline` + - `Online · firmware — update available`, when the firmware differs from the integration version + - `Online · firmware · in sync`, when `revision == device_revision` + - `Online · firmware · syncing…` + - `Revert` and `Save` buttons, disabled when `layout` deep-equals `saved` or when local validation returns errors. + - Body: `` plus `` side by side, stacked when narrow. Local errors are listed under the map as `errorMessage(code)` plus the block name, and `errorRefs` is passed to the grid. + - Screen settings: a "Screen" section under the map, with a number input "Sleep after (seconds)" wired through `setSleepTimeout` and the helper text "0 keeps the screen on." + - Save: + - Success: `Saved — sent to the screen.` when `pushed`, else `Saved — the screen is offline and will update when it reconnects.` + - On rejection, keep the working copy. If `code == "invalid_layout"`, show the parsed error messages; otherwise show `err.message`. + - **`dev/mock-hass.ts`:** `createMockHass()` returns a `Hass` with: + - states for `light.kitchen`, `light.living_room`, `climate.bedroom` and `sensor.outdoor_temperature`; + - `callWS` that serves one screen and keeps the layout in memory, starting from the reference fixture. + + Tests and `dev/index.html` both use it. + +- [ ] **Step 1: Write the failing tests** in `panel.test.ts`, using `createMockHass` with `callWS` wrapped in `vi.fn`. + +```ts +test("loads the first screen and renders its map", ...) // 4 .block inside hc-grid +test("save is disabled until something changes", ...) +test("adding a block and saving sends the new layout", ...) // callWS called with {type: "ha_controller/layout/save", entry_id, layout: 5 blocks}; notice "Saved — sent to the screen." +test("save error keeps changes", ...) // callWS rejects {code: "invalid_layout", message: "invalid_name@b2"} → "Names need 1 to 32 characters." shown, 5 blocks still rendered +test("refresh does not reset working copy", ...) // edit, advance fake timers 10 s, assign a new hass → edit still present +test("changing the sleep delay enables Save and sends it", ...) // 20 → 45; saved layout.settings.sleep_timeout === 45 +test("status line reports update available", ...) // firmware_version 0.0.9 vs integration 0.1.0 +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement `api.ts`, `ha-controller-panel.ts` (with `customElements.define` guarded against double definition), `dev/mock-hass.ts` and `dev/index.html`.** + +- [ ] **Step 4: Run the tests and the build** + +Run: `npm --prefix frontend test && npm --prefix frontend run build && test -f custom_components/ha_controller/frontend/ha-controller-panel.js` +Expected: PASS, and the bundle exists. + +- [ ] **Step 5: Manual check.** Run `npm --prefix frontend run dev`. Expected: + - the reference map looks like the screenshot, with 4 blocks and 8 "+"; + - clicking "+" right of Kitchen adds "Block 5"; + - deleting Hello World is refused with "Other blocks would become unreachable."; + - Save shows the notice. + + The end-to-end check inside Home Assistant happens in plan 4, Task 5. + +- [ ] **Step 6: Write the docs.** + - **`docs/configuration.md`** (user guide): + - opening the panel (sidebar › HA Controller, admin only); + - the map: start block, adding a block with "+"; + - how swiping on the screen follows the map: put a finger on the right edge and slide left to open the block on the right, and the same for every edge; + - block types (Light, Thermostat, Custom) and custom items; + - font sizes S/M/L/XL and backgrounds (text colour is automatic); + - screen settings: the sleep delay (default 20 s; `0` keeps the screen on); + - saving and the status line; + - limits (32 blocks, 6 items, 32-char names, 64-char texts, 64 emoji). + - **`docs/development.md`**, "Panel" section: `npm ci`, `npm test`, `npm run dev` (mock harness), and `npm run build -- --watch` while testing in Home Assistant. + - **`docs/README.md`:** link `configuration.md`. + +- [ ] **Step 7: Commit** + +```bash +git add frontend docs CLAUDE.md +git commit -m "feat(panel): add panel root with save, status and dev harness" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md b/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md new file mode 100644 index 0000000..f2108c6 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md @@ -0,0 +1,875 @@ +# HA Controller — Plan 4: ESPHome Firmware + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build the screen firmware: an ESPHome config for the Waveshare ESP32-S3-Touch-AMOLED-1.75 plus a desktop simulator. It renders the layout pushed by the integration, navigates between blocks with edge swipes and smooth slides, drives the light/climate knobs and custom items, sleeps after the configured delay and wakes on touch, reports controls and hellos to Home Assistant, and installs firmware over the air on request. + +**Architecture:** Two local external components. +- `ha_controller`: + - **Pure C++17 modules** with no ESPHome or LVGL headers, unit-tested on the host against `protocol/fixtures/`: `layout`, `states`, `knob`, `format`, `gesture`, `color`, `hold`. + - **LVGL 9.5 modules:** `pager` (gestures, animation, edge hints) and `widgets` (block views). + - **`HaController`:** the ESPHome component that glues them to the native API actions and events declared in YAML. +- `axp2101_battery`: reads the PMU. + +YAML is split into `packages/board-waveshare-amoled-175.yaml` (hardware) and `packages/ui.yaml` (UI, API actions, hello). The device config and `simulator.yaml` (ESPHome `host` + SDL) both include them. + +**Tech Stack:** ESPHome 2026.10.2, ESP-IDF, LVGL 9.5 (bundled by ESPHome), ArduinoJson 7, C++17, CMake ≥ 3.20, doctest 2.4.12, Python 3.13 (ESPHome CLI), SDL2 (simulator). + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§4, §5, §7, §15) + +## Global Constraints + +- **ESPHome:** `esphome==2026.10.2` in `esphome/requirements.txt`, `min_version: 2026.10.0`, framework `esp-idf`. ESPHome project `pyxel-dev.ha-controller`, version `${project_version}` from `esphome/version.yaml`. +- **Hardware:** all pins, addresses, transforms and registers exactly as spec §4. The touch component `cst9217` comes from `https://github.com/shelson/esphome-cst9217`, pinned to the commit SHA current at implementation time. +- **LVGL 9.5 API names:** + - screens and objects: `lv_screen_load`, `lv_layer_top`, `lv_obj_delete`, `lv_obj_remove_flag`; + - animations: `lv_anim_set_duration`, `lv_anim_set_completed_cb`, `lv_anim_delete`, `lv_anim_path_ease_out`; + - input and events: `lv_indev_active`, `lv_indev_get_point`, `lv_event_get_target_obj`, `lv_event_get_hit_test_info`; + - rendering and activity: `lv_refr_now`, `lv_display_get_inactive_time`, `lv_display_trigger_activity`. + + Every LVGL call runs on the ESPHome main loop: `setup`, `loop`, API actions or LVGL event callbacks. +- **Pure modules:** `layout.*`, `states.*`, `knob.h`, `format.h`, `gesture.*`, `color.h`, `hold.h` and `axp2101_regs.h` include only the standard library and ``. They compile on the host in C++17. All component sources stay flat in their component directory. +- **Protocol and constants:** protocol v1 (spec §7) and constants (spec §15). `PROTOCOL_VERSION = 1` lives in `layout.h`. +- **ESPHome callbacks:** views never register ESPHome sensor or number callbacks. `HaController` subscribes once in `setup()` and forwards to the live views, because callbacks cannot be removed when the layout is rebuilt. +- **Secrets:** no Wi-Fi credentials or secrets in any committed YAML. + +## Review Focus + +1. **A layout or state push arriving mid-swipe.** The pager must cancel the animation, reset the tracker and show the right page, with no dangling pointers. Owner: Task 3 `SwipeTracker reset` test, plus the Task 6 manual check "push a layout while dragging". +2. **Malformed or hostile payloads:** wrong types, huge numbers, missing `items`, deep nesting. The parser must return `invalid_payload` and leave the current UI untouched. Owner: Task 1 extra parser cases. +3. **Touches exactly on the ring boundary, on the diagonal, outside the visible circle, or arriving as several points.** Classification must stay deterministic. Owner: Task 3 boundary and tie tests. +4. **Battery absent or PMU not answering.** The sensors publish NaN, battery rows show `— %`, and nothing crashes. Owner: Task 2 `format_percent(NAN)`, Task 4 decode tests, Task 7 manual check with the battery unplugged. +5. **The touch that wakes a sleeping screen.** It must never toggle a light or move a knob, and the screen must not fall straight back asleep. Owner: Task 8 `should_sleep` tests and the Task 8 manual wake checks. The `millis()` wraparound cases remain covered by the Task 2 and Task 3 tests. + +--- + +### Task 1: Host test harness, layout parser and colours + +**Files:** +- Create: + - `esphome/components/ha_controller/layout.h`, `layout.cpp`, `color.h` + - `esphome/tests/CMakeLists.txt`, `esphome/tests/test_main.cpp`, `esphome/tests/fixtures.h` + - `esphome/tests/test_layout.cpp`, `esphome/tests/test_color.cpp` + +**Interfaces:** +- Produces (namespace `esphome::ha_controller`): + +```cpp +constexpr int PROTOCOL_VERSION = 1; +enum class FontSize : uint8_t { S, M, L, XL }; +enum class Widget : uint8_t { LIGHT, CLIMATE, CUSTOM }; +enum class ItemKind : uint8_t { TEXT, EMOJI, ENTITY, BATTERY, BRIGHTNESS }; +enum class ParseError : uint8_t { NONE, BAD_JSON, UNSUPPORTED_VERSION, INVALID_PAYLOAD }; +struct Item { std::string id; ItemKind kind; FontSize font; std::string text; }; +struct Block { std::string id; int x; int y; std::string name; uint32_t bg; FontSize font; Widget widget; std::vector items; }; +struct Layout { + std::string rev; std::string start; // start is "" when null + uint32_t sleep_s{20}; // payload "sleep"; 0 = never + std::vector blocks; + const Block *find(const std::string &id) const; + const Block *find_at(int x, int y) const; +}; +ParseError parse_layout(const std::string &json, Layout &out); // `out` is replaced only on NONE +const char *parse_error_code(ParseError e); // "none", "bad_json", "unsupported_version", "invalid_payload" +// color.h +bool parse_hex_rgb(const std::string &hex, uint32_t &out); // "RRGGBB" or "#RRGGBB" +float relative_luminance(uint32_t rgb); +uint32_t text_color_for(uint32_t rgb); // 0x000000 if luminance > 0.30 else 0xFFFFFF +``` + + Test helpers in `fixtures.h`: `std::string read_fixture(const std::string &relative)`, which reads from the `FIXTURES_DIR` compile definition, and `std::string json_field(const std::string &file, const char *key)`, which re-serialises one top-level field. + +- [ ] **Step 1: Set up the host harness** in `esphome/tests/CMakeLists.txt`: + - CMake ≥ 3.20, C++17. + - `FetchContent` doctest `v2.4.12` (GIT_TAG) and ArduinoJson `v7.4.2` (GIT_TAG; same major as ESPHome's bundled 7.x). + - Target `unit_tests`: every `test_*.cpp` plus the pure `.cpp` files from `../components/ha_controller/`. + - Include path `../components`. + - `FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../../protocol/fixtures"`. + - `add_test(unit_tests …)`. + +- [ ] **Step 2: Write the failing tests** + +```cpp +TEST_CASE("parses the reference payload") { + Layout l; REQUIRE(parse_layout(json_field("payloads/valid/reference.json", "payload"), l) == ParseError::NONE); + CHECK(l.rev == "90538742"); CHECK(l.start == "b1"); CHECK(l.sleep_s == 20); CHECK(l.blocks.size() == 4); + CHECK(l.find("b3")->widget == Widget::CUSTOM); CHECK(l.find("b3")->items.size() == 5); + CHECK(l.find("b3")->items[1].kind == ItemKind::EMOJI); CHECK(l.find("b3")->items[1].text == "👋"); + CHECK(l.find("b3")->items[1].font == FontSize::XL); CHECK(l.find("b3")->items[2].font == FontSize::S); + CHECK(l.find("b4")->widget == Widget::CLIMATE); CHECK(l.find("b1")->bg == 0x5B9E4D); + CHECK(l.find_at(0, -1)->id == "b2"); CHECK(l.find_at(5, 5) == nullptr); +} +TEST_CASE("parses the empty payload") { /* start == "" and blocks empty */ } +TEST_CASE("strips U+FE0F from emoji text") { /* {"…","kind":"emoji","text":"❄️",…} → "❄" */ } +TEST_CASE("rejects every invalid payload fixture") { + // for each payloads/invalid/*.json: parse_layout(text, l) returns the expected code; a pre-filled `l` is unchanged +} +TEST_CASE("rejects hostile payloads") { + // "x": 1e40 · "x": "1" · "name": 5 · custom block without "items" · "font": "xxl" · "bg": "GGGGGG" · "sleep": -1 · "sleep": 4000 · no "sleep" · nested 64-deep arrays → INVALID_PAYLOAD or BAD_JSON +} +TEST_CASE("text colour follows colors.json") { /* every entry: text_color_for(bg) == text */ } +``` + +- [ ] **Step 3: Run the tests to verify they fail** + +Run: `cmake -S esphome/tests -B build/tests && cmake --build build/tests` +Expected: FAIL (`layout.h` not found). + +- [ ] **Step 4: Implement `layout.cpp` and `color.h`.** + - Use `JsonDocument doc; deserializeJson(doc, json)`. An error or non-object gives `BAD_JSON`. + - `v` must be the integer 1; otherwise `UNSUPPORTED_VERSION`. + - Every required field from spec §7.3 must be present with its JSON type, `x`/`y` must fit `int`, and `sleep` must be an integer from 0 to 3600. Otherwise `INVALID_PAYLOAD`. + - Remove the UTF-8 bytes `EF B8 8F` from `text`. + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `cmake --build build/tests && ctest --test-dir build/tests --output-on-failure` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add esphome/components/ha_controller esphome/tests +git commit -m "feat(firmware): parse layout payloads on the screen" +``` + +--- + +### Task 2: State parser, knob scale, formatting and interaction hold + +**Files:** +- Create: + - `esphome/components/ha_controller/states.h`, `states.cpp`, `knob.h`, `format.h`, `hold.h` + - `esphome/tests/test_states.cpp`, `test_knob.cpp`, `test_format.cpp`, `test_hold.cpp` + +**Interfaces:** +- Produces: + +```cpp +struct StateUpdate { + std::string id; bool available{true}; + std::optional on; std::optional brightness; // light (nullopt brightness = on/off only) + std::optional target; float min{7}, max{35}, step{0.5f}; // climate + std::string unit, current, action; // climate + std::optional text; // entity item +}; +bool parse_states(const std::string &json, std::vector &out); // false on bad JSON / not an array; elements without a string id are skipped +struct KnobScale { + float min, max, step; + int steps() const; // round((max-min)/step); step <= 0 counts as 1; 0 when max <= min + int index_of(float value) const; // clamped to [0, steps()] + float value_at(int index) const; // min + index*step, clamped to [min, max] +}; +std::string format_value(float value, float step); // 1 decimal if step < 1, else none +std::string format_percent(float pct); // "87 %", NaN → "— %" +class InteractionHold { public: explicit InteractionHold(uint32_t window_ms = 1500); + void touch(uint32_t now_ms); bool active(uint32_t now_ms) const; }; // active iff touched and (now - last) < window, unsigned +``` + +- [ ] **Step 1: Write the failing tests** + +```cpp +// states: parse json_field("states/.json", "updates") for each fixture +CHECK(u.on == true); CHECK(u.brightness == 50); // light-dimmable-on +CHECK(!u.brightness.has_value()); // light-onoff +CHECK(u.available == false); // light-unavailable +CHECK(*u.target == doctest::Approx(20.5)); CHECK(u.step == doctest::Approx(0.5)); +CHECK(u.unit == "°C"); CHECK(u.current == "19.8 °C"); CHECK(u.action == "Heating"); // climate-heating +CHECK(!u.target.has_value()); CHECK(u.current == "—"); // climate-defaults +CHECK(*u.text == "12.3 °C"); // entity-precision +CHECK_FALSE(parse_states("{\"id\":1}", out)); +// knob +CHECK(KnobScale{0, 100, 1}.steps() == 100); CHECK(KnobScale{7, 35, 0.5f}.steps() == 56); +CHECK(KnobScale{7, 35, 0.5f}.index_of(20.5f) == 27); CHECK(KnobScale{7, 35, 0.5f}.value_at(27) == doctest::Approx(20.5)); +CHECK(KnobScale{7, 35, 0.5f}.index_of(100) == 56); CHECK(KnobScale{7, 35, 0.5f}.index_of(-5) == 0); +CHECK(KnobScale{10, 10, 0.5f}.steps() == 0); CHECK(KnobScale{7, 35, 0}.steps() == 28); +// format +CHECK(format_value(20.5f, 0.5f) == "20.5"); CHECK(format_value(21, 1) == "21"); CHECK(format_value(21, 0.5f) == "21.0"); +CHECK(format_percent(87.4f) == "87 %"); CHECK(format_percent(NAN) == "— %"); +// hold +InteractionHold h; CHECK_FALSE(h.active(0)); h.touch(1000); CHECK(h.active(2499)); CHECK_FALSE(h.active(2500)); +h.touch(0xFFFFFF00u); CHECK(h.active(0x00000100u)); // wraparound +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build build/tests` +Expected: FAIL. + +- [ ] **Step 3: Implement the five headers and `states.cpp`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build build/tests && ctest --test-dir build/tests --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller esphome/tests +git commit -m "feat(firmware): parse state updates and add knob helpers" +``` + +--- + +### Task 3: Edge-swipe gesture model + +**Files:** +- Create: `esphome/components/ha_controller/gesture.h`, `gesture.cpp`, `esphome/tests/test_gesture.cpp` + +**Interfaces:** +- Produces (spec §5.2–§5.3): + +```cpp +enum class Edge : uint8_t { NONE, LEFT, RIGHT, TOP, BOTTOM }; +struct GridStep { int dx; int dy; }; +Edge classify_edge(int x, int y, int size, int edge_width); // centre = size/2.0f; ring iff r >= size/2.0f - edge_width (inclusive); |dx| >= |dy| → horizontal +GridStep step_for(Edge edge); // RIGHT {1,0} · LEFT {-1,0} · TOP {0,-1} · BOTTOM {0,1} · NONE {0,0} +struct SwipeConfig { int size = 466; float commit_ratio = 0.25f; float flick_velocity = 0.6f; + int flick_min_px = 24; float rubber_factor = 0.3f; int rubber_max_px = 48; uint32_t velocity_window_ms = 100; }; +class SwipeTracker { + public: + explicit SwipeTracker(SwipeConfig cfg = {}); + void begin(Edge edge, bool has_target, int x, int y, uint32_t t_ms); + int update(int x, int y, uint32_t t_ms); // visual offset (px) along the navigation axis + bool release(uint32_t t_ms); // true = commit; tracker becomes inactive + void reset(); // abort without decision + bool active() const; Edge edge() const; int progress() const; +}; +uint32_t settle_duration_ms(int remaining_px, int size); // clamp(220 * remaining / size, 80, 220) +``` + +- [ ] **Step 1: Write the failing tests** + +```cpp +CHECK(classify_edge(233, 233, 466, 36) == Edge::NONE); CHECK(classify_edge(460, 233, 466, 36) == Edge::RIGHT); +CHECK(classify_edge(5, 233, 466, 36) == Edge::LEFT); CHECK(classify_edge(233, 4, 466, 36) == Edge::TOP); +CHECK(classify_edge(233, 462, 466, 36) == Edge::BOTTOM); CHECK(classify_edge(430, 233, 466, 36) == Edge::RIGHT); // r = 197, boundary +CHECK(classify_edge(429, 233, 466, 36) == Edge::NONE); CHECK(classify_edge(10, 10, 466, 36) == Edge::LEFT); // diagonal tie → horizontal +CHECK(classify_edge(456, 10, 466, 36) == Edge::RIGHT); // outside the visible circle still classifies +SwipeTracker t; +t.begin(Edge::RIGHT, true, 460, 233, 0); CHECK(t.update(400, 233, 50) == 60); CHECK(t.update(300, 240, 300) == 160); CHECK(t.release(400)); +t.begin(Edge::RIGHT, true, 460, 233, 0); CHECK(t.update(420, 233, 500) == 40); CHECK_FALSE(t.release(600)); // slow and short +t.begin(Edge::LEFT, true, 5, 233, 0); t.update(25, 233, 10); CHECK(t.update(65, 233, 40) == 60); CHECK(t.release(45)); // flick +t.begin(Edge::RIGHT, true, 460, 233, 0); CHECK(t.update(470, 233, 50) == 0); // outward ignored +t.begin(Edge::TOP, false, 233, 4, 0); CHECK(t.update(233, 204, 100) == 48); CHECK_FALSE(t.release(150)); // rubber band +t.begin(Edge::BOTTOM, true, 233, 462, 0); CHECK(t.update(233, -600, 50) == 466); // clamp to size +t.begin(Edge::LEFT, true, 5, 233, 0xFFFFFFF0u); t.update(65, 233, 0x00000020u); CHECK(t.release(0x00000020u)); // wraparound flick +t.begin(Edge::LEFT, true, 5, 233, 0); t.update(300, 233, 10); t.reset(); CHECK_FALSE(t.active()); CHECK_FALSE(t.release(20)); +CHECK(settle_duration_ms(466, 466) == 220); CHECK(settle_duration_ms(0, 466) == 80); CHECK(settle_duration_ms(233, 466) == 110); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build build/tests` +Expected: FAIL. + +- [ ] **Step 3: Implement `gesture.cpp`.** Keep a small ring buffer of `(t, progress)` samples, including the `begin` sample. On release, velocity = `(progress_now − progress_old) / (t_now − t_old)`, where `old` is the oldest sample inside `velocity_window_ms`. Use unsigned time differences. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build build/tests && ctest --test-dir build/tests --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller esphome/tests +git commit -m "feat(firmware): model edge swipes" +``` + +--- + +### Task 4: Hardware bring-up — board package, AXP2101 battery, boot page, firmware CI + +**Files:** +- Create: + - `esphome/requirements.txt`, `esphome/version.yaml`, `esphome/ha-controller.yaml` + - `esphome/packages/board-waveshare-amoled-175.yaml`, `esphome/packages/ui.yaml` + - `esphome/components/axp2101_battery/__init__.py`, `axp2101_battery.h`, `axp2101_battery.cpp`, `axp2101_regs.h` + - `esphome/tests/test_axp2101.cpp` + - `.github/workflows/firmware.yml` +- Modify: `esphome/tests/CMakeLists.txt` (include path for `axp2101_battery`), `CLAUDE.md` (commands) + +**Interfaces:** +- Produces: + - **`axp2101_regs.h`** (namespace `esphome::axp2101_battery`): + - register constants `REG_STATUS1 = 0x00`, `REG_STATUS2 = 0x01`, `REG_ADC_CTRL = 0x30`, `REG_VBAT_H = 0x34`, `REG_VBAT_L = 0x35`, `REG_BAT_DET = 0x68`, `REG_BAT_PERCENT = 0xA4`; + - `bool battery_present(uint8_t status1)` (bit 3); + - `bool is_charging(uint8_t status2)`: `(status2 >> 5) == 0x01`; + - `uint16_t battery_millivolts(uint8_t hi, uint8_t lo)`: `((hi & 0x1F) << 8) | lo`; + - `float battery_percent(uint8_t raw)`: capped at 100. + - **The `axp2101_battery:` YAML component:** `PollingComponent` + `i2c::I2CDevice`, default address `0x34`, `update_interval` default 30 s. It has optional sub-entities: + - `battery_level`: sensor, %, device_class `battery`, accuracy 0; + - `battery_voltage`: sensor, V, device_class `voltage`, accuracy 2; + - `charging`: binary sensor, device_class `battery_charging`. + + `setup()` sets bit 0 of `0x30` and bit 0 of `0x68` (read-modify-write) and calls `mark_failed()` on an I²C error. `update()` publishes NaN for level and voltage when no battery is present. + - **YAML ids used by later tasks:** `amoled` (display), `touch`, `bus_a`, `battery_level`, `battery_charging`, `screen_brightness`. The fonts are `font_s|m|l|xl`, `value_s|m|l|xl` and `emoji_s|m|l|xl`. + +- [ ] **Step 1: Write the failing tests** in `test_axp2101.cpp`. + +```cpp +CHECK(battery_present(0x08)); CHECK_FALSE(battery_present(0xF7)); +CHECK(is_charging(0x20)); CHECK(is_charging(0x3F)); CHECK_FALSE(is_charging(0x40)); CHECK_FALSE(is_charging(0x00)); CHECK_FALSE(is_charging(0xA0)); +CHECK(battery_millivolts(0x0F, 0xA0) == 4000); CHECK(battery_millivolts(0xFF, 0xFF) == 0x1FFF); +CHECK(battery_percent(87) == 87.0f); CHECK(battery_percent(150) == 100.0f); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build build/tests` +Expected: FAIL (`axp2101_regs.h` not found). + +- [ ] **Step 3: Implement `axp2101_regs.h`, the `axp2101_battery` component (`__init__.py`, `.h`, `.cpp`) and the CMake include path** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build build/tests && ctest --test-dir build/tests --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Write the YAML.** + - **`esphome/requirements.txt`:** `esphome==2026.10.2`. + - **`esphome/version.yaml`:** `substitutions: {project_version: "0.1.0"}`. + - **`esphome/packages/board-waveshare-amoled-175.yaml`**, verbatim apart from the SHA: + +```yaml +esphome: + platformio_options: + board_build.flash_mode: dio + board_build.f_flash: 80000000L + board_build.f_cpu: 240000000L +esp32: + variant: esp32s3 + flash_size: 16MB + framework: + type: esp-idf +psram: + mode: octal + speed: 80MHz +external_components: + - source: + type: git + url: https://github.com/shelson/esphome-cst9217 + ref: + components: [cst9217] +i2c: + - id: bus_a + sda: GPIO15 + scl: GPIO14 + frequency: 400kHz +spi: + - id: display_qspi + type: quad + clk_pin: GPIO38 + data_pins: [GPIO4, GPIO5, GPIO6, GPIO7] +display: + - platform: mipi_spi + id: amoled + model: CO5300 + bus_mode: quad + reset_pin: GPIO39 + cs_pin: GPIO12 + dimensions: {width: 466, height: 466} + auto_clear_enabled: false + update_interval: never +touchscreen: + - platform: cst9217 + id: touch + display: amoled + interrupt_pin: GPIO11 + reset_pin: GPIO40 + transform: {mirror_x: true, mirror_y: true} + on_touch: + - logger.log: {level: DEBUG, format: "touch x=%d y=%d", args: [touch.x, touch.y]} +axp2101_battery: + i2c_id: bus_a + battery_level: {id: battery_level, name: Battery} + battery_voltage: {name: Battery voltage} + charging: {id: battery_charging, name: Charging} +number: + - platform: template + id: screen_brightness + name: Screen brightness + icon: mdi:brightness-6 + entity_category: config + unit_of_measurement: "%" + min_value: 5 + max_value: 100 + step: 1 + initial_value: 80 + restore_value: true + optimistic: true + on_value: + - lambda: id(amoled).set_brightness((uint8_t) lroundf(x * 2.55f)); +``` + + - **`esphome/packages/ui.yaml`:** + - The 12 fonts of spec §4.2: + - text: `file: {type: gfonts, family: Inter, weight: 600}`, `bpp: 4`, `glyphsets: [GF_Latin_Core]`; + - value: same file, `glyphs: " 0123456789.,-+%°CFOfn—"`; + - emoji: `file: {type: gfonts, family: Noto Emoji}`, `bpp: 4`, `glyphs: !include ../../custom_components/ha_controller/emoji.json`. + - `lvgl:` with `displays: [amoled]`, `touchscreens: [touch]`, `buffer_size: 25%`, `bg_color: 0x000000` and page `boot_page` holding: + - label `HA Controller` (`font_m`, white, centre, y −40); + - label `v${project_version}` (`font_s`, `0x9CA3AF`, y 10); + - label `💡` (`emoji_m`, y 70); + - a hidden `arc` (`keep_arc`) and a hidden `slider` (`keep_slider`), so that ESPHome compiles those LVGL widgets for the runtime code. + - **`esphome/ha-controller.yaml`:** + - Substitutions `name: ha-controller` and `friendly_name: HA Controller`. + - `packages`: `version`, `board`, `ui`. + - `esphome:` with name, friendly_name, `name_add_mac_suffix: true`, `min_version: 2026.10.0` and `project: {name: pyxel-dev.ha-controller, version: ${project_version}}`. + - `logger:`, `api:`, `ota: [{platform: esphome}]`. + - `wifi: {ap: {ssid: HA Controller}}`, `captive_portal:`, `improv_serial:`. + - `external_components: [{source: {type: local, path: components}}]`. + +- [ ] **Step 6: Compile** + +Run: `python3.13 -m venv .venv-esphome && .venv-esphome/bin/pip install -r esphome/requirements.txt && .venv-esphome/bin/esphome compile esphome/ha-controller.yaml` +Expected: `SUCCESS`, and the image fits the app partition (ESPHome sizes it for 16 MB). If a font option is rejected (e.g. `glyphsets`), replace it with an explicit `glyphs:` string covering U+0020–U+007E, U+00A0–U+017F and `°—…’“”€`. Record the change in `docs/hardware.md` in Task 9. + +- [ ] **Step 7: Hardware check.** Flash over USB-C with `.venv-esphome/bin/esphome run esphome/ha-controller.yaml`. Expected: + - the round display shows "HA Controller", the version and 💡, centred; + - tapping near the top/right/bottom/left edges logs about `(233,5)` / `(460,233)` / `(233,460)` / `(5,233)`. If not, fix `transform` (`mirror_x`, `mirror_y`, `swap_xy`) and repeat; + - with a battery: `Battery` reads 0–100 %, `Battery voltage` 3.3–4.3 V, and `Charging` turns on when USB is plugged in; + - without a battery: level and voltage are unknown (NaN) and there are no errors; + - the `Screen brightness` number dims the panel; + - Wi-Fi provisioning works through the `HA Controller` access point and its captive portal. + +- [ ] **Step 8: Add the firmware CI.** In `.github/workflows/firmware.yml`, workflow `Firmware`: + - Triggers: `push` to `main` and `pull_request`, on paths `esphome/**`, `protocol/**`, `custom_components/ha_controller/emoji.json` and `.github/workflows/firmware.yml`. + - Job `host-tests`: `cmake -S esphome/tests -B build/tests`, `cmake --build build/tests`, `ctest --test-dir build/tests --output-on-failure`. + - Job `compile`: + - `actions/setup-python@v5` with Python 3.13; + - `actions/cache@v4` on `~/.platformio` and `esphome/.esphome`, keyed on `hashFiles('esphome/requirements.txt', 'esphome/**/*.yaml')`; + - `pip install -r esphome/requirements.txt`; + - `esphome compile esphome/ha-controller.yaml`. + + Add the host-test and compile commands to `CLAUDE.md`. + +- [ ] **Step 9: Commit** + +```bash +git add esphome .github/workflows/firmware.yml CLAUDE.md +git commit -m "feat(firmware): bring up the Waveshare AMOLED 1.75 board" +``` + +--- + +### Task 5: `ha_controller` component, API actions, hello and simulator + +**Files:** +- Create: + - `esphome/components/ha_controller/__init__.py`, `ha_controller.h`, `ha_controller.cpp` + - `esphome/components/ha_controller/widgets.h`, `widgets.cpp` (placeholder views in this task) + - `esphome/simulator.yaml` +- Modify: `esphome/packages/ui.yaml`, `.github/workflows/firmware.yml` (simulator compile), `CLAUDE.md` + +**Interfaces:** +- Consumes: Tasks 1–2 (parsers), plan 2 (hello handling, `set_layout`/`set_states` callers). +- Produces: + - **The `ha_controller:` YAML component** (`DEPENDENCIES = ["lvgl"]`, `AUTO_LOAD = ["json"]`): + - Keys: `id`, `size` (default 466), `edge_width` (default 36). + - Fonts: `text_fonts`, `value_fonts`, `emoji_fonts`, each a mapping `{s, m, l, xl}` → `font` id. + - Optional local sources: `battery_level` (sensor id), `battery_charging` (binary_sensor id), `screen_brightness` (number id). + - Trigger `on_control`, with variables `block`, `item`, `op` (`std::string`) and `value` (`float`). + - **The component class:** + +```cpp +enum class FontRole : uint8_t { TEXT, VALUE, EMOJI }; +class ControlSink { public: virtual void on_control(const std::string &block, const std::string &item, const char *op, float value) = 0; }; +class HaController : public Component, public ControlSink { + public: + void setup() override; void loop() override; float get_setup_priority() const override; // setup_priority::LATE + void set_geometry(int size, int edge_width); + void set_font(FontRole role, FontSize size, font::Font *font); // wraps with lvgl::FontEngine → const lv_font_t* + void set_battery_sensor(sensor::Sensor *s); void set_charging_sensor(binary_sensor::BinarySensor *s); + void set_brightness_number(number::Number *n); + void add_on_control_callback(std::function &&cb); + void set_layout(const std::string &json); // parse; on NONE rebuild views (keep current block id if still present, else start) + void set_states(const std::string &json); // dispatch each update to the view that owns its id + void show_message(const std::string &title, const std::string &detail); // full-screen overlay + lv_refr_now(nullptr) + void hide_message(); // back to what the current mode requires + std::string get_revision() const; // "none" until a layout is applied + void on_control(const std::string &block, const std::string &item, const char *op, float value) override; +}; +class ControlTrigger : public Trigger { public: explicit ControlTrigger(HaController *parent); }; +// widgets.h (completed in Task 7) +struct Theme { const lv_font_t *text[4]; const lv_font_t *value[4]; const lv_font_t *emoji[4]; int size; int edge_width; }; +struct LocalSources { sensor::Sensor *battery{}; binary_sensor::BinarySensor *charging{}; number::Number *brightness{}; }; +class BlockView { public: virtual ~BlockView(); + lv_obj_t *root() const; const std::string &id() const; + virtual bool owns(const std::string &id) const; + virtual void apply(const StateUpdate &u, uint32_t now_ms); + virtual void on_local_update(); // battery / charging / brightness changed + virtual void loop(uint32_t now_ms); }; +std::unique_ptr make_block_view(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink, const LocalSources &local); +``` + + - **Messages** (spec §5.9): the "no layout" detail is `App.get_name() + " · v" + ESPHOME_PROJECT_VERSION`. + - **`ui.yaml` additions:** + - the `ha_controller:` block wired to the Task 4 ids; + - `on_control` → `homeassistant.event` `esphome.ha_controller_control`, with data `block`, `item`, `op` and `value: !lambda 'return str_sprintf("%.2f", value);'`; + - `api: on_client_connected: [delay: 5s, script.execute: {id: send_hello, reason: connected}]`; + - API actions `set_layout` (`layout: string`), which calls `id(ui).set_layout(layout)` then `script.execute {id: send_hello, reason: applied}`, and `set_states` (`states: string`); + - script `send_hello` (`parameters: {reason: string}`, `mode: queued`) firing `esphome.ha_controller_hello` with data `node` (`App.get_name()`), `version: ${project_version}`, `protocol: "1"`, `revision` (`id(ui).get_revision()`) and `reason`; + - `interval: 60s`, which runs the script with reason `heartbeat` when `api.connected`. + - **Fallback for event data:** if ESPHome rejects lambdas in `homeassistant.event` `data:`, use `variables:` + `data_template:` with the same keys. + +- [ ] **Step 1: Implement the codegen and the C++ component.** + - In this task, `make_block_view` returns a basic view: a full-screen object with the block background and its name centred in `text_fonts[block.font]` and `text_color_for(bg)`. + - The component builds its own screen (`lv_obj_create(nullptr)` + `lv_screen_load`) in `setup()`. It shows "Waiting for Home Assistant" until a layout arrives, and in this task it shows only the current block. + - `setup()` registers the battery/charging/brightness state callbacks once, and they forward to `view->on_local_update()`. + +- [ ] **Step 2: Write `esphome/simulator.yaml`**: + - `packages`: `version` and `ui`. + - `esphome:`: name `ha-controller-sim`, friendly name `HA Controller Simulator`, the same `project`. + - `host:`, `logger:`, `api:`. + - `display: [{platform: sdl, id: amoled, dimensions: {width: 466, height: 466}, auto_clear_enabled: false, update_interval: never}]` and `touchscreen: [{platform: sdl, id: touch, display: amoled}]`. + - Template stand-ins: `sensor` `battery_level` (constant 76, unit %), `binary_sensor` `battery_charging` (false), and `number` `screen_brightness` (5–100, optimistic, no `on_value`). + - `external_components` (local). + +- [ ] **Step 3: Compile both configs** + +Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Expected: both `SUCCESS`. The simulator needs SDL2: `brew install sdl2` or `apt install libsdl2-dev`. + +- [ ] **Step 4: End-to-end check with Home Assistant**, using plan 2's integration and plan 3's built panel. + 1. Run `.venv-esphome/bin/esphome run esphome/simulator.yaml`. The window shows "Waiting for Home Assistant". + 2. In Home Assistant, add an ESPHome device on `:6053`, then add the HA Controller integration and pick "HA Controller Simulator". + 3. Within 5 s of the connection, the simulator shows "No blocks yet". Developer tools › Events shows `esphome.ha_controller_hello` with reasons `connected` and then `applied`. + 4. In the panel, add three blocks and save. The simulator shows the start block's name on its background. + 5. Heartbeat hellos arrive every 60 s with a revision equal to the panel's. + +- [ ] **Step 5: Extend CI and the docs.** In `firmware.yml` `compile`, add `sudo apt-get install -y libsdl2-dev` and `esphome compile esphome/simulator.yaml`. Add the simulator commands to `CLAUDE.md`. + +- [ ] **Step 6: Commit** + +```bash +git add esphome .github/workflows/firmware.yml CLAUDE.md +git commit -m "feat(firmware): receive layouts and talk to Home Assistant" +``` + +--- + +### Task 6: Pager — edge swipes, slide animation, edge hints + +**Files:** +- Create: `esphome/components/ha_controller/pager.h`, `pager.cpp` +- Modify: `esphome/components/ha_controller/ha_controller.h`, `ha_controller.cpp` + +**Interfaces:** +- Consumes: `classify_edge`, `step_for`, `SwipeTracker` and `settle_duration_ms` (Task 3); `Layout::find_at` (Task 1). +- Produces: + +```cpp +struct PageRef { std::string id; int x; int y; lv_obj_t *obj; }; +class Pager { + public: + void attach(lv_obj_t *screen, int size, int edge_width); // creates viewport, edge overlay on lv_layer_top(), 4 hint arcs + lv_obj_t *viewport() const; // parent for page objects + void set_pages(std::vector pages, const std::string &show_id); // cancels animations, resets tracker, shows one page + void set_enabled(bool enabled); // false while a message is shown + const std::string ¤t_id() const; +}; +``` + +- **Edge overlay:** a transparent full-screen object with `LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_ADV_HITTEST`. On `LV_EVENT_HIT_TEST` it sets `res` to `classify_edge(point) != NONE`. + - `PRESSED` begins the tracker. The target is `find_at(current + step_for(edge))`. A present target page is unhidden at its offset. + - `PRESSING` updates the tracker and positions the pages: current at `(-dx·offset, -dy·offset)`, target at `(dx·(size−offset), dy·(size−offset))`. + - `RELEASED` and `PRESS_LOST` release the tracker and animate with `lv_anim_path_ease_out` over `settle_duration_ms(remaining, size)`. On completion, commit (the target becomes current, the old page is hidden, the hints are refreshed) or cancel (the target is hidden). + - Presses during an animation are ignored. +- **Hints:** four non-clickable arcs on the top layer: + - RIGHT 350°→10°, BOTTOM 80°→100°, LEFT 170°→190°, TOP 260°→280°; + - size 458 px, width 6, white at `LV_OPA_60`, indicator and knob hidden; + - visible only where `find_at` has a neighbour. + +- [ ] **Step 1: Implement `Pager` and use it from `HaController`.** `set_layout` builds the views under `pager.viewport()`, then calls `set_pages`. + +- [ ] **Step 2: Compile both configs** + +Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 3: Simulator check.** Build the reference map in the panel: Kitchen start, Lights above, Hello World left, Bedroom below Hello World. Expected: + - From Kitchen, a mouse-drag from the left edge to the right slides to Hello World. + - From the top edge downwards, it slides to Lights. + - From the right edge leftwards, it rubber-bands by at most 48 px and returns. + - From Hello World, the bottom edge upwards slides to Bedroom. + - A drag starting in the centre does nothing. + - A short slow drag snaps back; a quick flick commits. + - The hints match the neighbours. + - Saving a layout from the panel while holding a drag shows the new layout cleanly, with no stuck half-page. + +- [ ] **Step 4: Device check.** Flash and repeat Step 3 with a finger. The slides look smooth (no visible stutter at ~30 fps or better). If they don't, try in order and keep the best: + 1. `lvgl: buffer_size: 100%`; + 2. `esp32: framework: sdkconfig_options: {CONFIG_ESP32S3_DATA_CACHE_64KB: "y", CONFIG_ESP32S3_DATA_CACHE_LINE_64B: "y"}`; + 3. `lvgl: buffer_size: 12%`. + + Note the result for `docs/hardware.md`. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller esphome/packages +git commit -m "feat(firmware): navigate between blocks with edge swipes" +``` + +--- + +### Task 7: Block views — light knob, climate knob, custom items + +**Files:** +- Modify: `esphome/components/ha_controller/widgets.h`, `widgets.cpp`, `ha_controller.cpp` + +**Interfaces:** +- Consumes: `KnobScale`, `format_value`, `format_percent`, `InteractionHold`, `StateUpdate`, `text_color_for` and `ControlSink` (Tasks 2, 5). +- Produces: `LightView`, `ClimateView` and `CustomView` behind `make_block_view`, following spec §5.5–§5.8 and §5.10. + - **Geometry:** knob arc 370 px, width 28, background angles 135°→45°, `LV_OBJ_FLAG_ADV_HITTEST` so only the ring takes touches. The name sits 96 px from the top. + - **Controls:** + - Arc `LV_EVENT_VALUE_CHANGED` updates the centre label only. + - Arc `LV_EVENT_RELEASED` → `sink.on_control(block, "", "set", value)`. + - A centre tap on a dimmable light → `"toggle"`. The toggle button on an on/off-only light → `"toggle"`. + - Every interaction calls `hold.touch(millis())`. + - **`apply()`:** while the hold is active, store the update as pending. `loop()` applies the pending update once the hold has expired. + - **Unavailable entity:** the centre shows `—` with a small `Unavailable` label, and the arc or button gets `LV_STATE_DISABLED`. + - **Custom items:** + - `text`, `emoji`, `entity` → labels, with `entity` text from `StateUpdate::text`. + - `battery` → a row with `🔋` (or `⚡` while charging) and `format_percent(level)`. + - `brightness` → a row with `☀` and a 220 px slider (5–100). It calls `brightness->make_call().set_value(v).perform()` at most every 100 ms while dragging and always on release, and follows the number's state in `on_local_update()`. + - A custom block without items shows its name centred. + +- [ ] **Step 1: Implement the three views.** + +- [ ] **Step 2: Compile both configs** + +Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 3: Simulator + Home Assistant check.** Use the reference map with real or template entities. Expected: + 1. **Light:** + - The knob shows Home Assistant's brightness. + - Dragging to about 30 % and releasing sets the light to 30 % (logbook). + - A centre tap toggles it. + - A brightness change in Home Assistant moves the knob within 1 s. + - While dragging, incoming updates do not move the knob. + 2. **On/off-only light:** a toggle button. + 3. **Climate:** steps of 0.5 °C; release updates the target; `Now …` and the action are shown. + 4. **Custom block:** + - text, emoji and the outdoor temperature are shown, and the temperature follows sensor changes; + - the battery row shows `🔋 76 %`; + - the brightness slider changes `number.*_screen_brightness`. + 5. **Renamed entity:** renaming one bound entity in Home Assistant shows `—` + `Unavailable` and disables its control. + +- [ ] **Step 4: Device check.** + - Repeat checks 1, 3 and 4 on hardware. + - The battery row shows the real level. + - The brightness slider dims the panel smoothly. + - With the battery unplugged, the row shows `🔋 — %` and nothing crashes. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller +git commit -m "feat(firmware): render light, climate and custom blocks" +``` + +--- + +### Task 8: Screen sleep and wake + +**Files:** +- Create: `esphome/components/ha_controller/sleep.h`, `esphome/tests/test_sleep.cpp` +- Modify: + - `esphome/components/ha_controller/__init__.py`, `ha_controller.h`, `ha_controller.cpp` + - `esphome/packages/ui.yaml`, `esphome/packages/board-waveshare-amoled-175.yaml` + - `esphome/simulator.yaml` + +**Interfaces:** +- Consumes: `Layout::sleep_s` (Task 1); spec §5.11. +- Produces: + +```cpp +// sleep.h (pure) +constexpr uint32_t DEFAULT_SLEEP_S = 20; +bool should_sleep(uint32_t inactive_ms, uint32_t timeout_s); // false when timeout_s == 0; true iff inactive_ms >= timeout_s * 1000 +// HaController additions +void set_sleep_timeout(uint32_t seconds); // set_layout passes layout.sleep_s; DEFAULT_SLEEP_S until the first layout +bool is_sleeping() const; +void wake(); // no-op when awake; otherwise fire on_wake, then lv_display_trigger_activity(nullptr) +``` + + - **`ha_controller:` additions:** + - Required `touchscreen` (id). The component registers a `touchscreen::TouchListener` whose `release()` calls `wake()` while sleeping. + - Triggers `on_sleep` and `on_wake` (no variables). + - **`loop()`:** while awake, when `should_sleep(lv_display_get_inactive_time(nullptr), timeout)` holds, mark the screen as sleeping and fire `on_sleep`. + - **`show_message()`:** calls `wake()` first. + - **YAML wiring:** + - **Board package:** script `screen_on` runs `id(amoled).set_brightness((uint8_t) lroundf(id(screen_brightness).state * 2.55f));`, and script `screen_off` runs `id(amoled).set_brightness(0);`. The `screen_brightness` `on_value` becomes "if `!id(ui).is_sleeping()` then `script.execute: screen_on`". + - **Simulator:** scripts `screen_on` and `screen_off` that only log. + - **`ui.yaml`:** + - `ha_controller:` gets `touchscreen: touch`; + - `on_sleep: [script.execute: screen_off, lvgl.pause]`; + - `on_wake: [lvgl.resume, lvgl.widget.redraw, script.execute: screen_on]`. + +- [ ] **Step 1: Write the failing tests** in `test_sleep.cpp`. + +```cpp +CHECK(DEFAULT_SLEEP_S == 20); +CHECK_FALSE(should_sleep(10'000'000, 0)); // 0 = never +CHECK_FALSE(should_sleep(19'999, 20)); CHECK(should_sleep(20'000, 20)); +CHECK_FALSE(should_sleep(3'599'999, 3600)); CHECK(should_sleep(3'600'000, 3600)); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build build/tests` +Expected: FAIL (`sleep.h` not found). + +- [ ] **Step 3: Implement `sleep.h`** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build build/tests && ctest --test-dir build/tests --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Implement the component additions and the YAML wiring, then compile both configs** + +Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 6: Simulator check.** Expected: + - After 20 s without input, the log shows `screen_off` and the window stops updating. + - Clicking the light knob position wakes the screen without toggling or moving anything. + - Setting the delay to 5 s in the panel makes the screen sleep after 5 s; `0` keeps it awake. + - A Home Assistant state change made while asleep is visible right after waking. + +- [ ] **Step 7: Device check.** Expected: + - The panel goes black after the delay. + - A tap on the knob area only wakes the screen, and the screen stays awake for the full delay afterwards. + - Changing `Screen brightness` from Home Assistant while asleep keeps the panel dark, and the new level shows on wake. + +- [ ] **Step 8: Commit** + +```bash +git add esphome +git commit -m "feat(firmware): sleep after the configured delay and wake on touch" +``` + +--- + +### Task 9: OTA install action, firmware docs, skills and reviewer agent + +**Files:** +- Create: + - `docs/hardware.md` + - `.claude/skills/firmware-dev/SKILL.md`, `.claude/skills/add-widget/SKILL.md` + - `.claude/agents/firmware-reviewer.md` +- Modify: `esphome/ha-controller.yaml`, `docs/development.md` ("Firmware" section), `docs/README.md`, `CLAUDE.md` + +**Interfaces:** +- Produces (used by plan 5): the device API action `install_firmware` (`url: string`, `md5_url: string`): + +```yaml +ota: + - platform: esphome + - platform: http_request +http_request: + verify_ssl: true +api: + actions: + - action: install_firmware + variables: {url: string, md5_url: string} + then: + - lambda: |- + id(ui).show_message("Updating firmware…", "Do not unplug the screen"); + - ota.http_request.flash: + url: !lambda return url; + md5_url: !lambda return md5_url; + - lambda: |- + id(ui).show_message("Update failed", "Check the screen's internet access"); + - delay: 5s + - lambda: id(ui).hide_message(); +``` + + The action lives in the device config only, because the simulator has no HTTP OTA. + +- [ ] **Step 1: Add the action, then compile** + +Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 2: OTA check on hardware.** + 1. Bump `esphome/version.yaml` locally to `0.1.1` (do not commit) and compile. + 2. Find the build output with `find esphome/.esphome/build -name firmware.ota.bin`. In that directory, create `firmware.ota.bin.md5` with `md5 -q firmware.ota.bin > firmware.ota.bin.md5` (Linux: `md5sum firmware.ota.bin | cut -d' ' -f1 > firmware.ota.bin.md5`), then serve it with `python3 -m http.server 8000 -d `. + 3. Call `esphome.ha_controller__install_firmware` from Developer tools with the LAN URLs. The screen shows "Updating firmware…", reboots, and the next hello carries `0.1.1`. Run it once while the screen sleeps: it must wake first. + 4. Repeat with a wrong `.md5`. The screen shows "Update failed" for 5 s, then the pages return. + 5. Revert `version.yaml`. + +- [ ] **Step 3: Write the docs.** + - **`docs/hardware.md`:** + - the board summary and pin table (spec §4); + - power and battery notes; + - the AXP2101 registers; + - the performance settings chosen in Task 6; + - any font fallback chosen in Task 4; + - enclosures: link `../3D_models/` (with or without a PWR button). + - **`docs/development.md`, "Firmware" section:** + - prerequisites: Python 3.13 venv with `esphome/requirements.txt`, CMake, SDL2; + - commands: host tests, compile, flash over USB, simulator; + - connecting Home Assistant to the simulator; + - the manual hardware checklist (Task 4 Step 7, Task 6 Steps 3–4, Task 7 Steps 3–4, Task 8 Steps 6–7, Task 9 Step 2). + - **`docs/README.md`:** link `hardware.md`. + +- [ ] **Step 4: Write the Claude guidance.** + - **`.claude/skills/firmware-dev/SKILL.md`:** + - `name: firmware-dev`. + - `description:` "Use when building, flashing, simulating or changing the ESPHome firmware (esphome/), including LVGL UI code." + - Body: + - commands; + - simulator loop; + - rules: + - pure logic goes in host-tested modules; + - LVGL is called on the main loop only; + - views never register ESPHome callbacks; + - call `lv_refr_now` before blocking work; + - LVGL is paused while the screen sleeps, so call `wake()` before showing anything the user must see; + - fonts are declared in `ui.yaml` and mapped in `ha_controller:`; + - new LVGL widget types need a hidden instance on `boot_page`; + - controls stay inside radius 185; + - keep the `cst9217` SHA pinned. + - **`.claude/skills/add-widget/SKILL.md`:** + - `name: add-widget`. + - `description:` "Use when adding a new block widget or custom item kind (e.g. switch, cover, fan, media volume) end-to-end." + - Body, a checklist that starts with the `protocol-change` skill: + 1. protocol doc and fixtures; + 2. `ENTITY_BLOCK_DOMAINS` / `ITEM_KINDS` in `const.py` and the panel model; + 3. state builder and control mapping; + 4. panel editor options and preview; + 5. C++ parser enum and view; + 6. `docs/configuration.md`; + 7. run all suites and both compiles. + - **`.claude/agents/firmware-reviewer.md`:** + - `name: firmware-reviewer`, `tools: Read, Grep, Glob, Bash`. + - `description:` "Reviews changes under esphome/ for ESPHome/LVGL correctness, memory and hardware safety. Use before merging firmware changes." + - Checklist: + - no blocking calls in `loop` except the OTA action; + - LVGL objects deleted with their views, with animations cancelled first; + - no ESPHome callbacks registered per view; + - JSON parsed defensively; + - pins and addresses match `docs/hardware.md`; + - host tests for new pure logic; + - both configs compile. + - Output: `file:line — issue — fix`. + - **`CLAUDE.md`:** list the skills and the agent. + +- [ ] **Step 5: Run every suite** + +Run: `pytest && npm --prefix frontend test && ctest --test-dir build/tests --output-on-failure` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add esphome/ha-controller.yaml docs .claude CLAUDE.md +git commit -m "feat(firmware): install firmware over the air on request" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md new file mode 100644 index 0000000..5f13681 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md @@ -0,0 +1,340 @@ +# HA Controller — Plan 5: Versioning, Firmware Updates, Web Installer and Releases + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship the integration and the firmware as one version: +- a version check and bump script; +- a firmware update entity in Home Assistant that keeps each screen on the integration's exact version, automatically by default; +- a GitHub Pages web installer that shows the version it flashes; +- a tag-driven release workflow that publishes the HACS zip, the firmware binaries and the Pages site. + +**Architecture:** +- **Versioning:** `scripts/versioning.py` owns the version rule. +- **Updates:** the integration's `update` platform asks the screen, through plan 4's `install_firmware` action, to download its OTA image for the integration version from GitHub Pages. +- **Release scripts:** three small, unit-tested scripts collect the firmware, package the integration and assemble the Pages site from GitHub release assets. +- **Workflow:** `release.yml` chains them on a `vX.Y.Z` tag. A manual run is a dry run. + +**Tech Stack:** Python 3.14 (integration, scripts, tests), Python 3.13 (ESPHome CLI in CI), GitHub Actions, `gh` CLI, ESP Web Tools 10.5.2, HACS. + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§10, §11) + +## Global Constraints + +- **Version:** one SemVer `X.Y.Z` in `custom_components/ha_controller/manifest.json`, `esphome/version.yaml`, `frontend/package.json` and `frontend/package-lock.json` (root `version` and `packages[""].version`). Change it only with `scripts/versioning.py bump`. +- **URLs:** firmware OTA `https://pyxel-dev.github.io/HA-controller/firmware//ha-controller.ota.bin` (+ `.md5`); release notes `https://github.com/pyxel-dev/HA-controller/releases/tag/v`. +- **Release assets:** `ha_controller.zip`, `ha-controller-.factory.bin`, `ha-controller-.ota.bin`, `ha-controller-.ota.bin.md5`. The `.md5` file holds exactly 32 lowercase hex characters and no newline. +- **Timings:** install timeout 300 s; auto-update at most once per screen and version every 3600 s; auto-update only when the integration version matches `^\d+\.\d+\.\d+$`. +- **Strings:** English only. + +## Review Focus + +1. **OTA failing repeatedly** (no internet, Pages outage). Expected: one automatic attempt per hour per version, never a storm. Owner: Task 2 `test_auto_update_installs_at_most_once_per_hour`. +2. **Screen newer than the integration** after an integration rollback. Expected: the update entity offers the integration's version and auto-update installs it. Owner: Task 2 `test_newer_firmware_is_offered_as_update`. +3. **Tag and version mismatch, or a non-SemVer tag.** Expected: the workflow fails before anything is published. Owner: Task 1 `test_check_tag_must_match`; in Task 4 the version check is the first build step. +4. **Pages rebuild dropping older OTA images.** Screens on an older integration could no longer update. Owner: Task 3 `test_build_site_keeps_every_release`. +5. **Install requested while the screen is offline or already updating.** Expected: a clear error and no second install. Owner: Task 2 `test_install_when_offline_raises`, `test_install_while_in_progress_raises`. + +--- + +### Task 1: Version check and bump + +**Files:** +- Create: `scripts/versioning.py`, `tests/scripts/__init__.py`, `tests/scripts/test_versioning.py` +- Modify: `.github/workflows/ci.yml` (job `versions`), `CLAUDE.md` + +**Interfaces:** +- Produces: + - `VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")` + - `def read_versions(root: Path) -> dict[str, str]`, keyed by `manifest`, `esphome`, `frontend`, `frontend-lock`. The `esphome` value comes from the line `project_version: "X.Y.Z"`, and `frontend-lock` must agree in both lock positions. + - `def check_versions(root: Path, tag: str | None = None) -> list[str]`: human-readable errors, `[]` when consistent; `tag` must equal `v` + version. + - `def bump_version(root: Path, version: str) -> None`: raises `ValueError` on non-SemVer input. Rewrites JSON with 2-space indent and a trailing newline, and edits only the YAML line. + - `def main(argv: list[str] | None = None) -> int`: `check [--tag vX.Y.Z]` → 0/1, `bump X.Y.Z` → 0. + +- [ ] **Step 1: Write the failing tests.** A `repo(tmp_path)` fixture writes the four files at `0.1.0`. + +```python +def test_read_versions(repo): assert set(read_versions(repo).values()) == {"0.1.0"} +def test_check_passes_when_equal(repo): assert check_versions(repo) == [] +def test_check_reports_mismatch(repo): ... # manifest 0.2.0 → one error naming "manifest", "0.2.0" and "0.1.0" +def test_check_tag_must_match(repo): + assert check_versions(repo, "v0.1.0") == [] and check_versions(repo, "v0.1.1") and check_versions(repo, "0.1.0") +def test_check_rejects_non_semver(repo): ... # all files "0.1" → error +def test_bump_rewrites_all(repo): ... # bump 1.2.3 → all four "1.2.3"; other JSON keys and YAML lines preserved +@pytest.mark.parametrize("bad", ["1.2", "v1.2.3", "1.2.3-rc1"]) +def test_bump_rejects_invalid(repo, bad): ... +def test_repository_versions_are_consistent(): assert check_versions(REPO_ROOT) == [] +def test_main_exit_codes(repo): ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/scripts/test_versioning.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `scripts/versioning.py`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/scripts -v && python scripts/versioning.py check` +Expected: PASS, exit 0. + +- [ ] **Step 5: Add CI and the docs.** Add job `versions` to `ci.yml` (setup-python 3.14, `python scripts/versioning.py check`). Add the commands to `CLAUDE.md`, and replace its plan-5 placeholder rule with the real command. + +- [ ] **Step 6: Commit** + +```bash +git add scripts/versioning.py tests/scripts .github/workflows/ci.yml CLAUDE.md +git commit -m "build: add single-version check and bump script" +``` + +--- + +### Task 2: Firmware update entity, auto-update and options flow + +**Files:** +- Create: `custom_components/ha_controller/firmware.py`, `custom_components/ha_controller/update.py`, `tests/integration/test_update.py` +- Modify: + - `custom_components/ha_controller/controller.py`, `__init__.py` (`PLATFORMS = [Platform.UPDATE]`), `config_flow.py` (options flow) + - `strings.json`, `translations/en.json` + +**Interfaces:** +- Consumes: plan 2's `ScreenController` (`device`, `integration_version`, `async_call_device`, `async_add_listener`, hello handling); plan 4's device action `install_firmware(url, md5_url)`. +- Produces: + - **`firmware.py`:** `def firmware_urls(version: str) -> tuple[str, str]`, returning the `.ota.bin` URL and its `.md5` URL, and `def is_release_version(version: str) -> bool`. + - **`ScreenController` additions:** + - `install_in_progress: bool`. + - `async def async_install_firmware(self, version: str) -> None`. It raises `HomeAssistantError`: + - "The screen is offline." when it is not online; + - "A firmware update is already running." when an install is in progress; + - when the device call fails; + - "Firmware update to {version} did not complete." when no hello with `{version}` arrives within 300 s. + + It notifies listeners when the install starts and when it ends. + - Auto-update inside `async_handle_hello`: when `entry.options.get(CONF_AUTO_UPDATE, True)`, the integration version is a release, the hello version differs from it, no install is running, and the last automatic attempt for that version is at least 3600 s old, then start `hass.async_create_background_task(...)` that installs and logs any failure. + - **`update.py`:** `FirmwareUpdateEntity(UpdateEntity)`. + - Entity setup: `has_entity_name`, `translation_key = "firmware"` ("HA Controller firmware"), `unique_id = f"{device_id}-firmware"`, `device_info = DeviceInfo(connections=.connections)`. + - Features: `INSTALL | PROGRESS`, `title = "HA Controller"`. + - Versions: `installed_version = controller.device.version` and `latest_version = controller.integration_version`. + - `release_url = RELEASE_URL.format(version=latest)` and `in_progress = controller.install_in_progress`. + - `version_is_newer(latest, installed)` returns `latest != installed`. + - `async_install(version, backup, **kwargs)` installs `latest_version`. + - `async_added_to_hass` subscribes `async_write_ha_state` to the controller. + - **Options flow:** `OptionsFlowHandler(OptionsFlow)` with step `init`: a boolean `auto_update` defaulting to the current option or `True`. `HaControllerConfigFlow.async_get_options_flow(config_entry)` returns `OptionsFlowHandler()`. + - **Strings:** + - `entity.update.firmware.name` = "HA Controller firmware". + - Options step `init`: title "HA Controller options"; `auto_update` label "Update the screen firmware automatically"; description "Installs the firmware that matches this integration's version whenever the screen reports a different one." + +- [ ] **Step 1: Write the failing tests.** Mock the `esphome.ha_controller_aabbcc_install_firmware` service and drive time with `freezer`. + +```python +async def test_unknown_before_first_hello(hass): ... # state "unknown" +async def test_update_entity_reports_versions(hass): ... # hello 0.0.9 → state "on", installed 0.0.9, latest 0.1.0, release_url …/tag/v0.1.0 +async def test_update_entity_off_when_versions_match(hass): ... +async def test_newer_firmware_is_offered_as_update(hass): ... # hello 0.2.0 → "on" +async def test_install_calls_device_and_completes_on_hello(hass): ... + # auto_update off; update.install → call data {"url": ".../firmware/0.1.0/ha-controller.ota.bin", "md5_url": "....ota.bin.md5"} + # in_progress True until hello version 0.1.0 → state "off", in_progress False +async def test_install_times_out(hass, freezer): ... # +301 s → HomeAssistantError, in_progress False +async def test_install_when_offline_raises(hass): ... +async def test_install_while_in_progress_raises(hass): ... +async def test_auto_update_installs_at_most_once_per_hour(hass, freezer): ... # hello 0.0.9 ×2 → 1 call; +3601 s → 2 calls +async def test_auto_update_disabled_by_option(hass): ... +async def test_auto_update_skipped_for_dev_versions(hass): ... # controller integration version "0.2.0.dev0" → no call +async def test_options_flow_toggles_auto_update(hass): ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/integration/test_update.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `firmware.py`, the controller additions, `update.py` and the options flow.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest -v && ruff check .` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller tests/integration/test_update.py +git commit -m "feat(integration): keep screen firmware on the integration version" +``` + +--- + +### Task 3: Release scripts and the web installer page + +**Files:** +- Create: + - `scripts/collect_firmware.py`, `scripts/package_integration.py`, `scripts/build_pages.py` + - `esphome/web/index.html` + - `tests/scripts/test_release_scripts.py` + +**Interfaces:** +- Consumes: the plan 3 bundle `custom_components/ha_controller/frontend/ha-controller-panel.js`; the ESPHome build tree (`esphome/.esphome/build/**/firmware.factory.bin`, `firmware.ota.bin`). +- Produces (each has an `argparse` CLI with the same parameters): + - **`collect(build_dir: Path, version: str, out_dir: Path) -> list[Path]`.** Requires exactly one `*.factory.bin` and one `*.ota.bin` under `build_dir`, otherwise it raises `ValueError`. It writes `ha-controller-.factory.bin`, `ha-controller-.ota.bin` and `ha-controller-.ota.bin.md5`. + - **`package(root: Path, out_file: Path) -> Path`.** Zips the contents of `custom_components/ha_controller/` at the zip root, excluding `__pycache__/`, `*.pyc` and `.gitkeep`. Raises `FileNotFoundError("Build the panel first: npm --prefix frontend run build")` when the bundle is missing. + - **`build_site(web_dir: Path, releases_dir: Path, latest: str, out_dir: Path) -> None`.** `releases_dir//` holds each release's assets. It writes: + - `index.html`, with every `{{VERSION}}` replaced by `latest`; + - `.nojekyll`; + - `firmware/ha-controller.factory.bin`, copied from `latest`; + - `firmware//ha-controller.ota.bin` and `.md5` for **every** version; + - `firmware/manifest.json`: + +```json +{"name": "HA Controller", "version": "", "home_assistant_domain": "esphome", "new_install_prompt_erase": true, + "builds": [{"chipFamily": "ESP32-S3", + "parts": [{"path": "ha-controller.factory.bin", "offset": 0}], + "ota": {"path": "/ha-controller.ota.bin", "md5": "", + "release_url": "https://github.com/pyxel-dev/HA-controller/releases/tag/v"}}]} +``` + + - **`esphome/web/index.html`:** a self-contained English page with inline CSS following `prefers-color-scheme`, titled "HA Controller — Web installer". It contains: + - the subtitle "Firmware {{VERSION}}" and a release-notes link `…/releases/tag/v{{VERSION}}`; + - ``; + - `` with slots `unsupported` ("Use Chrome or Edge on a desktop computer.") and `not-allowed` ("Open this page over HTTPS."); + - five steps: + 1. connect the screen with USB-C; + 2. click Install; + 3. set up Wi-Fi when asked, or join the "HA Controller" access point; + 4. add the screen in Home Assistant (ESPHome); + 5. install the HA Controller integration **{{VERSION}}** from HACS; + - the tip "If the board is not detected, hold BOOT while plugging it in." + +- [ ] **Step 1: Write the failing tests** + +```python +def test_collect_writes_versioned_files_and_md5(tmp_path): ... # .md5 == hashlib.md5(ota).hexdigest(), 32 chars, no newline +def test_collect_requires_exactly_one_of_each(tmp_path): ... # none → ValueError; two factory bins → ValueError +def test_package_zips_integration_with_panel(tmp_path): ... # names include "manifest.json", "frontend/ha-controller-panel.js"; no __pycache__ +def test_package_requires_built_panel(tmp_path): ... +def test_build_site_manifest(tmp_path): ... # exact dict above for latest 0.2.0 +def test_build_site_keeps_every_release(tmp_path): ... # releases 0.1.0 + 0.2.0 → both firmware//ha-controller.ota.bin(.md5) +def test_build_site_renders_version(tmp_path): ... # index.html contains "Firmware 0.2.0", no "{{VERSION}}"; .nojekyll exists +def test_build_site_requires_latest_assets(tmp_path): ... +def test_web_page_template(): ... # real esphome/web/index.html: ≥ 2 "{{VERSION}}" and "esp-web-tools@10.5.2" +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest tests/scripts/test_release_scripts.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the three scripts and `index.html`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest tests/scripts -v` +Expected: PASS. + +- [ ] **Step 5: Preview locally.** + 1. Build a fake site from the scripts' test data: `python scripts/build_pages.py --web esphome/web --releases --latest 0.1.0 --out site`. + 2. Serve it with `python3 -m http.server -d site`. + 3. Open it in Chrome and confirm the page shows "Firmware 0.1.0" and an Install button. + +- [ ] **Step 6: Commit** + +```bash +git add scripts esphome/web tests/scripts +git commit -m "build: add release packaging scripts and web installer page" +``` + +--- + +### Task 4: Release workflow, HACS packaging, user docs and release skill + +**Files:** +- Create: + - `.github/workflows/release.yml` + - `docs/getting-started.md`, `docs/updates.md`, `docs/releasing.md` + - `.claude/skills/release/SKILL.md` +- Modify: `hacs.json`, `README.md`, `docs/README.md`, `CLAUDE.md` + +**Interfaces:** +- Consumes: Tasks 1–3, `esphome/requirements.txt` and the `npm` scripts. +- Produces: + - **`hacs.json`:** `{"name": "HA Controller", "homeassistant": "2026.10.0", "zip_release": true, "filename": "ha_controller.zip"}`. + - **`release.yml`.** Triggers: `push` on tags `v*` and `workflow_dispatch` (dry run). Permissions: `contents: write`, `pages: write`, `id-token: write`. Concurrency group `release`. + - **Job `build`** (`ubuntu-latest`). Steps, in order: + 1. Checkout, then setup-python 3.13 and setup-node 24 with the npm cache. + 2. Read the version from `manifest.json` into an output. + 3. `python scripts/versioning.py check`, plus `--tag "$GITHUB_REF_NAME"` on tag runs. + 4. `npm --prefix frontend ci` and `npm --prefix frontend run build`. + 5. `python scripts/package_integration.py --out dist/ha_controller.zip`. + 6. `pip install -r esphome/requirements.txt` and `esphome compile esphome/ha-controller.yaml`. + 7. `python scripts/collect_firmware.py --build-dir esphome/.esphome/build --version --out dist`. + 8. `actions/upload-artifact@v4` (`dist`). + - **Job `release`** (needs `build`, tag runs only): download the artifact, then `gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --generate-notes --verify-tag` with `GH_TOKEN`. + - **Job `pages`** (needs `build` and `release`, tag runs only, environment `github-pages`): + 1. Checkout. + 2. For every tag from `gh release list --limit 200 --json tagName -q '.[].tagName'`, run `gh release download "$tag" -p 'ha-controller-*' -D "releases/${tag#v}"`. + 3. `python scripts/build_pages.py --web esphome/web --releases releases --latest --out site`. + 4. `actions/configure-pages@v5`, `actions/upload-pages-artifact@v3` (`site`) and `actions/deploy-pages@v4`. + +- [ ] **Step 1: Write the workflow and update `hacs.json`.** + +- [ ] **Step 2: Dry run.** Push the branch, run "Release" with `workflow_dispatch`, and download the `dist` artifact. Expected: + - the `build` job is green and `release`/`pages` are skipped; + - the artifact holds `ha_controller.zip` (with `frontend/ha-controller-panel.js` inside) plus the three `ha-controller-0.1.0.*` files. + +- [ ] **Step 3: Write the user docs.** + - **`docs/getting-started.md`:** + 1. Hardware and enclosure: link `../3D_models/`. + 2. Flash from `https://pyxel-dev.github.io/HA-controller/` with Chrome or Edge. + 3. Wi-Fi via Improv or the `HA Controller` access point and captive portal. + 4. Adopt the discovered ESPHome device in Home Assistant. + 5. In HACS, add the custom repository `https://github.com/pyxel-dev/HA-controller` (type Integration), install the **same version** as shown on the installer page, and restart. + 6. Settings › Devices & services › Add integration › HA Controller, then pick the screen. + 7. Open the HA Controller panel. + + Troubleshooting: + - **The screen stays on "Waiting for Home Assistant":** check that the ESPHome device and the HA Controller entry exist. If the hello events never show up under Developer tools › Events, enable "Allow the device to perform Home Assistant actions" in the ESPHome device options. + - **"Firmware update required":** see `updates.md`. + - **`docs/updates.md`:** + - The one-version rule. + - Integration updates come through HACS. To install them automatically, create an automation that calls `update.install` on the HACS update entity. + - Firmware follows the integration automatically (the `auto_update` option, default on), or by hand from the "HA Controller firmware" update entity. + - Rolling back the integration makes the firmware follow. + - A screen without internet access must be re-flashed over USB from the installer. + - **`docs/releasing.md`:** + - One-time setup: Settings › Pages › Source "GitHub Actions"; repository description and topics for HACS. + - Steps: + 1. `python scripts/versioning.py bump X.Y.Z` + 2. commit `chore: release X.Y.Z` + 3. `git tag vX.Y.Z && git push origin main vX.Y.Z` + 4. watch the "Release" workflow + 5. check the Pages page shows X.Y.Z, and that HACS offers X.Y.Z + - Dry runs use `workflow_dispatch`. + - **`README.md`:** an "Install" section with the installer URL and the HACS custom repository, and links to `docs/getting-started.md` and `docs/README.md`. + - **`docs/README.md`:** link the three new docs. + +- [ ] **Step 4: Write `.claude/skills/release/SKILL.md`** and list it in `CLAUDE.md`. + - Frontmatter `name: release`. + - `description:` "Use when cutting a release or changing the release pipeline: versions, release workflow, GitHub Pages installer, HACS packaging, firmware OTA URLs." + - Body: + - Never edit versions by hand. + - The release steps from `docs/releasing.md`. + - What each job produces. + - OTA URLs must stay stable (`firmware//ha-controller.ota.bin`), because integrations already installed depend on them. + - Check `pytest tests/scripts` after any script change. + +- [ ] **Step 5: Run every suite** + +Run: `pytest && ruff check . && python scripts/versioning.py check && npm --prefix frontend test` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add .github/workflows/release.yml hacs.json README.md docs .claude CLAUDE.md +git commit -m "ci: release integration, firmware and web installer from tags" +``` + +- [ ] **Step 7: First release (owner).** Follow `docs/releasing.md` for `0.1.0`. Expected: + - the GitHub release has 4 assets; + - `https://pyxel-dev.github.io/HA-controller/` shows "Firmware 0.1.0" and flashes a blank board; + - HACS installs 0.1.0; + - the "HA Controller firmware" entity reports `0.1.0` / `0.1.0`. diff --git a/docs/superpowers/specs/2026-11-16-ha-controller-design.md b/docs/superpowers/specs/2026-11-16-ha-controller-design.md new file mode 100644 index 0000000..3c116d0 --- /dev/null +++ b/docs/superpowers/specs/2026-11-16-ha-controller-design.md @@ -0,0 +1,467 @@ +# HA Controller — Design Spec + +| | | +|---|---| +| Date | 2026-11-16 | +| Status | Approved 2026-11-16, executed with subagent-driven development | +| Repository | https://github.com/pyxel-dev/HA-controller | +| Plans | `docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md` → `…-5-release.md` (execute in order 1, 2, 3, 4, 5) | + +## 1. Goal + +Turn the Waveshare ESP32-S3-Touch-AMOLED-1.75 into a Home Assistant remote. In a Home Assistant sidebar panel, the user draws a map of **blocks** on a grid. The screen shows one block at a time. To move to a neighbouring block, the user swipes in from the screen edge on that side. A block controls one entity with a knob (light brightness or thermostat temperature), or it shows custom content: text, emoji, entity states, the screen's battery level and a screen brightness control. + +## 2. Requirements + +| ID | Requirement (from the product owner) | +|---|---| +| R1 | Documentation lives in `/docs`. Everything in the repository is written in English. | +| R2 | `/esphome` contains everything needed to build and flash the firmware. Flashing works from an HTML page served by GitHub Pages. | +| R3 | The web page states the firmware version it installs. The firmware version always equals the integration version. | +| R4 | Home Assistant updates the screen firmware automatically. | +| R5 | Claude Code skills and agents guide future development. | +| R6 | The Home Assistant view mirrors on-screen navigation: blocks on a grid, a start block, and "+" placeholders around existing blocks ([reference screenshot](assets/editor-reference.png)). | +| R7 | Navigation: put a finger on a screen edge and slide towards the centre to move to the neighbour on that side. For example, right edge + slide left goes to the right neighbour. Transitions are smooth. | +| R8 | Entity blocks: a light with a brightness knob, a thermostat with a temperature knob. | +| R9 | Custom blocks: text, emoji, textual entity states, and screen info (battery %, screen brightness control). | +| R10 | Font size and background are configurable per block from the integration. | +| R11 | The screen sleeps after a delay set in the integration (default 20 s). A touch wakes it. | + +## 3. Architecture + +```text + Home Assistant Screen (ESPHome firmware) +┌──────────────────────────────────────────┐ ┌──────────────────────────────────────┐ +│ custom integration `ha_controller` │ ESPHome │ external component `ha_controller` │ +│ config entry per screen │ actions │ layout + state parsers (pure C++) │ +│ layout store + validation │ ─────────▶ │ pager: edge swipes, slide animation │ +│ compiler → device payload (+ revision) │ set_layout │ block views: knobs, custom items │ +│ sync engine (hello, states, controls) │ set_states │ message screen │ +│ firmware update entity + auto-update │ install_fw │ │ +│ websocket API + sidebar panel (Lit) │ ◀───────── │ board package: CO5300 display, │ +└──────────────────────────────────────────┘ events │ CST9217 touch, AXP2101 battery, │ + ▲ HACS (release zip) hello / │ screen brightness number │ + │ control └──────────────────────────────────────┘ + GitHub Releases ──────▶ GitHub Pages: web installer + firmware// ▲ OTA download / USB flash +``` + +- The screen is an ordinary ESPHome device, adopted by Home Assistant's ESPHome integration. The custom integration opens no connection of its own. It calls the device's user-defined ESPHome actions, which Home Assistant exposes as services `esphome._` (node name with `-` replaced by `_`). It also listens to the `esphome.ha_controller_*` events fired by the device. +- Home Assistant's ESPHome integration adds `device_id` to every device event. It requires the "Allow the device to perform Home Assistant actions" option for actions, but not for events (`homeassistant/components/esphome/manager.py`). The design uses events only, so that option can stay off. +- The integration is the single source of truth for both the layout and the version. The firmware is a generic renderer. + +### Repository layout + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/superpowers/` holds this spec and the plans. | +| `protocol/fixtures/` | Shared test fixtures: the cross-language contract | +| `custom_components/ha_controller/` | Home Assistant integration (Python) | +| `custom_components/ha_controller/emoji.json` | Canonical list of supported emoji, read by the firmware build, the panel and the integration | +| `custom_components/ha_controller/frontend/` | Built panel bundle (generated, git-ignored) | +| `frontend/` | Panel source (TypeScript, Lit, Vite) | +| `esphome/` | Firmware: device config, packages, simulator config, external components, host tests, web installer page | +| `scripts/` | Versioning, packaging, GitHub Pages site builder | +| `tests/` | Python tests (protocol fixtures, docs, integration, scripts) | +| `.claude/` | Claude Code skills and agents | +| `.github/workflows/` | CI, firmware CI, release | +| `3D_models/`, `files/` | Existing enclosure models (unchanged) | + +## 4. Hardware & firmware platform + +| Item | Value | +|---|---| +| Board | Waveshare ESP32-S3-Touch-AMOLED-1.75: ESP32-S3R8 (8 MB octal PSRAM), 16 MB flash, USB-C (native USB) | +| Display | 1.75" round AMOLED, 466×466, CO5300 over QSPI. CS GPIO12, SCLK GPIO38, D0–D3 GPIO4/5/6/7, RESET GPIO39. TE (GPIO13) is not used. | +| Touch | CST9217 (I²C 0x5A). INT GPIO11, RESET GPIO40. Transform: mirror_x + mirror_y. | +| I²C bus | SDA GPIO15, SCL GPIO14, 400 kHz. Shared by AXP2101 0x34, TCA9554 0x20, QMI8658 0x6B, PCF85063 0x51, ES8311 0x18 and ES7210 0x40. | +| PMU | AXP2101 at 0x34: battery %, voltage, charging (registers in §4.1) | +| ESPHome | 2026.10.2, pinned in `esphome/requirements.txt`. `min_version: 2026.10.0`, framework esp-idf. | +| Display driver | `display: platform: mipi_spi`, `model: CO5300`, `bus_mode: quad`. Brightness through `set_brightness(uint8_t)`. | +| Touch driver | External component `cst9217` from https://github.com/shelson/esphome-cst9217, pinned to a commit SHA | +| UI | ESPHome `lvgl:`, which bundles LVGL 9.5. The `ha_controller` external component drives it at runtime through the LVGL C API. | +| JSON | ArduinoJson 7, bundled by ESPHome's `json:` component | +| Native API | Max message size 32 768 bytes. Plaintext (no encryption key in a prebuilt binary). | + +**4.1 AXP2101 registers** (from XPowersLib): +- Enable the ADC: set bit 0 of 0x30. +- Enable battery detection: set bit 0 of 0x68. +- Battery present: bit 3 of 0x00. +- Charging: `(reg 0x01 >> 5) == 0x01`. +- Battery %: register 0xA4 (0–100). +- Battery mV: `((reg 0x34 & 0x1F) << 8) | reg 0x35`. + +The display and touch rails are powered by default, so the firmware does not touch the LDO registers. + +**4.2 Fonts** compiled into the firmware (sizes in px): + +| Size key | Text font (Inter 600, glyphset `GF_Latin_Core`) | Value font (Inter 600, glyphs `" 0123456789.,-+%°CFOfn—"`) | Emoji font (Noto Emoji, glyphs from `emoji.json`) | +|---|---|---|---| +| `s` | 20 | 40 | 32 | +| `m` | 28 | 56 | 48 | +| `l` | 40 | 72 | 64 | +| `xl` | 56 | 96 | 88 | + +A glyph missing from a font is not drawn. v1 targets Latin scripts. + +## 5. On-screen UX + +**5.1 Grid.** Blocks sit on integer cells `(x, y)`. `x` grows to the right and `y` grows **downwards**, exactly as drawn in the panel. +- The screen shows the start block after a layout is applied and after a reboot. +- When a new layout arrives, the screen stays on the current block if a block with the same id still exists. Otherwise it goes to the start block. + +**5.2 Edge swipe.** The touch point is classified on the round display, with `size = 466` and centre `c = (size/2, size/2)`: +- `r = distance(point, c)`. If `r < size/2 − 36`, there is no edge and the touch goes to the widgets. +- Otherwise the dominant axis of `(dx, dy) = point − c` picks the edge. If `|dx| ≥ |dy|`, it is RIGHT when `dx ≥ 0` and LEFT otherwise. If not, it is BOTTOM when `dy > 0` and TOP otherwise. +- Edge → target cell: RIGHT `(x+1, y)`, LEFT `(x−1, y)`, TOP `(x, y−1)`, BOTTOM `(x, y+1)`. +- Progress is the inward finger travel along the edge's axis, clamped to `[0, size]`: + - RIGHT: `start_x − x` + - LEFT: `x − start_x` + - TOP: `y − start_y` + - BOTTOM: `start_y − y` + + Outward and perpendicular motion is ignored. +- With a target, the current page and the target page follow the finger (offset = progress). Without a target, the current page rubber-bands: offset = `min(progress × 0.3, 48)`. +- On release, the navigation commits if a target exists and either `progress ≥ 0.25 × size`, or velocity ≥ 0.6 px/ms with `progress ≥ 24`. Velocity is measured over the last 100 ms. Otherwise both pages slide back. +- Edge touches are captured by a transparent full-screen object on LVGL's top layer. Its hit test only accepts points in the edge ring, so every other touch reaches the page widgets. + +**5.3 Transition.** +- After release, the pages animate to their final position with an ease-out curve. The duration is `clamp(220 × remaining_px / size, 80, 220)` ms. +- Only the current page and the target page are visible; every other page is hidden. + +**5.4 Edge hints.** A short arc (20°, 6 px, white at 60 % opacity) marks each edge of the current block that has a neighbour. + +**5.5 Common page rendering.** +- Each page is a full-screen object filled with the block background. +- Text is black (`#000000`) if the background's WCAG relative luminance is `> 0.30`, otherwise white (`#FFFFFF`). +- Interactive controls stay inside the circle of radius `233 − 36 − 12 = 185` px, so they never overlap the edge ring. + +**5.6 Light block.** The name sits at the top, in the text font of the block size. +- **Dimmable light:** a 270° arc knob (diameter 370 px, width 28 px, gap at the bottom) with range 0–100. + - The centre shows `NN%` or `Off` in the value font. + - Tapping the centre toggles the light. + - Releasing the knob sends the new brightness; 0 turns the light off. +- **On/off-only light:** a 220 px round toggle button in the centre, showing `On`/`Off`. +- **Unavailable entity:** the centre shows `—` with a small `Unavailable` label below, and the controls are disabled. + +**5.7 Climate block.** +- The name sits at the top, with an arc knob over `[min, max]` in steps of `step`. +- The centre shows the target, e.g. `21.5°`: one decimal when `step < 1`, none otherwise. +- A small label below shows `Now ` and the action, e.g. `Heating`. +- Releasing the knob sends the new target. +- If the entity is unavailable or has no single target temperature, the centre shows `—` and the knob is disabled. + +**5.8 Custom block.** Items are stacked vertically and centred with an 8 px gap. Each item has its own font size, defaulting to the block's. +- `text`: a label. +- `emoji`: a label in the emoji font. +- `entity`: a label showing the state text pushed by Home Assistant. +- `battery`: a row `🔋 87 %` (`⚡` while charging), fed by the local battery sensor. +- `brightness`: a row with `☀` and a 220 px slider (5–100 %). It drives the local screen brightness number, applied at most every 100 ms while dragging and always on release. + +A custom block with no items shows its name centred. + +**5.9 Messages.** A full-screen message (title in `m`, detail in `s`) replaces the pages when: + +| Condition | Title | Detail | +|---|---|---| +| No layout received since boot | `Waiting for Home Assistant` | ` · v` | +| Layout protocol not supported | `Firmware update required` | `Open Home Assistant to update` | +| Layout invalid | `Invalid layout` | parse error code | +| Layout has no blocks | `No blocks yet` | `Add blocks in Home Assistant › HA Controller` | +| OTA running | `Updating firmware…` | `Do not unplug the screen` | +| OTA failed (shown 5 s) | `Update failed` | `Check the screen's internet access` | + +**5.10 Interaction hold.** After a local interaction with a block (knob or toggle), incoming state updates for that block are held for 1500 ms; then the latest one is applied. This stops the knob from jumping back while Home Assistant catches up. + +**5.11 Sleep.** +- **Delay:** a per-screen setting (`sleep` in the payload). `0` means never; otherwise 5–3600 s. The default is 20 s, which also applies before the first layout arrives. +- **Going to sleep:** when LVGL has seen no touch activity for the delay, the display brightness goes to 0 and LVGL rendering is paused. Wi-Fi and the Home Assistant connection stay up. Incoming layouts and states are applied without waking the screen. +- **Waking:** releasing a touch wakes the screen. The waking touch never reaches a widget. Brightness returns to the `Screen brightness` value and the inactivity timer restarts. +- **Exceptions:** + - Firmware-update messages (§5.9) wake the screen. + - While the screen sleeps, a `Screen brightness` change is stored and applied on wake. +- **No deep sleep:** it would drop the Home Assistant connection. + +## 6. Layout model (integration and panel) + +The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: + +```json +{ "version": 1, "start": "b1", "settings": { "sleep_timeout": 20 }, "blocks": [ + { "id": "b1", "x": 0, "y": 0, "name": "Kitchen", "background": "#5B9E4D", "font_size": "m", + "type": "entity", "entity_id": "light.kitchen" }, + { "id": "b2", "x": 0, "y": -1, "name": "Lights", "background": "#C94F3D", "font_size": "m", + "type": "entity", "entity_id": "light.living_room" }, + { "id": "b3", "x": -1, "y": 0, "name": "Hello World", "background": "#4F86DD", "font_size": "l", + "type": "custom", "items": [ + { "id": "i1", "kind": "text", "text": "Hello World", "font_size": null }, + { "id": "i2", "kind": "emoji", "emoji": "👋", "font_size": "xl" }, + { "id": "i3", "kind": "entity", "entity_id": "sensor.outdoor_temperature", "attribute": null, "font_size": "s" }, + { "id": "i4", "kind": "battery", "font_size": "s" }, + { "id": "i5", "kind": "brightness", "font_size": null } ] }, + { "id": "b4", "x": -1, "y": 1, "name": "Bedroom", "background": "#7B2FA0", "font_size": "m", + "type": "entity", "entity_id": "climate.bedroom" } ] } +``` + +Unknown keys are ignored, so the panel can keep `entity_id` and `items` when the user switches a block's type. + +Validation returns a list of `{code, ref}`, where `ref` is the offending block or item id, or `null`. An empty list means the layout is valid. It runs in three phases: +1. **Structure.** It stops at the first error. +2. **Per-field checks.** All errors are collected. +3. **Connectivity.** Only runs if phase 2 found nothing. + +| Code | Rule | +|---|---| +| `invalid_structure` | `version` must be `1`, `settings` an object, `blocks` a list, and blocks and items objects with the expected JSON types | +| `too_many_blocks` | At most 32 blocks | +| `invalid_sleep_timeout` | `settings.sleep_timeout` is an integer (not a boolean): `0` (never) or 5–3600 seconds | +| `invalid_id` | Ids match `^[a-z][a-z0-9]{0,7}$` | +| `duplicate_id` | Ids are unique across blocks **and** items | +| `coordinate_out_of_range` | `-32 ≤ x, y ≤ 32` (integers) | +| `duplicate_position` | One block per cell (ref = the later block) | +| `invalid_start` | `start` is `null` if and only if there are no blocks; otherwise it is the id of an existing block | +| `disconnected` | Every block is reachable from `start` through 4-neighbour cells (one error per unreachable block, in layout order) | +| `invalid_name` | 1–32 characters after trimming | +| `invalid_background` | `^#[0-9A-Fa-f]{6}$` | +| `invalid_font_size` | Block: `s`/`m`/`l`/`xl`. Item: the same, or `null` (inherit). | +| `invalid_type` | `entity` or `custom` | +| `invalid_entity` | Entity block: an `entity_id` of domain `light` or `climate`. Entity item: an id matching `^[a-z0-9_]+\.[a-z0-9_]+$`, and `attribute` either `null` or 1–64 characters. | +| `too_many_items` | At most 6 items per custom block | +| `invalid_item` | `kind` is one of `text`, `emoji`, `entity`, `battery`, `brightness` | +| `invalid_text` | Text item: 1–64 characters | +| `unsupported_emoji` | Emoji item: after removing U+FE0F, the value is an entry of `emoji.json` | +| `payload_too_large` | The compiled payload (§7.3) is larger than 24 576 UTF-8 bytes. Checked by the integration only. | + +Entities that do not exist (yet) are valid; the screen shows them as unavailable. + +## 7. Device protocol v1 (normative) + +`PROTOCOL_VERSION = 1`. `docs/protocol.md` is the living copy of this section. `protocol/fixtures/` pins it with examples, used by the tests of all three implementations. + +**7.1 Actions (Home Assistant → screen).** Services `esphome._`: + +| Action | Variables | Effect | +|---|---|---| +| `set_layout` | `layout: string` (payload JSON, §7.3) | Parse it. On success, rebuild the pages and adopt `rev`. Then fire a hello with reason `applied`; this also happens after a failure, with the revision unchanged. | +| `set_states` | `states: string` (JSON array, §7.4) | Apply each update to the block or item with that id. Unknown ids are ignored. | +| `install_firmware` | `url: string`, `md5_url: string` | Show `Updating firmware…`, render it immediately, then run `ota.http_request.flash`. On failure, show `Update failed` for 5 s. | + +**7.2 Events (screen → Home Assistant).** Data values are strings, and Home Assistant adds `device_id`. + +| Event | Data | When | +|---|---|---| +| `esphome.ha_controller_hello` | `node` (ESPHome node name), `version` (firmware version), `protocol` (`"1"`), `revision` (applied `rev` or `none`), `reason` (`connected` / `heartbeat` / `applied`) | 5 s after an API client connects, every 60 s while connected, and after each `set_layout` | +| `esphome.ha_controller_control` | `block` (block id), `item` (item id or empty), `op` (`toggle` / `set`), `value` (decimal, `%.2f`) | Centre tap on a light (`toggle`), knob release (`set`) | + +**7.3 Layout payload.** The integration compiles it from the stored layout: +- **Top level:** `v` (1), `rev`, `start` (id or `null`), `sleep` (integer seconds, `0` = never), `blocks`. +- **Block:** `id`, `x`, `y`, `name`, `bg` (6 uppercase hex digits, no `#`), `font`, `widget`. + - `widget` is `light` or `climate` (taken from the entity domain), or `custom`. + - Custom blocks also carry `items` (possibly empty). Entity blocks carry no `items`. +- **Item:** `id`, `kind`, `font` (the item's size, or the block's when the item's is `null`). + - `text` items carry `text` (the text). + - `emoji` items carry `text` (the emoji without U+FE0F). + - Other kinds carry no `text`. +- No entity ids are sent to the screen. +- `rev` is the first 8 hex chars of SHA-256 over the UTF-8 bytes of `json.dumps(payload_without_rev, sort_keys=True, separators=(",", ":"), ensure_ascii=False)`. + - Golden values: empty payload (`sleep` 20) → `c4aad3fa`; `payloads/valid/reference.json` → `90538742`; `payloads/valid/emoji-variation.json` → `5387d4ea`. +- **Transport encoding:** compact JSON (`separators=(",", ":")`, `ensure_ascii=False`), at most 24 576 bytes. + +Device parse errors: +- `bad_json`: not JSON, or not an object. +- `unsupported_version`: `v != 1`. +- `invalid_payload`: a missing or mistyped field, an unknown `widget`, `kind` or `font`, or a `sleep` outside 0–3600. + +**7.4 State updates.** A JSON array. Each element has `id` (block or item id) and `available` (bool, default `true`): + +| Target | Fields | +|---|---| +| Light block | `on` (bool), `brightness` (0–100 integer; `null` for on/off-only lights; `0` when a dimmable light is off) | +| Climate block | `target` (number or `null`), `min`, `max`, `step` (numbers), `unit` (`°C`/`°F`), `current` (display string), `action` (display string, e.g. `Heating`) | +| Entity item | `text` (display string) | + +An unavailable or missing entity sends `{"id": …, "available": false}`. Entity items send `{"id": …, "text": "—"}` instead. Updates are sent in layout order, in chunks of at most 8 192 bytes. + +**7.5 Handshake and resync** (integration side): +- **On a hello from the screen's `device_id`:** record the node, version, protocol, revision and time. Then: + - If `protocol ≠ 1`, push nothing (auto-update may run, §11). + - Else, if `revision ≠` the current revision, push the layout and then all states. Push immediately when `reason = connected`. Otherwise push at most once per 300 s for the same revision. + - Else, if `reason = connected`, push all states. +- **Entity state changes:** coalesced for 200 ms, then pushed for the changed entities. This only happens while the screen is online (a hello within the last 150 s) and on protocol 1. +- **Saving a layout:** pushes it immediately if the screen is online. + +**7.6 Control mapping** (integration side). The entity always comes from the layout, never from the event. + +| Block | op | Service call | +|---|---|---| +| Light | `toggle` | `light.toggle` `{entity_id}` | +| Light | `set`, value ≤ 0 | `light.turn_off` `{entity_id}` | +| Light | `set`, value > 0 | `light.turn_on` `{entity_id, brightness_pct: round(clamp(value, 1, 100))}` | +| Climate | `set` | `climate.set_temperature` `{entity_id, temperature: clamp(value, min_temp, max_temp)}` (bounds from the current state, defaults 7/35) | + +Anything else is ignored: an unknown block, a custom block, an unparsable value. Service errors are logged, never raised. + +**7.7 State builders** (integration side): +- **Light:** + - Unavailable if the entity is missing, `unavailable` or `unknown`. + - Dimmable if `supported_color_modes` contains a mode other than `onoff`. + - Brightness: `round((attribute brightness or 255) × 100 / 255)` when on, `0` when off, `null` when not dimmable. +- **Climate:** + - `unit` is Home Assistant's temperature unit. + - `step` is `target_temp_step`, or else `0.5` for °C and `1` for °F. + - `min`/`max` come from `min_temp`/`max_temp` (defaults 7/35). + - `current` is `" "`, or `—`. + - `action` is `hvac_action`, or else the state, with `_` replaced by a space and the first letter capitalised. +- **Entity item:** + - `—` if the entity is missing, `unavailable` or `unknown`, or if the attribute is missing. + - A numeric value is rounded to the entity registry's `sensor.display_precision`, or else `suggested_display_precision`, or else left unchanged. + - The result is `" "` when a unit exists, truncated to 64 characters. + +## 8. Home Assistant integration + +- **Config flow:** one entry per screen. + - Step `user` shows a device selector filtered to `integration: esphome, manufacturer: pyxel-dev, model: ha-controller`. Home Assistant derives the manufacturer and model from the firmware's `project.name: pyxel-dev.ha-controller`. + - The manufacturer and model are checked server-side (error `not_ha_controller`). + - `unique_id` = device id. Title = device name. Data: `{"device_id": …}`. +- **Options flow** (plan 5): `auto_update` (bool, default `true`). +- **Runtime:** `entry.runtime_data` is a `ScreenController`. It owns the layout store, the compiled payload and revision, the device status, the event listeners (filtered by `device_id`), entity tracking, and firmware installs. +- **Websocket API** (admin only): + - `ha_controller/screens` → `{"screens": [{entry_id, title, device_id, online, firmware_version, integration_version, protocol_ok, revision, device_revision}]}` + - `ha_controller/layout/get` `{entry_id}` → `{"layout": …}` + - `ha_controller/layout/save` `{entry_id, layout}` → `{"revision": …, "pushed": bool}`. Errors: `not_found`, and `invalid_layout` with message `code@ref, …`. +- **Panel:** + - Sidebar entry "HA Controller", icon `mdi:remote`, URL `/ha-controller`, admins only. + - The module is served from `/ha_controller_static/ha-controller-panel.js?v=`. + - Registered with the first loaded entry and removed with the last. +- **Manifest:** `dependencies: ["frontend", "http", "panel_custom", "websocket_api"]`, `after_dependencies: ["esphome"]`, `integration_type: device`, `iot_class: local_push`. Brand images live in `custom_components/ha_controller/brand/`. +- **Minimum Home Assistant:** 2026.10.0 (Python 3.14). + +## 9. Panel UX + +- **Header:** + - A screen selector, when there are several screens. + - A status line: `Online · firmware 0.1.0 · in sync`, `Offline`, or `Firmware 0.0.9 — update available`. + - `Revert` and `Save` buttons, disabled when nothing changed or the layout has errors. +- **Map** (see the [reference screenshot](assets/editor-reference.png)): + - A CSS grid of 96 px square cells with 12 px gaps and a 16 px radius, covering blocks and placeholders. Columns follow `x` ascending, rows follow `y` ascending. + - Blocks are filled with their background and show their name in the contrast text colour. + - The start block has a 3 px outline and a `start` badge. + - Placeholders (2 px dashed border, `+`) appear on every empty 4-neighbour of a block. If there is no block, there is only one, at `(0, 0)`. There are none at 32 blocks, and none for cells out of range. + - The selected block has a ring in the theme's primary colour. +- **Adding a block:** clicking a placeholder adds a block there and selects it. The first block becomes the start block. Defaults: + - id `b`, name `Block `; + - background from the palette `#C94F3D #4F86DD #5B9E4D #7B2FA0 #E08A2E #2E9E8F #D2477A #5C6BC0`, picked by block count; + - font `m`, type `custom`, no items. +- **Editor** for the selected block: + - Name, background (colour input + palette swatches), font size (S/M/L/XL), type (Entity/Custom). + - An entity picker limited to `light.*`/`climate.*`. + - For custom blocks, an items list: add Text, Emoji, Entity state, Battery or Screen brightness; edit, move up/down, remove; per-item font size with "Inherit". The emoji picker shows only `emoji.json`. + - `Set as start block`. + - `Delete block`, disabled with the reason when it is the start block of a multi-block layout or when deleting it would disconnect other blocks. + - A 220 px round preview showing the background, the contrast text and the content. +- **Validation** runs locally with the same rules and codes as the integration. Errors are listed with human messages and highlighted on the map. +- **Screen settings:** a "Screen" section under the map with a "Sleep after (seconds)" input. Default 20; `0` keeps the screen on. Validated with `invalid_sleep_timeout`. +- **Refresh and save:** the screen list refreshes every 10 s. Saving reports `Saved — sent to the screen.` or `Saved — the screen is offline and will update when it reconnects.` + +## 10. Versioning & distribution + +- **One version:** a single SemVer version `X.Y.Z` for the whole repository, stored in three places: + - `custom_components/ha_controller/manifest.json` (`version`) + - `esphome/version.yaml` (`substitutions.project_version`) + - `frontend/package.json` (`version`) + + `scripts/versioning.py check [--tag vX.Y.Z]` fails CI on any mismatch, and `scripts/versioning.py bump X.Y.Z` rewrites all three. The initial version is `0.1.0`. +- **Release:** pushing tag `vX.Y.Z` cuts a release. The release workflow: + 1. verifies the versions; + 2. builds the panel; + 3. packages `ha_controller.zip` (the contents of `custom_components/ha_controller/`, with the built panel); + 4. compiles the firmware; + 5. publishes a GitHub release with `ha_controller.zip`, `ha-controller-X.Y.Z.factory.bin`, `ha-controller-X.Y.Z.ota.bin` and `ha-controller-X.Y.Z.ota.bin.md5`. +- **GitHub Pages:** the release workflow then rebuilds `https://pyxel-dev.github.io/HA-controller/` from the release assets: + - `index.html` (web installer); + - `firmware/manifest.json` (ESP Web Tools manifest for the latest version); + - `firmware/ha-controller.factory.bin` (latest); + - `firmware//ha-controller.ota.bin` + `.md5` for every release. +- **Web installer:** an ESP Web Tools 10.5.2 install button. The page prints "Firmware X.Y.Z" (substituted at build time) and links to the release notes. It explains: + - USB-C with Chrome or Edge; + - Wi-Fi setup, through Improv serial or the `HA Controller` access point + captive portal; + - adding the screen in Home Assistant; + - installing the integration with the **same version** through HACS. +- **HACS:** a custom repository. `hacs.json` sets `zip_release: true`, `filename: ha_controller.zip` and `homeassistant: 2026.10.0`. + +## 11. Firmware updates + +- **Update entity:** the integration creates one `update` entity per screen ("HA Controller firmware"), attached to the screen's device. + - `installed_version` is the version from the last hello. + - `latest_version` is the integration version. + - `release_url` is the release page. + - `version_is_newer` returns `latest != installed`. A firmware newer than the integration (after an integration rollback) therefore also shows as an update. +- **Install:** calls `install_firmware` with `https://pyxel-dev.github.io/HA-controller/firmware//ha-controller.ota.bin` and its `.md5`, and sets `in_progress`. It then waits up to 300 s for a hello carrying ``, and raises an error otherwise. +- **Auto-update** (option `auto_update`, default on): the integration installs automatically when all of these hold: + - a hello reports a version different from the integration version; + - the integration version is a release (`^\d+\.\d+\.\d+$`); + - no install is running. + + It makes at most one automatic attempt per screen and version every 3600 s. +- **Network requirement:** OTA requires internet access from the screen to GitHub Pages. Without it, re-flash over USB from the web installer. +- **No ESPHome `update:` entity:** the firmware does not define one of its own. + +## 12. Testing strategy + +- **Shared fixtures** in `protocol/fixtures/`, read by the Python, TypeScript and C++ tests: + - `layouts/valid` + - `layouts/invalid` (expected code + ref) + - `payloads/valid` (stored layout + golden payload) + - `payloads/invalid` (raw text + expected device parse error) + - `states` (Home Assistant states + expected updates) + - `controls` (event + expected service call) + - `colors.json` (background → text colour) +- **Integration:** pytest + `pytest-homeassistant-custom-component`, ruff. hassfest and HACS validation run in CI. +- **Panel:** vitest (model, and components with happy-dom), `tsc --noEmit`, production build. +- **Firmware:** + - Host C++ tests (CMake, doctest, ArduinoJson 7) for the pure modules: layout and state parsing, knob scale, gestures, colours, AXP2101 decoding. + - `esphome compile` of the device and simulator configs. + - A manual hardware checklist in `docs/development.md`. +- **Simulator:** `esphome/simulator.yaml` runs the same UI on a desktop (ESPHome `host` platform + SDL, 466×466) and accepts Home Assistant API connections. + +## 13. Developer guidance (Claude Code) + +- `CLAUDE.md`: purpose; rules (English only, one version, protocol changes go through the protocol skill, TDD); repository map; commands. +- Skills (`.claude/skills/`): `protocol-change`, `add-widget`, `firmware-dev`, `release`. +- Agents (`.claude/agents/`): `protocol-guardian`, `ha-integration-reviewer`, `firmware-reviewer`. + +## 14. Out of scope for v1 + +- PWR button handling. +- Deep sleep. +- IMU, RTC, audio and SD card features. +- Colour emoji. +- Non-Latin scripts. +- Entity widgets other than light and climate, such as switch, cover, fan or media player. Add them with the `add-widget` skill. +- Drag-and-drop to move blocks. +- Several layouts per screen. +- Panel translations. +- OTA without internet access. +- Automatic discovery of new screens. +- API encryption in the prebuilt firmware. + +## 15. Constants + +| Name | Value | +|---|---| +| Screen size | 466 px | +| Edge ring width | 36 px | +| Commit distance / flick | 0.25 × size / 0.6 px/ms with ≥ 24 px | +| Rubber band | × 0.3, max 48 px | +| Settle animation | clamp(220 × remaining / size, 80, 220) ms, ease-out | +| Interaction hold | 1500 ms | +| Max blocks / items / name / text | 32 / 6 / 32 / 64 | +| Coordinate range | −32…32 | +| Max payload / state chunk | 24 576 / 8 192 bytes | +| Hello delay / heartbeat | 5 s / 60 s | +| Online timeout | 150 s | +| Push retry (same revision) | 300 s | +| State coalescing | 200 ms | +| Install timeout | 300 s | +| Auto-update retry | 3600 s | +| Panel status refresh | 10 s | +| Sleep delay | default 20 s; `0` = never; otherwise 5–3600 s | diff --git a/docs/superpowers/specs/assets/editor-reference.png b/docs/superpowers/specs/assets/editor-reference.png new file mode 100644 index 0000000000000000000000000000000000000000..c524cf1c8fea88ad5dc22d04f2aea166ea227c76 GIT binary patch literal 107510 zcmb@u2UL{F7B1RABMqWt5EN*#fPw;|171@L62Ztf!lLQrifDXAhSDG66`v^TS~F@->6gJa_GG}K2Z1HU&cy`e-PZ4Zf6ZxCYd35s8!aJhD4Smhbj zL#X+r$3|h*kl=`c>)zq_M)Q=Y3T{aBvuhF8FKI#GkK$ul;Ls`u38#WT)#bm7 z-^=io!RF>1egKS$X*D)A^^;^Zo*@~tOu*(_QIQ#;l($WmtZjS($;{NsV&9@?L~s)_ z`MN{SorKP+-sQ-d{kSE5K|p8qYKZ$Cld1dayeFnN6kr6YhFJC-z9CU8jU>FCT_&Hq z9n5sEcm_VZrhHDla8aj|T8Z5Kn`3~bI2O<84cF=$V*Q*pfuE@}N@++xmkD0`Z6gvn z0Mijp_#SJyz#1ge{+Yi!rFWR;aEk#S+&0OPc>?j>o%ohXO z_HMoSNyXCwha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rSM@*Q;ElXSqjoXdJ)Q>r1_UDN?nzH~ulbaNj`4!_{@`K5pOoPouF@ z-V0n#7id2?E!~g&YMHxt^BGZ$ZMWubfJb?4_Sliz{=4L30PY*!=^z<)jhrBQ4M_iNpcaY7mH38Zi^K!CGV7X$dyLKdz2@NOw}FAOq^a1 zTz{FDbnCzB#D6;R|Ed#@=C{!et-n861{`+Aq*R6dC=Eb=^8fvbqvqD#m+Epwc@GPK zqXcVN(P(jJCnjk|H(!PB-y$*cE8lE9W51Uzbm;z$0=OCE+-*XSX8*~!P`@QZ1$|>l jV)m$_K1`5VmJhHEF8UZB#Ds-o!9UqsN;mT)jUN0j7atJ( literal 0 HcmV?d00001 From ac14103b71ad36db6290c82333d505f1547f3b1a Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 20:40:21 +0100 Subject: [PATCH 02/49] chore: add repository conventions, docs skeleton and CI Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 18 ++++++++++++ .gitignore | 15 +++++++++- CLAUDE.md | 40 ++++++++++++++++++++++++++ README.md | 17 +++++++++-- docs/README.md | 4 +++ docs/architecture.md | 61 ++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 10 +++++++ requirements_test.txt | 3 ++ tests/__init__.py | 0 tests/docs/__init__.py | 0 tests/docs/test_links.py | 47 +++++++++++++++++++++++++++++++ 11 files changed, 211 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 CLAUDE.md create mode 100644 docs/README.md create mode 100644 docs/architecture.md create mode 100644 pyproject.toml create mode 100644 requirements_test.txt create mode 100644 tests/__init__.py create mode 100644 tests/docs/__init__.py create mode 100644 tests/docs/test_links.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c79722b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,18 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + python: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.14" + - run: pip install -r requirements_test.txt + - run: ruff check . + - run: pytest diff --git a/.gitignore b/.gitignore index 496ee2c..6fc4a9d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,14 @@ -.DS_Store \ No newline at end of file +.DS_Store +__pycache__/ +.pytest_cache/ +.ruff_cache/ +.venv*/ +node_modules/ +frontend/coverage/ +custom_components/ha_controller/frontend/*.js +esphome/.esphome/ +esphome/secrets.yaml +build/ +dist/ +site/ +.superpowers/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..d1a31ea --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,40 @@ +# HA Controller — guidance for Claude Code + +HA Controller turns the Waveshare ESP32-S3-Touch-AMOLED-1.75 round touch screen into a Home Assistant remote. +It is a custom integration with a sidebar panel, an ESPHome firmware and a GitHub Pages web installer. + +## Rules + +- English only: code, comments, docs and commit messages. +- One version for the whole repository. Change it only with `python scripts/versioning.py bump X.Y.Z` (added in plan 5). +- The protocol is defined in `docs/protocol.md` and pinned by `protocol/fixtures/`. +- TDD: write the failing test first, then the code. +- Never commit `esphome/secrets.yaml`. +- Specs and plans live in `docs/superpowers/`. + +## Repository map + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/superpowers/` holds this spec and the plans. | +| `protocol/fixtures/` | Shared test fixtures: the cross-language contract | +| `custom_components/ha_controller/` | Home Assistant integration (Python) | +| `custom_components/ha_controller/emoji.json` | Canonical list of supported emoji, read by the firmware build, the panel and the integration | +| `custom_components/ha_controller/frontend/` | Built panel bundle (generated, git-ignored) | +| `frontend/` | Panel source (TypeScript, Lit, Vite) | +| `esphome/` | Firmware: device config, packages, simulator config, external components, host tests, web installer page | +| `scripts/` | Versioning, packaging, GitHub Pages site builder | +| `tests/` | Python tests (protocol fixtures, docs, integration, scripts) | +| `.claude/` | Claude Code skills and agents | +| `.github/workflows/` | CI, firmware CI, release | +| `3D_models/`, `files/` | Existing enclosure models (unchanged) | + +## Commands + +| Command | Purpose | +|---|---| +| `pytest` | Run the Python tests | +| `ruff check .` | Lint the Python code | + +## Skills and agents + diff --git a/README.md b/README.md index 9999a74..4426542 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,22 @@ # HA Controller -An ESP-32 remote control with a 1.75-inch AMOLED display + +HA Controller turns the Waveshare ESP32-S3-Touch-AMOLED-1.75, a round AMOLED touch screen, into a Home Assistant remote. A custom integration with a sidebar panel lets you design what the screen shows, and an ESPHome firmware renders it. + +- Block map editor in Home Assistant +- Edge-swipe navigation between blocks +- Light and thermostat knobs +- Custom blocks +- Automatic firmware updates + +Status: under active development. + +See the [documentation](docs/README.md). ## 3D models -You can find two 3D models with or without power button, into [3D Models](3D_models) folder. Each models is in STL or 3MF. +You can find two 3D models, with or without power button, in the [3D_models](3D_models) folder. Each model is available as STL or 3MF.

    -

    \ No newline at end of file +

    diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..8c6a513 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,4 @@ +# HA Controller documentation + +- [Architecture](architecture.md): subsystems, data flow and repository layout. +- [Design specification](superpowers/specs/2026-11-16-ha-controller-design.md): the approved design for version 1, with the plans in `superpowers/plans/`. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..232ae1c --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,61 @@ +# Architecture + +HA Controller has three parts: a Home Assistant custom integration with a sidebar panel, an ESPHome firmware for the screen, and a GitHub Pages web installer. This page is the contributor overview. + +## Overview + +```text + Home Assistant Screen (ESPHome firmware) +┌──────────────────────────────────────────┐ ┌──────────────────────────────────────┐ +│ custom integration `ha_controller` │ ESPHome │ external component `ha_controller` │ +│ config entry per screen │ actions │ layout + state parsers (pure C++) │ +│ layout store + validation │ ─────────▶ │ pager: edge swipes, slide animation │ +│ compiler → device payload (+ revision) │ set_layout │ block views: knobs, custom items │ +│ sync engine (hello, states, controls) │ set_states │ message screen │ +│ firmware update entity + auto-update │ install_fw │ │ +│ websocket API + sidebar panel (Lit) │ ◀───────── │ board package: CO5300 display, │ +└──────────────────────────────────────────┘ events │ CST9217 touch, AXP2101 battery, │ + ▲ HACS (release zip) hello / │ screen brightness number │ + │ control └──────────────────────────────────────┘ + GitHub Releases ──────▶ GitHub Pages: web installer + firmware// ▲ OTA download / USB flash +``` + +## Subsystems + +- The screen is an ordinary ESPHome device, adopted by Home Assistant's ESPHome integration. The custom integration opens no connection of its own. It calls the device's user-defined ESPHome actions, which Home Assistant exposes as services `esphome._` (node name with `-` replaced by `_`). It also listens to the `esphome.ha_controller_*` events fired by the device. +- Home Assistant's ESPHome integration adds `device_id` to every device event. It requires the "Allow the device to perform Home Assistant actions" option for actions, but not for events (`homeassistant/components/esphome/manager.py`). The design uses events only, so that option can stay off. +- The integration is the single source of truth for both the layout and the version. The firmware is a generic renderer. + +- **Integration** (`custom_components/ha_controller/`): stores and validates layouts, compiles them into the device payload, runs the sync engine and exposes the websocket API used by the panel. +- **Panel** (`frontend/`): the block map editor, built with Lit and Vite and served from the integration. +- **Firmware** (`esphome/`): a generic renderer. It parses the layout and states it receives, draws the blocks and reports touches as events. +- **Distribution** (`scripts/`, `.github/workflows/`): HACS release zip, firmware builds and the web installer on GitHub Pages. + +## Handshake: hello, layout and states + +When the screen connects (or reboots) it fires a `hello` event carrying its firmware version and the protocol version. The integration answers with `set_layout` (the compiled layout payload with its revision) and then `set_states` (the current Home Assistant states of the entities the layout uses). Afterwards it sends `set_states` again whenever a watched entity changes, and `set_layout` whenever the stored layout changes. The exact messages are defined in `docs/protocol.md` and pinned by `protocol/fixtures/`. + +## Controls become service calls + +A touch on a block (a knob turn, a tap on a custom item) is sent by the firmware as a `control` event. The integration maps the event to a Home Assistant service call using the stored layout, never trusting the device for entity ids or service names, and runs it. The resulting state change flows back to the screen through `set_states`. + +## Firmware updates + +The integration version is the single version of the repository. The integration creates an `update` entity per screen: the installed version comes from the last hello and the latest version is the integration version. Installing calls the device's `install_firmware` action with the OTA URL on GitHub Pages (`firmware//`). With the `auto_update` option on, a hello reporting a different version triggers one automatic install attempt per screen and version, only for release versions. OTA needs internet access from the screen. Without it, re-flash over USB from the web installer. + +## Repository layout + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/superpowers/` holds this spec and the plans. | +| `protocol/fixtures/` | Shared test fixtures: the cross-language contract | +| `custom_components/ha_controller/` | Home Assistant integration (Python) | +| `custom_components/ha_controller/emoji.json` | Canonical list of supported emoji, read by the firmware build, the panel and the integration | +| `custom_components/ha_controller/frontend/` | Built panel bundle (generated, git-ignored) | +| `frontend/` | Panel source (TypeScript, Lit, Vite) | +| `esphome/` | Firmware: device config, packages, simulator config, external components, host tests, web installer page | +| `scripts/` | Versioning, packaging, GitHub Pages site builder | +| `tests/` | Python tests (protocol fixtures, docs, integration, scripts) | +| `.claude/` | Claude Code skills and agents | +| `.github/workflows/` | CI, firmware CI, release | +| `3D_models/`, `files/` | Existing enclosure models (unchanged) | diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..6e970aa --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,10 @@ +[tool.pytest.ini_options] +testpaths = ["tests"] +asyncio_mode = "auto" + +[tool.ruff] +target-version = "py314" +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] diff --git a/requirements_test.txt b/requirements_test.txt new file mode 100644 index 0000000..33489d4 --- /dev/null +++ b/requirements_test.txt @@ -0,0 +1,3 @@ +pytest +pytest-asyncio +ruff diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/docs/__init__.py b/tests/docs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/docs/test_links.py b/tests/docs/test_links.py new file mode 100644 index 0000000..aacf285 --- /dev/null +++ b/tests/docs/test_links.py @@ -0,0 +1,47 @@ +"""Documentation checks: relative links resolve and the docs index is complete.""" + +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DOC_ROOTS = ["README.md", "CLAUDE.md", "docs"] # docs/superpowers/** is excluded +EXCLUDED = ROOT / "docs" / "superpowers" +LINK_RE = re.compile(r"\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") +EXTERNAL_PREFIXES = ("http://", "https://", "mailto:", "#") + + +def _markdown_files() -> list[Path]: + files: list[Path] = [] + for name in DOC_ROOTS: + path = ROOT / name + if path.is_dir(): + files.extend(p for p in path.rglob("*.md") if EXCLUDED not in p.parents) + elif path.exists(): + files.append(path) + return sorted(files) + + +def test_relative_links_resolve(): + broken = [] + for md_file in _markdown_files(): + for target in LINK_RE.findall(md_file.read_text(encoding="utf-8")): + if target.startswith(EXTERNAL_PREFIXES): + continue + relative = target.split("#", 1)[0] + if relative and not (md_file.parent / relative).resolve().exists(): + broken.append(f"{md_file.relative_to(ROOT)} -> {target}") + assert not broken, "Broken relative links:\n" + "\n".join(broken) + + +def test_docs_index_lists_every_doc(): + index = ROOT / "docs" / "README.md" + assert index.exists(), "docs/README.md is missing" + linked = { + (index.parent / t.split("#", 1)[0]).resolve() + for t in LINK_RE.findall(index.read_text(encoding="utf-8")) + if not t.startswith(EXTERNAL_PREFIXES) + } + missing = [ + p.name for p in (ROOT / "docs").glob("*.md") if p != index and p.resolve() not in linked + ] + assert not missing, f"Docs not linked from docs/README.md: {missing}" From 0d67763d902bd42e999d28edae725a5ae10e07af Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 20:42:56 +0100 Subject: [PATCH 03/49] feat(protocol): add protocol v1 contract, shared fixtures and guidance Co-Authored-By: Claude Sonnet 5.5 --- .claude/agents/protocol-guardian.md | 15 + .claude/skills/protocol-change/SKILL.md | 13 + CLAUDE.md | 2 + custom_components/ha_controller/emoji.json | 66 ++++ docs/README.md | 1 + docs/protocol.md | 141 +++++++ protocol/README.md | 28 ++ protocol/fixtures/colors.json | 38 ++ protocol/fixtures/controls/climate-clamp.json | 26 ++ protocol/fixtures/controls/climate-set.json | 26 ++ .../fixtures/controls/ignored-bad-value.json | 11 + .../controls/ignored-climate-toggle.json | 11 + .../controls/ignored-custom-block.json | 11 + .../controls/ignored-unknown-block.json | 11 + .../fixtures/controls/light-set-over.json | 18 + .../fixtures/controls/light-set-zero.json | 17 + protocol/fixtures/controls/light-set.json | 18 + protocol/fixtures/controls/light-toggle.json | 17 + .../invalid/coordinate_out_of_range.json | 25 ++ .../layouts/invalid/disconnected.json | 85 +++++ .../layouts/invalid/duplicate_id.json | 85 +++++ .../layouts/invalid/duplicate_position.json | 85 +++++ .../layouts/invalid/invalid_background.json | 85 +++++ .../layouts/invalid/invalid_entity-item.json | 85 +++++ .../layouts/invalid/invalid_entity.json | 85 +++++ .../invalid/invalid_font_size-item.json | 85 +++++ .../layouts/invalid/invalid_font_size.json | 85 +++++ .../fixtures/layouts/invalid/invalid_id.json | 85 +++++ .../layouts/invalid/invalid_item.json | 85 +++++ .../layouts/invalid/invalid_name.json | 85 +++++ .../invalid/invalid_sleep_timeout.json | 85 +++++ .../layouts/invalid/invalid_start-empty.json | 14 + .../layouts/invalid/invalid_start.json | 85 +++++ .../invalid/invalid_structure-settings.json | 83 +++++ .../invalid/invalid_structure-version.json | 85 +++++ .../layouts/invalid/invalid_structure.json | 14 + .../layouts/invalid/invalid_text.json | 85 +++++ .../layouts/invalid/invalid_type.json | 85 +++++ .../layouts/invalid/too_many_blocks.json | 345 ++++++++++++++++++ .../layouts/invalid/too_many_items.json | 97 +++++ .../layouts/invalid/unsupported_emoji.json | 85 +++++ .../layouts/valid/emoji-variation.json | 26 ++ protocol/fixtures/layouts/valid/empty.json | 8 + .../fixtures/layouts/valid/reference.json | 79 ++++ protocol/fixtures/layouts/valid/single.json | 19 + .../payloads/invalid/bad_json-array.json | 4 + .../fixtures/payloads/invalid/bad_json.json | 4 + .../invalid/invalid_payload-sleep.json | 4 + .../invalid/invalid_payload-widget.json | 4 + .../payloads/invalid/invalid_payload.json | 4 + .../payloads/invalid/unsupported_version.json | 4 + .../payloads/valid/emoji-variation.json | 28 ++ protocol/fixtures/payloads/valid/empty.json | 10 + .../fixtures/payloads/valid/reference.json | 76 ++++ protocol/fixtures/states/all-missing.json | 24 ++ .../fixtures/states/climate-defaults.json | 29 ++ protocol/fixtures/states/climate-heating.json | 33 ++ protocol/fixtures/states/entity-missing.json | 14 + .../fixtures/states/entity-precision.json | 28 ++ .../fixtures/states/light-dimmable-off.json | 25 ++ .../fixtures/states/light-dimmable-on.json | 26 ++ protocol/fixtures/states/light-onoff.json | 25 ++ .../fixtures/states/light-unavailable.json | 19 + tests/protocol/__init__.py | 0 tests/protocol/test_fixtures.py | 117 ++++++ 65 files changed, 3103 insertions(+) create mode 100644 .claude/agents/protocol-guardian.md create mode 100644 .claude/skills/protocol-change/SKILL.md create mode 100644 custom_components/ha_controller/emoji.json create mode 100644 docs/protocol.md create mode 100644 protocol/README.md create mode 100644 protocol/fixtures/colors.json create mode 100644 protocol/fixtures/controls/climate-clamp.json create mode 100644 protocol/fixtures/controls/climate-set.json create mode 100644 protocol/fixtures/controls/ignored-bad-value.json create mode 100644 protocol/fixtures/controls/ignored-climate-toggle.json create mode 100644 protocol/fixtures/controls/ignored-custom-block.json create mode 100644 protocol/fixtures/controls/ignored-unknown-block.json create mode 100644 protocol/fixtures/controls/light-set-over.json create mode 100644 protocol/fixtures/controls/light-set-zero.json create mode 100644 protocol/fixtures/controls/light-set.json create mode 100644 protocol/fixtures/controls/light-toggle.json create mode 100644 protocol/fixtures/layouts/invalid/coordinate_out_of_range.json create mode 100644 protocol/fixtures/layouts/invalid/disconnected.json create mode 100644 protocol/fixtures/layouts/invalid/duplicate_id.json create mode 100644 protocol/fixtures/layouts/invalid/duplicate_position.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_background.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_entity-item.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_entity.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_font_size-item.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_font_size.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_id.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_item.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_name.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_start-empty.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_start.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_structure-settings.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_structure-version.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_structure.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_text.json create mode 100644 protocol/fixtures/layouts/invalid/invalid_type.json create mode 100644 protocol/fixtures/layouts/invalid/too_many_blocks.json create mode 100644 protocol/fixtures/layouts/invalid/too_many_items.json create mode 100644 protocol/fixtures/layouts/invalid/unsupported_emoji.json create mode 100644 protocol/fixtures/layouts/valid/emoji-variation.json create mode 100644 protocol/fixtures/layouts/valid/empty.json create mode 100644 protocol/fixtures/layouts/valid/reference.json create mode 100644 protocol/fixtures/layouts/valid/single.json create mode 100644 protocol/fixtures/payloads/invalid/bad_json-array.json create mode 100644 protocol/fixtures/payloads/invalid/bad_json.json create mode 100644 protocol/fixtures/payloads/invalid/invalid_payload-sleep.json create mode 100644 protocol/fixtures/payloads/invalid/invalid_payload-widget.json create mode 100644 protocol/fixtures/payloads/invalid/invalid_payload.json create mode 100644 protocol/fixtures/payloads/invalid/unsupported_version.json create mode 100644 protocol/fixtures/payloads/valid/emoji-variation.json create mode 100644 protocol/fixtures/payloads/valid/empty.json create mode 100644 protocol/fixtures/payloads/valid/reference.json create mode 100644 protocol/fixtures/states/all-missing.json create mode 100644 protocol/fixtures/states/climate-defaults.json create mode 100644 protocol/fixtures/states/climate-heating.json create mode 100644 protocol/fixtures/states/entity-missing.json create mode 100644 protocol/fixtures/states/entity-precision.json create mode 100644 protocol/fixtures/states/light-dimmable-off.json create mode 100644 protocol/fixtures/states/light-dimmable-on.json create mode 100644 protocol/fixtures/states/light-onoff.json create mode 100644 protocol/fixtures/states/light-unavailable.json create mode 100644 tests/protocol/__init__.py create mode 100644 tests/protocol/test_fixtures.py diff --git a/.claude/agents/protocol-guardian.md b/.claude/agents/protocol-guardian.md new file mode 100644 index 0000000..ebc4af8 --- /dev/null +++ b/.claude/agents/protocol-guardian.md @@ -0,0 +1,15 @@ +--- +name: protocol-guardian +description: Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol.md, protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging. +tools: Read, Grep, Glob, Bash +--- + +You review protocol changes. Read the diff (`git diff main...HEAD`), then check: + +- Field names, error codes, limits and constants are identical in `docs/protocol.md`, the Python integration, the TypeScript model and the C++ parsers. +- Fixtures under `protocol/fixtures/` are updated, and each invalid layout fixture still breaks exactly one rule. +- Golden `rev` values are recomputed (see `protocol/README.md`). +- `PROTOCOL_VERSION` is bumped in `const.py` and `ha_controller.h` on breaking changes. +- `docs/protocol.md` describes the new behaviour. + +Output a list of `file:line — inconsistency — fix`, or "Protocol consistent". diff --git a/.claude/skills/protocol-change/SKILL.md b/.claude/skills/protocol-change/SKILL.md new file mode 100644 index 0000000..7a50e3a --- /dev/null +++ b/.claude/skills/protocol-change/SKILL.md @@ -0,0 +1,13 @@ +--- +name: protocol-change +description: "Use when changing anything that crosses the Home Assistant ↔ screen boundary: layout fields, validation rules, payload keys, state update fields, events, actions, emoji list or limits." +--- + +# Changing the HA ↔ screen protocol + +1. Classify the change. The C++ parser rejects unknown `widget`/`kind`/`font` values, so any new value is breaking: bump `PROTOCOL_VERSION` in `custom_components/ha_controller/const.py` and in the firmware's `ha_controller.h`. +2. Edit `docs/protocol.md` first. +3. Update `protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet in `protocol/README.md`. +4. Update the Python code (`layout.py`, `compiler.py`, `states.py`, `controls.py`), the TypeScript model (`frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). +5. Run `pytest`, `npm --prefix frontend test`, the host C++ tests and `esphome compile`. +6. Ask the `protocol-guardian` agent to review. diff --git a/CLAUDE.md b/CLAUDE.md index d1a31ea..d87fa04 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,3 +38,5 @@ It is a custom integration with a sidebar panel, an ESPHome firmware and a GitHu ## Skills and agents +- Skill `protocol-change` (`.claude/skills/protocol-change/`): checklist for any change that crosses the Home Assistant ↔ screen boundary. +- Agent `protocol-guardian` (`.claude/agents/protocol-guardian.md`): reviews a diff for protocol consistency across docs, fixtures, Python, TypeScript and C++. diff --git a/custom_components/ha_controller/emoji.json b/custom_components/ha_controller/emoji.json new file mode 100644 index 0000000..8ced6fd --- /dev/null +++ b/custom_components/ha_controller/emoji.json @@ -0,0 +1,66 @@ +[ + "💡", + "🔥", + "❄", + "🌡", + "💧", + "🌬", + "☀", + "🌙", + "⭐", + "☁", + "⛅", + "🌧", + "⚡", + "🔋", + "🔌", + "🏠", + "🛋", + "🛏", + "🛁", + "🚿", + "🍳", + "🍽", + "☕", + "🍷", + "🧺", + "🪴", + "🚪", + "🪟", + "🔒", + "🔓", + "🔑", + "🔔", + "🔕", + "🔊", + "🔇", + "🎵", + "📺", + "🎮", + "💻", + "📱", + "⏰", + "📅", + "🚗", + "🚲", + "🐶", + "🐱", + "👶", + "👋", + "👍", + "❤", + "😀", + "😴", + "🎉", + "🎄", + "✅", + "❌", + "⚠", + "ℹ", + "▶", + "⏸", + "♻", + "🌀", + "🧊", + "🏡" +] diff --git a/docs/README.md b/docs/README.md index 8c6a513..1fd5cd1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,3 +2,4 @@ - [Architecture](architecture.md): subsystems, data flow and repository layout. - [Design specification](superpowers/specs/2026-11-16-ha-controller-design.md): the approved design for version 1, with the plans in `superpowers/plans/`. +- [Device protocol v1](protocol.md): the normative layout model and device protocol, pinned by `protocol/fixtures/`. diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..75b4554 --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,141 @@ +# Device protocol v1 + +## 6. Layout model (integration and panel) + +The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: + +```json +{ "version": 1, "start": "b1", "settings": { "sleep_timeout": 20 }, "blocks": [ + { "id": "b1", "x": 0, "y": 0, "name": "Kitchen", "background": "#5B9E4D", "font_size": "m", + "type": "entity", "entity_id": "light.kitchen" }, + { "id": "b2", "x": 0, "y": -1, "name": "Lights", "background": "#C94F3D", "font_size": "m", + "type": "entity", "entity_id": "light.living_room" }, + { "id": "b3", "x": -1, "y": 0, "name": "Hello World", "background": "#4F86DD", "font_size": "l", + "type": "custom", "items": [ + { "id": "i1", "kind": "text", "text": "Hello World", "font_size": null }, + { "id": "i2", "kind": "emoji", "emoji": "👋", "font_size": "xl" }, + { "id": "i3", "kind": "entity", "entity_id": "sensor.outdoor_temperature", "attribute": null, "font_size": "s" }, + { "id": "i4", "kind": "battery", "font_size": "s" }, + { "id": "i5", "kind": "brightness", "font_size": null } ] }, + { "id": "b4", "x": -1, "y": 1, "name": "Bedroom", "background": "#7B2FA0", "font_size": "m", + "type": "entity", "entity_id": "climate.bedroom" } ] } +``` + +Unknown keys are ignored, so the panel can keep `entity_id` and `items` when the user switches a block's type. + +Validation returns a list of `{code, ref}`, where `ref` is the offending block or item id, or `null`. An empty list means the layout is valid. It runs in three phases: +1. **Structure.** It stops at the first error. +2. **Per-field checks.** All errors are collected. +3. **Connectivity.** Only runs if phase 2 found nothing. + +| Code | Rule | +|---|---| +| `invalid_structure` | `version` must be `1`, `settings` an object, `blocks` a list, and blocks and items objects with the expected JSON types | +| `too_many_blocks` | At most 32 blocks | +| `invalid_sleep_timeout` | `settings.sleep_timeout` is an integer (not a boolean): `0` (never) or 5–3600 seconds | +| `invalid_id` | Ids match `^[a-z][a-z0-9]{0,7}$` | +| `duplicate_id` | Ids are unique across blocks **and** items | +| `coordinate_out_of_range` | `-32 ≤ x, y ≤ 32` (integers) | +| `duplicate_position` | One block per cell (ref = the later block) | +| `invalid_start` | `start` is `null` if and only if there are no blocks; otherwise it is the id of an existing block | +| `disconnected` | Every block is reachable from `start` through 4-neighbour cells (one error per unreachable block, in layout order) | +| `invalid_name` | 1–32 characters after trimming | +| `invalid_background` | `^#[0-9A-Fa-f]{6}$` | +| `invalid_font_size` | Block: `s`/`m`/`l`/`xl`. Item: the same, or `null` (inherit). | +| `invalid_type` | `entity` or `custom` | +| `invalid_entity` | Entity block: an `entity_id` of domain `light` or `climate`. Entity item: an id matching `^[a-z0-9_]+\.[a-z0-9_]+$`, and `attribute` either `null` or 1–64 characters. | +| `too_many_items` | At most 6 items per custom block | +| `invalid_item` | `kind` is one of `text`, `emoji`, `entity`, `battery`, `brightness` | +| `invalid_text` | Text item: 1–64 characters | +| `unsupported_emoji` | Emoji item: after removing U+FE0F, the value is an entry of `emoji.json` | +| `payload_too_large` | The compiled payload (§7.3) is larger than 24 576 UTF-8 bytes. Checked by the integration only. | + +Entities that do not exist (yet) are valid; the screen shows them as unavailable. + +## 7. Device protocol v1 (normative) + +`PROTOCOL_VERSION = 1`. `docs/protocol.md` is the living copy of this section. `protocol/fixtures/` pins it with examples, used by the tests of all three implementations. + +**7.1 Actions (Home Assistant → screen).** Services `esphome._`: + +| Action | Variables | Effect | +|---|---|---| +| `set_layout` | `layout: string` (payload JSON, §7.3) | Parse it. On success, rebuild the pages and adopt `rev`. Then fire a hello with reason `applied`; this also happens after a failure, with the revision unchanged. | +| `set_states` | `states: string` (JSON array, §7.4) | Apply each update to the block or item with that id. Unknown ids are ignored. | +| `install_firmware` | `url: string`, `md5_url: string` | Show `Updating firmware…`, render it immediately, then run `ota.http_request.flash`. On failure, show `Update failed` for 5 s. | + +**7.2 Events (screen → Home Assistant).** Data values are strings, and Home Assistant adds `device_id`. + +| Event | Data | When | +|---|---|---| +| `esphome.ha_controller_hello` | `node` (ESPHome node name), `version` (firmware version), `protocol` (`"1"`), `revision` (applied `rev` or `none`), `reason` (`connected` / `heartbeat` / `applied`) | 5 s after an API client connects, every 60 s while connected, and after each `set_layout` | +| `esphome.ha_controller_control` | `block` (block id), `item` (item id or empty), `op` (`toggle` / `set`), `value` (decimal, `%.2f`) | Centre tap on a light (`toggle`), knob release (`set`) | + +**7.3 Layout payload.** The integration compiles it from the stored layout: +- **Top level:** `v` (1), `rev`, `start` (id or `null`), `sleep` (integer seconds, `0` = never), `blocks`. +- **Block:** `id`, `x`, `y`, `name`, `bg` (6 uppercase hex digits, no `#`), `font`, `widget`. + - `widget` is `light` or `climate` (taken from the entity domain), or `custom`. + - Custom blocks also carry `items` (possibly empty). Entity blocks carry no `items`. +- **Item:** `id`, `kind`, `font` (the item's size, or the block's when the item's is `null`). + - `text` items carry `text` (the text). + - `emoji` items carry `text` (the emoji without U+FE0F). + - Other kinds carry no `text`. +- No entity ids are sent to the screen. +- `rev` is the first 8 hex chars of SHA-256 over the UTF-8 bytes of `json.dumps(payload_without_rev, sort_keys=True, separators=(",", ":"), ensure_ascii=False)`. + - Golden values: empty payload (`sleep` 20) → `c4aad3fa`; `payloads/valid/reference.json` → `90538742`; `payloads/valid/emoji-variation.json` → `5387d4ea`. +- **Transport encoding:** compact JSON (`separators=(",", ":")`, `ensure_ascii=False`), at most 24 576 bytes. + +Device parse errors: +- `bad_json`: not JSON, or not an object. +- `unsupported_version`: `v != 1`. +- `invalid_payload`: a missing or mistyped field, an unknown `widget`, `kind` or `font`, or a `sleep` outside 0–3600. + +**7.4 State updates.** A JSON array. Each element has `id` (block or item id) and `available` (bool, default `true`): + +| Target | Fields | +|---|---| +| Light block | `on` (bool), `brightness` (0–100 integer; `null` for on/off-only lights; `0` when a dimmable light is off) | +| Climate block | `target` (number or `null`), `min`, `max`, `step` (numbers), `unit` (`°C`/`°F`), `current` (display string), `action` (display string, e.g. `Heating`) | +| Entity item | `text` (display string) | + +An unavailable or missing entity sends `{"id": …, "available": false}`. Entity items send `{"id": …, "text": "—"}` instead. Updates are sent in layout order, in chunks of at most 8 192 bytes. + +**7.5 Handshake and resync** (integration side): +- **On a hello from the screen's `device_id`:** record the node, version, protocol, revision and time. Then: + - If `protocol ≠ 1`, push nothing (auto-update may run, §11). + - Else, if `revision ≠` the current revision, push the layout and then all states. Push immediately when `reason = connected`. Otherwise push at most once per 300 s for the same revision. + - Else, if `reason = connected`, push all states. +- **Entity state changes:** coalesced for 200 ms, then pushed for the changed entities. This only happens while the screen is online (a hello within the last 150 s) and on protocol 1. +- **Saving a layout:** pushes it immediately if the screen is online. + +**7.6 Control mapping** (integration side). The entity always comes from the layout, never from the event. + +| Block | op | Service call | +|---|---|---| +| Light | `toggle` | `light.toggle` `{entity_id}` | +| Light | `set`, value ≤ 0 | `light.turn_off` `{entity_id}` | +| Light | `set`, value > 0 | `light.turn_on` `{entity_id, brightness_pct: round(clamp(value, 1, 100))}` | +| Climate | `set` | `climate.set_temperature` `{entity_id, temperature: clamp(value, min_temp, max_temp)}` (bounds from the current state, defaults 7/35) | + +Anything else is ignored: an unknown block, a custom block, an unparsable value. Service errors are logged, never raised. + +**7.7 State builders** (integration side): +- **Light:** + - Unavailable if the entity is missing, `unavailable` or `unknown`. + - Dimmable if `supported_color_modes` contains a mode other than `onoff`. + - Brightness: `round((attribute brightness or 255) × 100 / 255)` when on, `0` when off, `null` when not dimmable. +- **Climate:** + - `unit` is Home Assistant's temperature unit. + - `step` is `target_temp_step`, or else `0.5` for °C and `1` for °F. + - `min`/`max` come from `min_temp`/`max_temp` (defaults 7/35). + - `current` is `" "`, or `—`. + - `action` is `hvac_action`, or else the state, with `_` replaced by a space and the first letter capitalised. +- **Entity item:** + - `—` if the entity is missing, `unavailable` or `unknown`, or if the attribute is missing. + - A numeric value is rounded to the entity registry's `sensor.display_precision`, or else `suggested_display_precision`, or else left unchanged. + - The result is `" "` when a unit exists, truncated to 64 characters. + + +## Fixtures + +The examples that pin this protocol live in [protocol/fixtures](../protocol/README.md). All three implementations test themselves against them. diff --git a/protocol/README.md b/protocol/README.md new file mode 100644 index 0000000..6f65acd --- /dev/null +++ b/protocol/README.md @@ -0,0 +1,28 @@ +# Protocol fixtures + +`fixtures/` is the executable contract of the protocol defined in [docs/protocol.md](../docs/protocol.md). All files are UTF-8 JSON without a BOM. + +## Who reads what + +| Folder | Content | Read by | +|---|---|---| +| `fixtures/layouts/valid`, `fixtures/layouts/invalid` | Stored layouts and the validation error each invalid one must produce | pytest in `tests/integration`, vitest in `frontend/test` | +| `fixtures/payloads/valid` | A stored layout and the compiled payload (with golden `rev`) | pytest in `tests/integration`, vitest in `frontend/test`, doctest in `esphome/tests` | +| `fixtures/payloads/invalid` | Raw strings sent to `set_layout` and the parse error expected | doctest in `esphome/tests` | +| `fixtures/states` | Home Assistant states and the expected update objects | pytest in `tests/integration` | +| `fixtures/controls` | Control events and the expected service call | pytest in `tests/integration` | +| `fixtures/colors.json` | Background colours and the expected text colour | pytest in `tests/integration`, vitest in `frontend/test`, doctest in `esphome/tests` | + +`tests/protocol` checks the fixtures themselves. + +## One broken rule per invalid fixture + +Each file in `layouts/invalid` takes a valid layout and breaks exactly one rule. Its stem is the expected error code, or the code followed by `-` and a suffix when a code has several cases. + +## Canonical revision + +```python +hashlib.sha256(json.dumps(p, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()[:8] +``` + +`p` is the payload without its `rev` key. Recompute the golden `rev` of `payloads/valid/*.json` whenever a payload changes. diff --git a/protocol/fixtures/colors.json b/protocol/fixtures/colors.json new file mode 100644 index 0000000..8ed6457 --- /dev/null +++ b/protocol/fixtures/colors.json @@ -0,0 +1,38 @@ +[ + { + "bg": "#FFFFFF", + "text": "#000000" + }, + { + "bg": "#000000", + "text": "#FFFFFF" + }, + { + "bg": "#5B9E4D", + "text": "#FFFFFF" + }, + { + "bg": "#4F86DD", + "text": "#FFFFFF" + }, + { + "bg": "#C94F3D", + "text": "#FFFFFF" + }, + { + "bg": "#7B2FA0", + "text": "#FFFFFF" + }, + { + "bg": "#F1C40F", + "text": "#000000" + }, + { + "bg": "#9E9E9E", + "text": "#000000" + }, + { + "bg": "#8C8C8C", + "text": "#FFFFFF" + } +] diff --git a/protocol/fixtures/controls/climate-clamp.json b/protocol/fixtures/controls/climate-clamp.json new file mode 100644 index 0000000..4590942 --- /dev/null +++ b/protocol/fixtures/controls/climate-clamp.json @@ -0,0 +1,26 @@ +{ + "layout": "reference", + "hass_states": { + "climate.bedroom": { + "state": "heat", + "attributes": { + "min_temp": 7, + "max_temp": 35 + } + } + }, + "event": { + "block": "b4", + "item": "", + "op": "set", + "value": "50.00" + }, + "expect_call": { + "domain": "climate", + "service": "set_temperature", + "data": { + "entity_id": "climate.bedroom", + "temperature": 35 + } + } +} diff --git a/protocol/fixtures/controls/climate-set.json b/protocol/fixtures/controls/climate-set.json new file mode 100644 index 0000000..8794970 --- /dev/null +++ b/protocol/fixtures/controls/climate-set.json @@ -0,0 +1,26 @@ +{ + "layout": "reference", + "hass_states": { + "climate.bedroom": { + "state": "heat", + "attributes": { + "min_temp": 7, + "max_temp": 35 + } + } + }, + "event": { + "block": "b4", + "item": "", + "op": "set", + "value": "21.50" + }, + "expect_call": { + "domain": "climate", + "service": "set_temperature", + "data": { + "entity_id": "climate.bedroom", + "temperature": 21.5 + } + } +} diff --git a/protocol/fixtures/controls/ignored-bad-value.json b/protocol/fixtures/controls/ignored-bad-value.json new file mode 100644 index 0000000..290ad87 --- /dev/null +++ b/protocol/fixtures/controls/ignored-bad-value.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "set", + "value": "abc" + }, + "expect_call": null +} diff --git a/protocol/fixtures/controls/ignored-climate-toggle.json b/protocol/fixtures/controls/ignored-climate-toggle.json new file mode 100644 index 0000000..dd5e767 --- /dev/null +++ b/protocol/fixtures/controls/ignored-climate-toggle.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b4", + "item": "", + "op": "toggle", + "value": "0.00" + }, + "expect_call": null +} diff --git a/protocol/fixtures/controls/ignored-custom-block.json b/protocol/fixtures/controls/ignored-custom-block.json new file mode 100644 index 0000000..8e65c09 --- /dev/null +++ b/protocol/fixtures/controls/ignored-custom-block.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b3", + "item": "", + "op": "set", + "value": "1" + }, + "expect_call": null +} diff --git a/protocol/fixtures/controls/ignored-unknown-block.json b/protocol/fixtures/controls/ignored-unknown-block.json new file mode 100644 index 0000000..15c4a1b --- /dev/null +++ b/protocol/fixtures/controls/ignored-unknown-block.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "zz", + "item": "", + "op": "set", + "value": "1" + }, + "expect_call": null +} diff --git a/protocol/fixtures/controls/light-set-over.json b/protocol/fixtures/controls/light-set-over.json new file mode 100644 index 0000000..50e6a98 --- /dev/null +++ b/protocol/fixtures/controls/light-set-over.json @@ -0,0 +1,18 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b2", + "item": "", + "op": "set", + "value": "150" + }, + "expect_call": { + "domain": "light", + "service": "turn_on", + "data": { + "entity_id": "light.living_room", + "brightness_pct": 100 + } + } +} diff --git a/protocol/fixtures/controls/light-set-zero.json b/protocol/fixtures/controls/light-set-zero.json new file mode 100644 index 0000000..e79c924 --- /dev/null +++ b/protocol/fixtures/controls/light-set-zero.json @@ -0,0 +1,17 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "set", + "value": "0.00" + }, + "expect_call": { + "domain": "light", + "service": "turn_off", + "data": { + "entity_id": "light.kitchen" + } + } +} diff --git a/protocol/fixtures/controls/light-set.json b/protocol/fixtures/controls/light-set.json new file mode 100644 index 0000000..5340543 --- /dev/null +++ b/protocol/fixtures/controls/light-set.json @@ -0,0 +1,18 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "set", + "value": "42.40" + }, + "expect_call": { + "domain": "light", + "service": "turn_on", + "data": { + "entity_id": "light.kitchen", + "brightness_pct": 42 + } + } +} diff --git a/protocol/fixtures/controls/light-toggle.json b/protocol/fixtures/controls/light-toggle.json new file mode 100644 index 0000000..25bfddc --- /dev/null +++ b/protocol/fixtures/controls/light-toggle.json @@ -0,0 +1,17 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "toggle", + "value": "0.00" + }, + "expect_call": { + "domain": "light", + "service": "toggle", + "data": { + "entity_id": "light.kitchen" + } + } +} diff --git a/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json b/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json new file mode 100644 index 0000000..bdfe85b --- /dev/null +++ b/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json @@ -0,0 +1,25 @@ +{ + "expect": { + "code": "coordinate_out_of_range", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 0 + }, + "blocks": [ + { + "id": "b1", + "x": 33, + "y": -2, + "name": "Solo", + "background": "#000000", + "font_size": "s", + "type": "custom", + "items": [] + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/disconnected.json b/protocol/fixtures/layouts/invalid/disconnected.json new file mode 100644 index 0000000..a6245c4 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/disconnected.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "disconnected", + "ref": "b4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 2, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/duplicate_id.json b/protocol/fixtures/layouts/invalid/duplicate_id.json new file mode 100644 index 0000000..c976924 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/duplicate_id.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "duplicate_id", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "b1", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/duplicate_position.json b/protocol/fixtures/layouts/invalid/duplicate_position.json new file mode 100644 index 0000000..2275e77 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/duplicate_position.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "duplicate_position", + "ref": "b4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": 0, + "y": 0, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_background.json b/protocol/fixtures/layouts/invalid/invalid_background.json new file mode 100644 index 0000000..abc7b13 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_background.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_background", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "red", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_entity-item.json b/protocol/fixtures/layouts/invalid/invalid_entity-item.json new file mode 100644 index 0000000..07a5134 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_entity-item.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_entity", + "ref": "i3" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "not an entity", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_entity.json b/protocol/fixtures/layouts/invalid/invalid_entity.json new file mode 100644 index 0000000..1a9c855 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_entity.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_entity", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "switch.kettle" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_font_size-item.json b/protocol/fixtures/layouts/invalid/invalid_font_size-item.json new file mode 100644 index 0000000..49f6b79 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_font_size-item.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_font_size", + "ref": "i1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": "huge" + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_font_size.json b/protocol/fixtures/layouts/invalid/invalid_font_size.json new file mode 100644 index 0000000..c5ea2a8 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_font_size.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_font_size", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "xxl", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_id.json b/protocol/fixtures/layouts/invalid/invalid_id.json new file mode 100644 index 0000000..82916a0 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_id.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_id", + "ref": "B4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "B4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_item.json b/protocol/fixtures/layouts/invalid/invalid_item.json new file mode 100644 index 0000000..aa38cd8 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_item.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_item", + "ref": "i4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "image", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_name.json b/protocol/fixtures/layouts/invalid/invalid_name.json new file mode 100644 index 0000000..a3b6402 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_name.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_name", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": " ", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json b/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json new file mode 100644 index 0000000..2576ad1 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_sleep_timeout", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 3 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_start-empty.json b/protocol/fixtures/layouts/invalid/invalid_start-empty.json new file mode 100644 index 0000000..01d9e95 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_start-empty.json @@ -0,0 +1,14 @@ +{ + "expect": { + "code": "invalid_start", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_start.json b/protocol/fixtures/layouts/invalid/invalid_start.json new file mode 100644 index 0000000..eeeb16d --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_start.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_start", + "ref": null + }, + "layout": { + "version": 1, + "start": "zz", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_structure-settings.json b/protocol/fixtures/layouts/invalid/invalid_structure-settings.json new file mode 100644 index 0000000..8cbe925 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_structure-settings.json @@ -0,0 +1,83 @@ +{ + "expect": { + "code": "invalid_structure", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": 20, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_structure-version.json b/protocol/fixtures/layouts/invalid/invalid_structure-version.json new file mode 100644 index 0000000..4192b9c --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_structure-version.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_structure", + "ref": null + }, + "layout": { + "version": 2, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_structure.json b/protocol/fixtures/layouts/invalid/invalid_structure.json new file mode 100644 index 0000000..f48243b --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_structure.json @@ -0,0 +1,14 @@ +{ + "expect": { + "code": "invalid_structure", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": {} + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_text.json b/protocol/fixtures/layouts/invalid/invalid_text.json new file mode 100644 index 0000000..a0a169e --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_text.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_text", + "ref": "i1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/invalid_type.json b/protocol/fixtures/layouts/invalid/invalid_type.json new file mode 100644 index 0000000..1201756 --- /dev/null +++ b/protocol/fixtures/layouts/invalid/invalid_type.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_type", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "gauge", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/too_many_blocks.json b/protocol/fixtures/layouts/invalid/too_many_blocks.json new file mode 100644 index 0000000..04c7dba --- /dev/null +++ b/protocol/fixtures/layouts/invalid/too_many_blocks.json @@ -0,0 +1,345 @@ +{ + "expect": { + "code": "too_many_blocks", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Block 1", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b2", + "x": 1, + "y": 0, + "name": "Block 2", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b3", + "x": 2, + "y": 0, + "name": "Block 3", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b4", + "x": 3, + "y": 0, + "name": "Block 4", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b5", + "x": 4, + "y": 0, + "name": "Block 5", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b6", + "x": 5, + "y": 0, + "name": "Block 6", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b7", + "x": 6, + "y": 0, + "name": "Block 7", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b8", + "x": 7, + "y": 0, + "name": "Block 8", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b9", + "x": 8, + "y": 0, + "name": "Block 9", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b10", + "x": 9, + "y": 0, + "name": "Block 10", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b11", + "x": 10, + "y": 0, + "name": "Block 11", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b12", + "x": 11, + "y": 0, + "name": "Block 12", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b13", + "x": 12, + "y": 0, + "name": "Block 13", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b14", + "x": 13, + "y": 0, + "name": "Block 14", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b15", + "x": 14, + "y": 0, + "name": "Block 15", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b16", + "x": 15, + "y": 0, + "name": "Block 16", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b17", + "x": 16, + "y": 0, + "name": "Block 17", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b18", + "x": 17, + "y": 0, + "name": "Block 18", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b19", + "x": 18, + "y": 0, + "name": "Block 19", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b20", + "x": 19, + "y": 0, + "name": "Block 20", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b21", + "x": 20, + "y": 0, + "name": "Block 21", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b22", + "x": 21, + "y": 0, + "name": "Block 22", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b23", + "x": 22, + "y": 0, + "name": "Block 23", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b24", + "x": 23, + "y": 0, + "name": "Block 24", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b25", + "x": 24, + "y": 0, + "name": "Block 25", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b26", + "x": 25, + "y": 0, + "name": "Block 26", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b27", + "x": 26, + "y": 0, + "name": "Block 27", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b28", + "x": 27, + "y": 0, + "name": "Block 28", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b29", + "x": 28, + "y": 0, + "name": "Block 29", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b30", + "x": 29, + "y": 0, + "name": "Block 30", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b31", + "x": 30, + "y": 0, + "name": "Block 31", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b32", + "x": 31, + "y": 0, + "name": "Block 32", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b33", + "x": 32, + "y": 0, + "name": "Block 33", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/too_many_items.json b/protocol/fixtures/layouts/invalid/too_many_items.json new file mode 100644 index 0000000..9e9391a --- /dev/null +++ b/protocol/fixtures/layouts/invalid/too_many_items.json @@ -0,0 +1,97 @@ +{ + "expect": { + "code": "too_many_items", + "ref": "b3" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + }, + { + "id": "i6", + "kind": "text", + "text": "A", + "font_size": null + }, + { + "id": "i7", + "kind": "text", + "text": "B", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/invalid/unsupported_emoji.json b/protocol/fixtures/layouts/invalid/unsupported_emoji.json new file mode 100644 index 0000000..7a673ce --- /dev/null +++ b/protocol/fixtures/layouts/invalid/unsupported_emoji.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "unsupported_emoji", + "ref": "i2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "🦄", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/protocol/fixtures/layouts/valid/emoji-variation.json b/protocol/fixtures/layouts/valid/emoji-variation.json new file mode 100644 index 0000000..7eb8b85 --- /dev/null +++ b/protocol/fixtures/layouts/valid/emoji-variation.json @@ -0,0 +1,26 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 3600 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Snow", + "background": "#FFFFFF", + "font_size": "xl", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "emoji", + "emoji": "❄️", + "font_size": null + } + ] + } + ] +} diff --git a/protocol/fixtures/layouts/valid/empty.json b/protocol/fixtures/layouts/valid/empty.json new file mode 100644 index 0000000..3cd8f9c --- /dev/null +++ b/protocol/fixtures/layouts/valid/empty.json @@ -0,0 +1,8 @@ +{ + "version": 1, + "start": null, + "settings": { + "sleep_timeout": 20 + }, + "blocks": [] +} diff --git a/protocol/fixtures/layouts/valid/reference.json b/protocol/fixtures/layouts/valid/reference.json new file mode 100644 index 0000000..2ebd691 --- /dev/null +++ b/protocol/fixtures/layouts/valid/reference.json @@ -0,0 +1,79 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] +} diff --git a/protocol/fixtures/layouts/valid/single.json b/protocol/fixtures/layouts/valid/single.json new file mode 100644 index 0000000..aabeba2 --- /dev/null +++ b/protocol/fixtures/layouts/valid/single.json @@ -0,0 +1,19 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 0 + }, + "blocks": [ + { + "id": "b1", + "x": 3, + "y": -2, + "name": "Solo", + "background": "#000000", + "font_size": "s", + "type": "custom", + "items": [] + } + ] +} diff --git a/protocol/fixtures/payloads/invalid/bad_json-array.json b/protocol/fixtures/payloads/invalid/bad_json-array.json new file mode 100644 index 0000000..2ae4a97 --- /dev/null +++ b/protocol/fixtures/payloads/invalid/bad_json-array.json @@ -0,0 +1,4 @@ +{ + "expect": "bad_json", + "text": "[1,2]" +} diff --git a/protocol/fixtures/payloads/invalid/bad_json.json b/protocol/fixtures/payloads/invalid/bad_json.json new file mode 100644 index 0000000..02556ae --- /dev/null +++ b/protocol/fixtures/payloads/invalid/bad_json.json @@ -0,0 +1,4 @@ +{ + "expect": "bad_json", + "text": "{\"v\":1," +} diff --git a/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json b/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json new file mode 100644 index 0000000..37b3dee --- /dev/null +++ b/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json @@ -0,0 +1,4 @@ +{ + "expect": "invalid_payload", + "text": "{\"v\":1,\"rev\":\"x\",\"start\":null,\"sleep\":-1,\"blocks\":[]}" +} diff --git a/protocol/fixtures/payloads/invalid/invalid_payload-widget.json b/protocol/fixtures/payloads/invalid/invalid_payload-widget.json new file mode 100644 index 0000000..a8c6e7c --- /dev/null +++ b/protocol/fixtures/payloads/invalid/invalid_payload-widget.json @@ -0,0 +1,4 @@ +{ + "expect": "invalid_payload", + "text": "{\"v\":1,\"rev\":\"x\",\"start\":\"b1\",\"sleep\":20,\"blocks\":[{\"id\":\"b1\",\"x\":0,\"y\":0,\"name\":\"A\",\"bg\":\"000000\",\"font\":\"m\",\"widget\":\"gauge\"}]}" +} diff --git a/protocol/fixtures/payloads/invalid/invalid_payload.json b/protocol/fixtures/payloads/invalid/invalid_payload.json new file mode 100644 index 0000000..d94e132 --- /dev/null +++ b/protocol/fixtures/payloads/invalid/invalid_payload.json @@ -0,0 +1,4 @@ +{ + "expect": "invalid_payload", + "text": "{\"v\":1,\"rev\":\"x\",\"start\":\"b1\",\"blocks\":[{\"id\":\"b1\"}]}" +} diff --git a/protocol/fixtures/payloads/invalid/unsupported_version.json b/protocol/fixtures/payloads/invalid/unsupported_version.json new file mode 100644 index 0000000..ba34385 --- /dev/null +++ b/protocol/fixtures/payloads/invalid/unsupported_version.json @@ -0,0 +1,4 @@ +{ + "expect": "unsupported_version", + "text": "{\"v\":2,\"rev\":\"x\",\"start\":null,\"blocks\":[]}" +} diff --git a/protocol/fixtures/payloads/valid/emoji-variation.json b/protocol/fixtures/payloads/valid/emoji-variation.json new file mode 100644 index 0000000..953dec4 --- /dev/null +++ b/protocol/fixtures/payloads/valid/emoji-variation.json @@ -0,0 +1,28 @@ +{ + "layout": "emoji-variation", + "payload": { + "v": 1, + "rev": "5387d4ea", + "start": "b1", + "sleep": 3600, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Snow", + "bg": "FFFFFF", + "font": "xl", + "widget": "custom", + "items": [ + { + "id": "i1", + "kind": "emoji", + "text": "❄", + "font": "xl" + } + ] + } + ] + } +} diff --git a/protocol/fixtures/payloads/valid/empty.json b/protocol/fixtures/payloads/valid/empty.json new file mode 100644 index 0000000..3a4e6b8 --- /dev/null +++ b/protocol/fixtures/payloads/valid/empty.json @@ -0,0 +1,10 @@ +{ + "layout": "empty", + "payload": { + "v": 1, + "rev": "c4aad3fa", + "start": null, + "sleep": 20, + "blocks": [] + } +} diff --git a/protocol/fixtures/payloads/valid/reference.json b/protocol/fixtures/payloads/valid/reference.json new file mode 100644 index 0000000..a9f0752 --- /dev/null +++ b/protocol/fixtures/payloads/valid/reference.json @@ -0,0 +1,76 @@ +{ + "layout": "reference", + "payload": { + "v": 1, + "rev": "90538742", + "start": "b1", + "sleep": 20, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "bg": "5B9E4D", + "font": "m", + "widget": "light" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "bg": "C94F3D", + "font": "m", + "widget": "light" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "bg": "4F86DD", + "font": "l", + "widget": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font": "l" + }, + { + "id": "i2", + "kind": "emoji", + "text": "👋", + "font": "xl" + }, + { + "id": "i3", + "kind": "entity", + "font": "s" + }, + { + "id": "i4", + "kind": "battery", + "font": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font": "l" + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "bg": "7B2FA0", + "font": "m", + "widget": "climate" + } + ] + } +} diff --git a/protocol/fixtures/states/all-missing.json b/protocol/fixtures/states/all-missing.json new file mode 100644 index 0000000..df191af --- /dev/null +++ b/protocol/fixtures/states/all-missing.json @@ -0,0 +1,24 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": null, + "hass_states": {}, + "updates": [ + { + "id": "b1", + "available": false + }, + { + "id": "b2", + "available": false + }, + { + "id": "i3", + "text": "—" + }, + { + "id": "b4", + "available": false + } + ] +} diff --git a/protocol/fixtures/states/climate-defaults.json b/protocol/fixtures/states/climate-defaults.json new file mode 100644 index 0000000..e0941ce --- /dev/null +++ b/protocol/fixtures/states/climate-defaults.json @@ -0,0 +1,29 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "climate.bedroom" + ], + "hass_states": { + "climate.bedroom": { + "state": "off", + "attributes": { + "temperature": null, + "current_temperature": null + } + } + }, + "updates": [ + { + "id": "b4", + "available": true, + "target": null, + "min": 7, + "max": 35, + "step": 0.5, + "unit": "°C", + "current": "—", + "action": "Off" + } + ] +} diff --git a/protocol/fixtures/states/climate-heating.json b/protocol/fixtures/states/climate-heating.json new file mode 100644 index 0000000..c4fa0ce --- /dev/null +++ b/protocol/fixtures/states/climate-heating.json @@ -0,0 +1,33 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "climate.bedroom" + ], + "hass_states": { + "climate.bedroom": { + "state": "heat", + "attributes": { + "temperature": 20.5, + "current_temperature": 19.8, + "min_temp": 7, + "max_temp": 35, + "target_temp_step": 0.5, + "hvac_action": "heating" + } + } + }, + "updates": [ + { + "id": "b4", + "available": true, + "target": 20.5, + "min": 7, + "max": 35, + "step": 0.5, + "unit": "°C", + "current": "19.8 °C", + "action": "Heating" + } + ] +} diff --git a/protocol/fixtures/states/entity-missing.json b/protocol/fixtures/states/entity-missing.json new file mode 100644 index 0000000..3d3ec18 --- /dev/null +++ b/protocol/fixtures/states/entity-missing.json @@ -0,0 +1,14 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "sensor.outdoor_temperature" + ], + "hass_states": {}, + "updates": [ + { + "id": "i3", + "text": "—" + } + ] +} diff --git a/protocol/fixtures/states/entity-precision.json b/protocol/fixtures/states/entity-precision.json new file mode 100644 index 0000000..c89b542 --- /dev/null +++ b/protocol/fixtures/states/entity-precision.json @@ -0,0 +1,28 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "sensor.outdoor_temperature" + ], + "hass_states": { + "sensor.outdoor_temperature": { + "state": "12.345", + "attributes": { + "unit_of_measurement": "°C" + } + } + }, + "registry_options": { + "sensor.outdoor_temperature": { + "sensor": { + "display_precision": 1 + } + } + }, + "updates": [ + { + "id": "i3", + "text": "12.3 °C" + } + ] +} diff --git a/protocol/fixtures/states/light-dimmable-off.json b/protocol/fixtures/states/light-dimmable-off.json new file mode 100644 index 0000000..ee2aa57 --- /dev/null +++ b/protocol/fixtures/states/light-dimmable-off.json @@ -0,0 +1,25 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.living_room" + ], + "hass_states": { + "light.living_room": { + "state": "off", + "attributes": { + "supported_color_modes": [ + "color_temp" + ] + } + } + }, + "updates": [ + { + "id": "b2", + "available": true, + "on": false, + "brightness": 0 + } + ] +} diff --git a/protocol/fixtures/states/light-dimmable-on.json b/protocol/fixtures/states/light-dimmable-on.json new file mode 100644 index 0000000..9a99452 --- /dev/null +++ b/protocol/fixtures/states/light-dimmable-on.json @@ -0,0 +1,26 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.kitchen" + ], + "hass_states": { + "light.kitchen": { + "state": "on", + "attributes": { + "brightness": 128, + "supported_color_modes": [ + "brightness" + ] + } + } + }, + "updates": [ + { + "id": "b1", + "available": true, + "on": true, + "brightness": 50 + } + ] +} diff --git a/protocol/fixtures/states/light-onoff.json b/protocol/fixtures/states/light-onoff.json new file mode 100644 index 0000000..24d35da --- /dev/null +++ b/protocol/fixtures/states/light-onoff.json @@ -0,0 +1,25 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.kitchen" + ], + "hass_states": { + "light.kitchen": { + "state": "on", + "attributes": { + "supported_color_modes": [ + "onoff" + ] + } + } + }, + "updates": [ + { + "id": "b1", + "available": true, + "on": true, + "brightness": null + } + ] +} diff --git a/protocol/fixtures/states/light-unavailable.json b/protocol/fixtures/states/light-unavailable.json new file mode 100644 index 0000000..a24b34d --- /dev/null +++ b/protocol/fixtures/states/light-unavailable.json @@ -0,0 +1,19 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.kitchen" + ], + "hass_states": { + "light.kitchen": { + "state": "unavailable", + "attributes": {} + } + }, + "updates": [ + { + "id": "b1", + "available": false + } + ] +} diff --git a/tests/protocol/__init__.py b/tests/protocol/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/protocol/test_fixtures.py b/tests/protocol/test_fixtures.py new file mode 100644 index 0000000..efa38c4 --- /dev/null +++ b/tests/protocol/test_fixtures.py @@ -0,0 +1,117 @@ +"""Executable protocol contract: shape and golden values of protocol/fixtures.""" + +import hashlib +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +FIXTURES = ROOT / "protocol" / "fixtures" +EMOJI = ROOT / "custom_components" / "ha_controller" / "emoji.json" + +LAYOUT_CODES = { + "invalid_structure", + "too_many_blocks", + "invalid_sleep_timeout", + "invalid_id", + "duplicate_id", + "coordinate_out_of_range", + "duplicate_position", + "invalid_start", + "disconnected", + "invalid_name", + "invalid_background", + "invalid_font_size", + "invalid_type", + "invalid_entity", + "too_many_items", + "invalid_item", + "invalid_text", + "unsupported_emoji", +} # the 18 codes of spec section 6 except payload_too_large + +VALID_LAYOUTS = sorted((FIXTURES / "layouts" / "valid").glob("*.json")) +INVALID_LAYOUTS = sorted((FIXTURES / "layouts" / "invalid").glob("*.json")) +VALID_PAYLOADS = sorted((FIXTURES / "payloads" / "valid").glob("*.json")) +COLORS_FILE = FIXTURES / "colors.json" + + +def _load(path: Path): + return json.loads(path.read_text("utf-8")) + + +def canonical_rev(payload: dict) -> str: + body = {k: v for k, v in payload.items() if k != "rev"} + text = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(text.encode()).hexdigest()[:8] + + +def luminance(color: str) -> float: + channels = [] + for i in (1, 3, 5): + c = int(color[i : i + 2], 16) / 255 + channels.append(c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4) + r, g, b = channels + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + +def test_emoji_list_is_well_formed(): + emoji = _load(EMOJI) + assert len(emoji) == 64 and len(set(emoji)) == 64 + assert all(len(e) == 1 for e in emoji) # one code point each + assert "️" not in "".join(emoji) + assert {"💡", "🔋", "⚡", "☀", "👋"} <= set(emoji) and "🦄" not in emoji + + +def test_all_fixtures_are_utf8_json(): + files = sorted(FIXTURES.rglob("*.json")) + assert files + for path in files: + raw = path.read_bytes() + assert not raw.startswith(b"\xef\xbb\xbf"), f"BOM in {path}" + json.loads(raw.decode("utf-8")) + + +def test_invalid_layout_fixtures_declare_known_codes(): + assert INVALID_LAYOUTS + for path in INVALID_LAYOUTS: + data = _load(path) + code, ref = data["expect"]["code"], data["expect"]["ref"] + assert code in LAYOUT_CODES, path.name + assert ref is None or isinstance(ref, str), path.name + assert path.stem == code or path.stem.startswith(code + "-"), path.name + assert isinstance(data["layout"], dict) + + +def test_every_layout_code_has_an_invalid_fixture(): + covered = {_load(p)["expect"]["code"] for p in INVALID_LAYOUTS} + assert covered == LAYOUT_CODES + + +def test_payload_revisions_match_canonical_hash(): + revs = {p.stem: _load(p)["payload"]["rev"] for p in VALID_PAYLOADS} + assert revs == { + "empty": "c4aad3fa", + "reference": "90538742", + "emoji-variation": "5387d4ea", + } + for path in VALID_PAYLOADS: + payload = _load(path)["payload"] + assert canonical_rev(payload) == payload["rev"], path.name + + +def test_fixtures_reference_existing_layouts(): + names = {p.stem for p in VALID_LAYOUTS} + checked = 0 + for folder in ("payloads/valid", "states", "controls"): + for path in sorted((FIXTURES / folder).glob("*.json")): + assert _load(path)["layout"] in names, path + checked += 1 + assert checked + + +def test_color_fixture_matches_luminance_rule(): + colors = _load(COLORS_FILE) + assert colors + for case in colors: + expected = "#000000" if luminance(case["bg"]) > 0.30 else "#FFFFFF" + assert case["text"] == expected, case From ab8b25572da8ac4872078ddb5c5dffed9924aca4 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 20:55:04 +0100 Subject: [PATCH 04/49] docs: keep the repository root free of tooling files Co-Authored-By: Claude Opus 5.5 --- .../2026-11-16-ha-controller-1-foundation.md | 85 +++++++------- .../2026-11-16-ha-controller-2-integration.md | 108 ++++++++++-------- .../plans/2026-11-16-ha-controller-3-panel.md | 78 ++++++------- .../2026-11-16-ha-controller-4-firmware.md | 42 +++---- .../2026-11-16-ha-controller-5-release.md | 68 +++++------ .../specs/2026-11-16-ha-controller-design.md | 35 +++--- 6 files changed, 213 insertions(+), 203 deletions(-) diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md index 777617c..4d40113 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md @@ -31,21 +31,22 @@ ### Task 1: Repository conventions, docs skeleton and CI **Files:** -- Create: `CLAUDE.md`, `docs/README.md`, `docs/architecture.md`, `pyproject.toml`, `requirements_test.txt`, `tests/__init__.py`, `tests/docs/__init__.py`, `tests/docs/test_links.py`, `.github/workflows/ci.yml` +- Create: `.claude/CLAUDE.md`, `docs/README.md`, `docs/architecture.md`, `.github/scripts/pyproject.toml`, `.github/scripts/requirements.txt`, `.github/scripts/tests/__init__.py`, `.github/scripts/tests/test_docs_links.py`, `.github/workflows/ci.yml` - Modify: `README.md` (rewrite in English), `.gitignore` **Interfaces:** - Produces: - - `pyproject.toml` with `[tool.pytest.ini_options] testpaths = ["tests"]`, `asyncio_mode = "auto"`, and `[tool.ruff] target-version = "py314"`, `line-length = 100`, lint rules `E,F,I,UP,B`. - - `requirements_test.txt` (`pytest`, `ruff`). Plan 2 replaces `pytest` with the Home Assistant test harness. - - `.github/workflows/ci.yml` with a single job `python`. Later plans add jobs. + - `.github/scripts/pyproject.toml` with `[tool.pytest.ini_options] testpaths = ["tests"]` and `[tool.ruff] target-version = "py314"`, `line-length = 100`, lint rules `E,F,I,UP,B`. + - `.github/scripts/requirements.txt` (`pytest`, `ruff`) for the repository checks. Plan 2 gives the integration its own test requirements under `custom_components/`. + - `.github/workflows/ci.yml` with a single job `repo-checks`. Later plans add jobs. + - The repository root keeps no files except `README.md`, `hacs.json` (plan 2) and `.gitignore`. - `docs/README.md` as the docs index. Later plans add links. - - `CLAUDE.md` with a `## Commands` table and a `## Skills and agents` section. Later plans append rows. + - `.claude/CLAUDE.md` with a `## Commands` table and a `## Skills and agents` section. Later plans append rows. -- [ ] **Step 1: Write the failing tests** in `tests/docs/test_links.py`. +- [ ] **Step 1: Write the failing tests** in `.github/scripts/tests/test_docs_links.py`. ```python -DOC_ROOTS = ["README.md", "CLAUDE.md", "docs"] # docs/superpowers/** is excluded +DOC_ROOTS = ["README.md", ".claude/CLAUDE.md", "docs"] # docs/superpowers/** is excluded def test_relative_links_resolve(): # For every markdown link [text](target) whose target does not start with @@ -60,7 +61,7 @@ def test_docs_index_lists_every_doc(): - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/docs -v` +Run: `pytest .github/scripts/tests -v` Expected: FAIL (`docs/README.md` is missing). - [ ] **Step 3: Write the docs and config** @@ -80,33 +81,33 @@ Expected: FAIL (`docs/README.md` is missing). - the hello → layout/states handshake; - controls → service calls; - firmware updates. - - **`CLAUDE.md`:** + - **`.claude/CLAUDE.md`:** - Title "HA Controller — guidance for Claude Code" and a two-line purpose. - `## Rules`: - English only. - - One version for the whole repo; change it only with `python scripts/versioning.py bump X.Y.Z` (added in plan 5). - - The protocol is defined in `docs/protocol.md` and pinned by `protocol/fixtures/`. + - One version for the whole repo; change it only with `python .github/scripts/versioning.py bump X.Y.Z` (added in plan 5). + - The protocol is defined in `docs/protocol/README.md` and pinned by `docs/protocol/fixtures/`. - TDD. - Never commit `esphome/secrets.yaml`. - Specs and plans live in `docs/superpowers/`. - `## Repository map`: the spec §3 table. - - `## Commands`: `pytest`, `ruff check .`. + - `## Commands`: `pytest .github/scripts/tests`, `ruff check .github/scripts`. - `## Skills and agents`: empty list. - - **`.gitignore`:** keep `.DS_Store`. Add `__pycache__/`, `.pytest_cache/`, `.ruff_cache/`, `.venv*/`, `node_modules/`, `frontend/coverage/`, `custom_components/ha_controller/frontend/*.js`, `esphome/.esphome/`, `esphome/secrets.yaml`, `build/`, `dist/`, `site/`. + - **`.gitignore`:** keep `.DS_Store`. Add `__pycache__/`, `.pytest_cache/`, `.ruff_cache/`, `.venv*/`, `node_modules/`, `custom_components/ha_controller/frontend/coverage/`, `.superpowers/`, `esphome/.esphome/`, `esphome/secrets.yaml`, `build/`, `dist/`, `site/`. - [ ] **Step 4: Run the tests and lint** -Run: `pytest tests/docs -v && ruff check .` +Run: `pytest .github/scripts/tests -v && ruff check .github/scripts` Expected: PASS, no lint findings. - [ ] **Step 5: Add CI.** In `.github/workflows/ci.yml`, workflow `CI`: - Triggers: `push` to `main` and `pull_request`. - - Job `python` on `ubuntu-latest`: `actions/checkout@v4`, `actions/setup-python@v5` with `python-version: "3.14"`, `pip install -r requirements_test.txt`, `ruff check .`, `pytest`. + - Job `repo-checks` on `ubuntu-latest`: `actions/checkout@v4`, `actions/setup-python@v5` with `python-version: "3.14"`, `pip install -r .github/scripts/requirements.txt`, `ruff check .github/scripts`, `pytest .github/scripts/tests`. - [ ] **Step 6: Commit** ```bash -git add README.md CLAUDE.md docs/README.md docs/architecture.md pyproject.toml requirements_test.txt tests .gitignore .github/workflows/ci.yml +git add README.md .claude/CLAUDE.md docs/README.md docs/architecture.md .github/scripts .gitignore .github/workflows/ci.yml git commit -m "chore: add repository conventions, docs skeleton and CI" ``` @@ -116,21 +117,21 @@ git commit -m "chore: add repository conventions, docs skeleton and CI" **Files:** - Create: - - `docs/protocol.md`, `protocol/README.md`, `custom_components/ha_controller/emoji.json` - - `protocol/fixtures/**` (see the tables below) - - `tests/protocol/__init__.py`, `tests/protocol/test_fixtures.py` + - `docs/protocol/README.md`, `docs/protocol/README.md`, `custom_components/ha_controller/emoji.json` + - `docs/protocol/fixtures/**` (see the tables below) + - `.github/scripts/tests/__init__.py`, `.github/scripts/tests/test_protocol_fixtures.py` - `.claude/skills/protocol-change/SKILL.md`, `.claude/agents/protocol-guardian.md` -- Modify: `docs/README.md` (link `protocol.md`), `CLAUDE.md` (skills and agents list) +- Modify: `docs/README.md` (link `protocol.md`), `.claude/CLAUDE.md` (skills and agents list) **Interfaces:** - Produces (consumed by plans 2, 3 and 4). All fixture files are UTF-8 JSON without a BOM. - `custom_components/ha_controller/emoji.json`: a JSON array of the 64 strings below, in this order: `💡 🔥 ❄ 🌡 💧 🌬 ☀ 🌙 ⭐ ☁ ⛅ 🌧 ⚡ 🔋 🔌 🏠 🛋 🛏 🛁 🚿 🍳 🍽 ☕ 🍷 🧺 🪴 🚪 🪟 🔒 🔓 🔑 🔔 🔕 🔊 🔇 🎵 📺 🎮 💻 📱 ⏰ 📅 🚗 🚲 🐶 🐱 👶 👋 👍 ❤ 😀 😴 🎉 🎄 ✅ ❌ ⚠ ℹ ▶ ⏸ ♻ 🌀 🧊 🏡` - - `protocol/fixtures/layouts/valid/.json`: a stored layout. - - `protocol/fixtures/layouts/invalid/.json`: `{"expect": {"code": str, "ref": str | null}, "layout": {...}}`. The stem equals `code` or starts with `code-`. - - `protocol/fixtures/payloads/valid/.json`: `{"layout": "", "payload": {...}}`. - - `protocol/fixtures/payloads/invalid/.json`: `{"expect": "bad_json" | "unsupported_version" | "invalid_payload", "text": ""}`. - - `protocol/fixtures/states/.json`: + - `docs/protocol/fixtures/layouts/valid/.json`: a stored layout. + - `docs/protocol/fixtures/layouts/invalid/.json`: `{"expect": {"code": str, "ref": str | null}, "layout": {...}}`. The stem equals `code` or starts with `code-`. + - `docs/protocol/fixtures/payloads/valid/.json`: `{"layout": "", "payload": {...}}`. + - `docs/protocol/fixtures/payloads/invalid/.json`: `{"expect": "bad_json" | "unsupported_version" | "invalid_payload", "text": ""}`. + - `docs/protocol/fixtures/states/.json`: ```json { @@ -144,10 +145,10 @@ git commit -m "chore: add repository conventions, docs skeleton and CI" ``` `registry_options` is optional; `updates` lists the expected update objects. - - `protocol/fixtures/controls/.json`: `{"layout": "reference", "hass_states": {...}, "event": {"block", "item", "op", "value"}, "expect_call": {"domain", "service", "data"} | null}`. - - `protocol/fixtures/colors.json`: `[{"bg": "#RRGGBB", "text": "#000000" | "#FFFFFF"}]`. + - `docs/protocol/fixtures/controls/.json`: `{"layout": "reference", "hass_states": {...}, "event": {"block", "item", "op", "value"}, "expect_call": {"domain", "service", "data"} | null}`. + - `docs/protocol/fixtures/colors.json`: `[{"bg": "#RRGGBB", "text": "#000000" | "#FFFFFF"}]`. -- [ ] **Step 1: Write the failing tests** in `tests/protocol/test_fixtures.py`. Local helpers: `canonical_rev(payload) -> str` and `luminance(hex) -> float` (spec §5.5/§7.3). +- [ ] **Step 1: Write the failing tests** in `.github/scripts/tests/test_protocol_fixtures.py`. Local helpers: `canonical_rev(payload) -> str` and `luminance(hex) -> float` (spec §5.5/§7.3). ```python def test_emoji_list_is_well_formed(): @@ -157,7 +158,7 @@ def test_emoji_list_is_well_formed(): assert "️" not in "".join(emoji) assert {"💡", "🔋", "⚡", "☀", "👋"} <= set(emoji) and "🦄" not in emoji -def test_all_fixtures_are_utf8_json(): ... # every protocol/fixtures/**/*.json: no BOM, json.loads ok +def test_all_fixtures_are_utf8_json(): ... # every docs/protocol/fixtures/**/*.json: no BOM, json.loads ok def test_invalid_layout_fixtures_declare_known_codes(): # expect.code in the 18 codes of spec §6 except payload_too_large @@ -177,7 +178,7 @@ def test_color_fixture_matches_luminance_rule(): - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/protocol -v` +Run: `pytest .github/scripts/tests -v` Expected: FAIL (the files are missing). - [ ] **Step 3: Write `emoji.json` and the fixtures.** @@ -291,13 +292,13 @@ Expected: FAIL (the files are missing). - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/protocol -v` +Run: `pytest .github/scripts/tests -v` Expected: PASS. - [ ] **Step 5: Write the protocol doc and guidance** - - **`docs/protocol.md`:** spec §6 and §7, verbatim, under the heading "Device protocol v1". Add a closing "Fixtures" section with the relative link `../protocol/README.md`. - - **`protocol/README.md`:** - - Who reads each fixture folder: pytest in `tests/integration`, vitest in `frontend/test`, doctest in `esphome/tests`. + - **`docs/protocol/README.md`:** spec §6 and §7, verbatim, under the heading "Device protocol v1". Add a closing "Fixtures" section with the relative link `../protocol/README.md`. + - **`docs/protocol/README.md`:** + - Who reads each fixture folder: pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test`, doctest in `esphome/tests`. - The rule "one broken rule per invalid fixture". - The canonical-revision snippet: @@ -309,28 +310,28 @@ Expected: PASS. - `description:` "Use when changing anything that crosses the Home Assistant ↔ screen boundary: layout fields, validation rules, payload keys, state update fields, events, actions, emoji list or limits." - Body, a numbered checklist: 1. Classify the change. The C++ parser rejects unknown `widget`/`kind`/`font` values, so any new value is breaking: bump `PROTOCOL_VERSION` in `custom_components/ha_controller/const.py` and in the firmware's `ha_controller.h`. - 2. Edit `docs/protocol.md` first. - 3. Update `protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet. - 4. Update the Python code (`layout.py`, `compiler.py`, `states.py`, `controls.py`), the TypeScript model (`frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). - 5. Run `pytest`, `npm --prefix frontend test`, the host C++ tests and `esphome compile`. + 2. Edit `docs/protocol/README.md` first. + 3. Update `docs/protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet. + 4. Update the Python code (`layout.py`, `compiler.py`, `states.py`, `controls.py`), the TypeScript model (`custom_components/ha_controller/frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). + 5. Run `pytest custom_components/ha_controller/tests`, `pytest .github/scripts/tests`, `npm --prefix custom_components/ha_controller/frontend test`, the host C++ tests and `esphome compile`. 6. Ask the `protocol-guardian` agent to review. - **`.claude/agents/protocol-guardian.md`:** - Frontmatter `name: protocol-guardian`, `tools: Read, Grep, Glob, Bash`. - - `description:` "Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol.md, protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging." + - `description:` "Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol/README.md, docs/protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging." - Body: - A checklist: field names, error codes, limits and constants identical in all places; fixtures updated; golden revs recomputed; `PROTOCOL_VERSION` bumped on breaking changes; docs updated. - Output: a list of `file:line — inconsistency — fix`, or "Protocol consistent". - **`docs/README.md`:** add a `protocol.md` bullet. - - **`CLAUDE.md`:** list the skill and the agent under `## Skills and agents`. + - **`.claude/CLAUDE.md`:** list the skill and the agent under `## Skills and agents`. - [ ] **Step 6: Run the whole suite** -Run: `pytest -v && ruff check .` +Run: `pytest .github/scripts/tests -v && ruff check .github/scripts` Expected: PASS. - [ ] **Step 7: Commit** ```bash -git add docs/protocol.md docs/README.md protocol custom_components/ha_controller/emoji.json tests/protocol .claude CLAUDE.md +git add docs/protocol docs/README.md custom_components/ha_controller/emoji.json .github/scripts/tests .claude .claude/CLAUDE.md git commit -m "feat(protocol): add protocol v1 contract, shared fixtures and guidance" ``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md index 665b399..7968284 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md @@ -5,7 +5,7 @@ **Goal:** Build the `ha_controller` custom integration: config flow, layout validation and compilation, state builders, the sync engine that talks to the screen through ESPHome actions and events, control mapping, the websocket API and the sidebar panel registration. **Architecture:** -- **Pure modules:** `layout.py`, `compiler.py`, `states.py` and `controls.py` hold the protocol logic. They are tested against `protocol/fixtures/`. +- **Pure modules:** `layout.py`, `compiler.py`, `states.py` and `controls.py` hold the protocol logic. They are tested against `docs/protocol/fixtures/`. - **`ScreenController`:** one per config entry. It wires those modules to Home Assistant: storage, event listeners filtered by `device_id`, entity tracking, and calls to the screen's `esphome._` services. - **`websocket.py` and `panel.py`:** expose the controller to the panel built in plan 3. @@ -38,10 +38,11 @@ **Files:** - Create: - `custom_components/ha_controller/`: `__init__.py`, `const.py`, `config_flow.py`, `manifest.json`, `strings.json`, `translations/en.json`, `brand/icon.png`, `brand/icon@2x.png` - - `scripts/make_brand_icon.py`, `hacs.json` - - `tests/conftest.py`, `tests/integration/__init__.py`, `tests/integration/helpers.py`, `tests/integration/test_config_flow.py` + - `.github/scripts/make_brand_icon.py`, `hacs.json` + - `custom_components/ha_controller/tests/conftest.py`, `custom_components/ha_controller/tests/__init__.py`, `custom_components/ha_controller/tests/helpers.py`, `custom_components/ha_controller/tests/test_config_flow.py` - `.github/workflows/validate.yml` -- Modify: `requirements_test.txt`, `CLAUDE.md` (commands) + - `custom_components/pyproject.toml`, `custom_components/requirements_test.txt`, `custom_components/__init__.py` (empty) +- Modify: `.github/scripts/requirements.txt` (add `pillow`), `.github/workflows/ci.yml` (job `integration`), `.claude/CLAUDE.md` (commands) **Interfaces:** - Produces: @@ -54,14 +55,14 @@ - Timings: `ONLINE_TIMEOUT = timedelta(seconds=150)`, `PUSH_RETRY = timedelta(seconds=300)`, `STATE_COALESCE_SECONDS = 0.2`, `INSTALL_TIMEOUT = 300`, `AUTO_UPDATE_RETRY = timedelta(seconds=3600)`. - Panel: `PANEL_URL_PATH = "ha-controller"`, `PANEL_COMPONENT = "ha-controller-panel"`, `PANEL_TITLE = "HA Controller"`, `PANEL_ICON = "mdi:remote"`, `STATIC_URL = "/ha_controller_static"`. - Release URLs: `FIRMWARE_BASE_URL = "https://pyxel-dev.github.io/HA-controller/firmware"`, `RELEASE_URL = "https://github.com/pyxel-dev/HA-controller/releases/tag/v{version}"`. - - **`tests/integration/helpers.py`:** + - **`custom_components/ha_controller/tests/helpers.py`:** - `async def register_screen(hass, *, name="HA Controller", manufacturer=MANUFACTURER, model=MODEL, mac="aa:bb:cc:dd:ee:ff") -> dr.DeviceEntry`. It adds an `esphome` `MockConfigEntry` and a device with `connections={(dr.CONNECTION_NETWORK_MAC, mac)}`. - `async def setup_screen(hass, device) -> MockConfigEntry`. It adds the `ha_controller` entry with `data={"device_id": device.id}` and `unique_id=device.id`, sets it up, and waits. - `NODE = "ha-controller-aabbcc"`. - `def hello(device, **overrides) -> dict`: a default hello for `NODE`, version `"0.1.0"`, protocol `"1"`, revision `"none"`, reason `"connected"`. - - `def load_fixture(*parts) -> Any`: reads `protocol/fixtures/...`. + - `def load_fixture(*parts) -> Any`: reads `docs/protocol/fixtures/...`. -- [ ] **Step 1: Write the failing tests** in `tests/integration/test_config_flow.py`, plus `tests/conftest.py` with an autouse `auto_enable_custom_integrations(enable_custom_integrations)` fixture. +- [ ] **Step 1: Write the failing tests** in `custom_components/ha_controller/tests/test_config_flow.py`, plus `custom_components/ha_controller/tests/conftest.py` with an autouse `auto_enable_custom_integrations(enable_custom_integrations)` fixture. ```python async def test_user_step_shows_device_selector(hass): ... # form, step_id "user", errors {} @@ -79,11 +80,16 @@ async def test_strings_match_english_translation(): # strings. - [ ] **Step 2: Run the tests to verify they fail** -Run: `pip install -r requirements_test.txt && pytest tests/integration/test_config_flow.py -v` +Run: `pip install -r custom_components/requirements_test.txt && pytest custom_components/ha_controller/tests/test_config_flow.py -v` Expected: FAIL (`ModuleNotFoundError` / integration not found). - [ ] **Step 3: Implement the skeleton.** - - **`requirements_test.txt`:** `pytest-homeassistant-custom-component==0.13.375`, `ruff`, `pillow`. + - **`custom_components/requirements_test.txt`:** `pytest-homeassistant-custom-component==0.13.375`, `ruff`. + - **`custom_components/pyproject.toml`:** + - `[tool.pytest.ini_options]`: `testpaths = ["ha_controller/tests"]`, `pythonpath = [".."]`, `asyncio_mode = "auto"`, `asyncio_default_fixture_loop_scope = "function"`. + - `[tool.ruff]`: `target-version = "py314"`, `line-length = 100`, lint rules `E,F,I,UP,B`. + - **`custom_components/__init__.py`:** empty. pytest then imports the tests as `custom_components.ha_controller.tests.*`, so the integration is never imported a second time under the name `ha_controller`. Tests import the integration only as `custom_components.ha_controller`. + - **`.github/scripts/requirements.txt`:** add `pillow`, for the brand icon script. - **`manifest.json`**, keys in hassfest order: ```json @@ -123,7 +129,7 @@ Expected: FAIL (`ModuleNotFoundError` / integration not found). - Error: `not_ha_controller` "This device is not an HA Controller screen." - Abort: `already_configured` "This screen is already set up." - **`hacs.json`:** `{"name": "HA Controller", "homeassistant": "2026.10.0"}`. - - **`scripts/make_brand_icon.py`:** a Pillow script that writes `brand/icon.png` (256×256) and `brand/icon@2x.png` (512×512), scaled from a 512 design: + - **`.github/scripts/make_brand_icon.py`:** a Pillow script that writes `brand/icon.png` (256×256) and `brand/icon@2x.png` (512×512), scaled from a 512 design: - transparent background; - a filled circle `#111827` with radius 240; - a ring `#374151`, width 36, radius 170; @@ -134,20 +140,22 @@ Expected: FAIL (`ModuleNotFoundError` / integration not found). - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/integration/test_config_flow.py -v && ruff check .` +Run: `pytest custom_components/ha_controller/tests/test_config_flow.py -v && ruff check custom_components` Expected: PASS. -- [ ] **Step 5: Add validation CI** in `.github/workflows/validate.yml`: +- [ ] **Step 5: Add CI.** + - Add job `integration` to `.github/workflows/ci.yml`: setup-python 3.14, `pip install -r custom_components/requirements_test.txt`, `ruff check custom_components`, `pytest custom_components/ha_controller/tests`. + - Create `.github/workflows/validate.yml`: - Triggers: `push`, `pull_request`, `schedule` (`cron: "0 0 * * *"`) and `workflow_dispatch`. - Job `hassfest`: checkout, then `home-assistant/actions/hassfest@master`. - Job `hacs`: `hacs/action@main` with `category: integration`. - If HACS reports the repository description or topics checks, the owner sets them once on GitHub. Description: "Home Assistant remote on the Waveshare ESP32-S3 1.75\" round AMOLED". Topics: `home-assistant`, `hacs`, `esphome`, `integration`. - - Add to the `CLAUDE.md` commands: `pytest tests/integration` and `python scripts/make_brand_icon.py`. + - Add to the `.claude/CLAUDE.md` commands: `pytest custom_components/ha_controller/tests` and `python .github/scripts/make_brand_icon.py`. - [ ] **Step 6: Commit** ```bash -git add custom_components/ha_controller scripts/make_brand_icon.py hacs.json requirements_test.txt tests .github/workflows/validate.yml CLAUDE.md +git add custom_components/ha_controller .github/scripts/make_brand_icon.py hacs.json custom_components/requirements_test.txt custom_components/pyproject.toml custom_components/__init__.py .github/scripts/requirements.txt .github/workflows/ci.yml .github/workflows/validate.yml .claude/CLAUDE.md git commit -m "feat(integration): add integration skeleton and config flow" ``` @@ -156,7 +164,7 @@ git commit -m "feat(integration): add integration skeleton and config flow" ### Task 2: Layout validation **Files:** -- Create: `custom_components/ha_controller/layout.py`, `tests/integration/test_layout.py` +- Create: `custom_components/ha_controller/layout.py`, `custom_components/ha_controller/tests/test_layout.py` **Interfaces:** - Produces: @@ -191,7 +199,7 @@ def test_sleep_timeout_bounds(value, ok): ... # reference with settings.sleep_t - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_layout.py -v` +Run: `pytest custom_components/ha_controller/tests/test_layout.py -v` Expected: FAIL (`ImportError`). - [ ] **Step 3: Implement `validate_layout`.** It runs in three phases, following spec §6. @@ -215,13 +223,13 @@ Expected: FAIL (`ImportError`). - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/integration/test_layout.py -v` +Run: `pytest custom_components/ha_controller/tests/test_layout.py -v` Expected: PASS (all 4 valid and 23 invalid fixtures, plus the unit tests). - [ ] **Step 5: Commit** ```bash -git add custom_components/ha_controller/layout.py tests/integration/test_layout.py +git add custom_components/ha_controller/layout.py custom_components/ha_controller/tests/test_layout.py git commit -m "feat(integration): validate layouts against protocol rules" ``` @@ -230,7 +238,7 @@ git commit -m "feat(integration): validate layouts against protocol rules" ### Task 3: Layout compiler **Files:** -- Create: `custom_components/ha_controller/compiler.py`, `tests/integration/test_compiler.py` +- Create: `custom_components/ha_controller/compiler.py`, `custom_components/ha_controller/tests/test_compiler.py` **Interfaces:** - Consumes: `normalize_emoji` (Task 2). @@ -259,20 +267,20 @@ def test_huge_layout_exceeds_payload_limit(): - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_compiler.py -v` +Run: `pytest custom_components/ha_controller/tests/test_compiler.py -v` Expected: FAIL. - [ ] **Step 3: Implement the three functions in `compiler.py`, following spec §7.3.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/integration/test_compiler.py -v` +Run: `pytest custom_components/ha_controller/tests/test_compiler.py -v` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add custom_components/ha_controller/compiler.py tests/integration/test_compiler.py +git add custom_components/ha_controller/compiler.py custom_components/ha_controller/tests/test_compiler.py git commit -m "feat(integration): compile layouts into device payloads" ``` @@ -281,7 +289,7 @@ git commit -m "feat(integration): compile layouts into device payloads" ### Task 4: State builders **Files:** -- Create: `custom_components/ha_controller/states.py`, `tests/integration/test_states.py` +- Create: `custom_components/ha_controller/states.py`, `custom_components/ha_controller/tests/test_states.py` **Interfaces:** - Produces: @@ -315,20 +323,20 @@ def test_chunk_updates_keeps_oversize_update_alone(): ... - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_states.py -v` +Run: `pytest custom_components/ha_controller/tests/test_states.py -v` Expected: FAIL. - [ ] **Step 3: Implement the builders in `states.py`, following spec §7.7.** `—` is U+2014. The climate unit is `hass.config.units.temperature_unit`. - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/integration/test_states.py -v` +Run: `pytest custom_components/ha_controller/tests/test_states.py -v` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add custom_components/ha_controller/states.py tests/integration/test_states.py +git add custom_components/ha_controller/states.py custom_components/ha_controller/tests/test_states.py git commit -m "feat(integration): build screen state updates" ``` @@ -337,7 +345,7 @@ git commit -m "feat(integration): build screen state updates" ### Task 5: Layout store and ScreenController sync engine **Files:** -- Create: `custom_components/ha_controller/store.py`, `custom_components/ha_controller/controller.py`, `tests/integration/test_controller.py` +- Create: `custom_components/ha_controller/store.py`, `custom_components/ha_controller/controller.py`, `custom_components/ha_controller/tests/test_controller.py` - Modify: `custom_components/ha_controller/__init__.py` **Interfaces:** @@ -383,7 +391,7 @@ async def test_status_reports_device(hass): ... # - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_controller.py -v` +Run: `pytest custom_components/ha_controller/tests/test_controller.py -v` Expected: FAIL. - [ ] **Step 3: Implement the controller, following spec §7.5.** @@ -399,13 +407,13 @@ Expected: FAIL. - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/integration -v` +Run: `pytest custom_components/ha_controller/tests -v` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add custom_components/ha_controller tests/integration/test_controller.py +git add custom_components/ha_controller custom_components/ha_controller/tests/test_controller.py git commit -m "feat(integration): sync layouts and states with the screen" ``` @@ -414,7 +422,7 @@ git commit -m "feat(integration): sync layouts and states with the screen" ### Task 6: Control events **Files:** -- Create: `custom_components/ha_controller/controls.py`, `tests/integration/test_controls.py` +- Create: `custom_components/ha_controller/controls.py`, `custom_components/ha_controller/tests/test_controls.py` - Modify: `custom_components/ha_controller/controller.py` **Interfaces:** @@ -439,20 +447,20 @@ async def test_service_error_is_swallowed(hass, caplog): ... # registered light - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_controls.py -v` +Run: `pytest custom_components/ha_controller/tests/test_controls.py -v` Expected: FAIL. - [ ] **Step 3: Implement `resolve_control` and the controller handler.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/integration -v` +Run: `pytest custom_components/ha_controller/tests -v` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add custom_components/ha_controller tests/integration/test_controls.py +git add custom_components/ha_controller custom_components/ha_controller/tests/test_controls.py git commit -m "feat(integration): map screen controls to service calls" ``` @@ -461,7 +469,7 @@ git commit -m "feat(integration): map screen controls to service calls" ### Task 7: Websocket API **Files:** -- Create: `custom_components/ha_controller/websocket.py`, `tests/integration/test_websocket.py` +- Create: `custom_components/ha_controller/websocket.py`, `custom_components/ha_controller/tests/test_websocket.py` - Modify: `custom_components/ha_controller/__init__.py` (call `async_register_websocket(hass)` in `async_setup`) **Interfaces:** @@ -486,20 +494,20 @@ async def test_commands_require_admin(hass, hass_ws_client, hass_admin_user): .. - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_websocket.py -v` +Run: `pytest custom_components/ha_controller/tests/test_websocket.py -v` Expected: FAIL. - [ ] **Step 3: Implement `websocket.py`.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/integration -v` +Run: `pytest custom_components/ha_controller/tests -v` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add custom_components/ha_controller tests/integration/test_websocket.py +git add custom_components/ha_controller custom_components/ha_controller/tests/test_websocket.py git commit -m "feat(integration): add websocket API for the panel" ``` @@ -509,15 +517,15 @@ git commit -m "feat(integration): add websocket API for the panel" **Files:** - Create: - - `custom_components/ha_controller/panel.py`, `custom_components/ha_controller/frontend/.gitkeep` - - `tests/integration/test_panel.py` + - `custom_components/ha_controller/panel.py` + - `custom_components/ha_controller/tests/test_panel.py` - `docs/development.md`, `.claude/agents/ha-integration-reviewer.md` -- Modify: `custom_components/ha_controller/__init__.py`, `docs/README.md`, `CLAUDE.md` +- Modify: `custom_components/ha_controller/__init__.py`, `docs/README.md`, `.claude/CLAUDE.md` **Interfaces:** -- Consumes: the plan 3 bundle path `custom_components/ha_controller/frontend/ha-controller-panel.js`. +- Consumes: the plan 3 bundle path `custom_components/ha_controller/frontend/dist/ha-controller-panel.js`. - Produces: - - `async def async_register_panel(hass, version: str) -> None`. It registers `StaticPathConfig(STATIC_URL, /frontend, True)` once per Home Assistant run, guarded by a `hass.data` flag. If `PANEL_URL_PATH` is not already in `hass.data[frontend.DATA_PANELS]`, it registers the panel with: + - `async def async_register_panel(hass, version: str) -> None`. It registers `StaticPathConfig(f"{STATIC_URL}/ha-controller-panel.js", /frontend/dist/ha-controller-panel.js, True)` once per Home Assistant run, guarded by a `hass.data` flag. This is a file route, so a missing bundle never breaks setup. If `PANEL_URL_PATH` is not already in `hass.data[frontend.DATA_PANELS]`, it registers the panel with: ```python await panel_custom.async_register_panel( @@ -546,26 +554,26 @@ async def test_static_path_registered_once(hass): ... # patch hass - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_panel.py -v` +Run: `pytest custom_components/ha_controller/tests/test_panel.py -v` Expected: FAIL. - [ ] **Step 3: Implement `panel.py` and wire it into `async_setup_entry` / `async_unload_entry`.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest -v && ruff check .` +Run: `pytest custom_components/ha_controller/tests -v && ruff check custom_components` Expected: PASS. - [ ] **Step 5: Write the docs and the reviewer agent.** - **`docs/development.md`:** create it with sections "Prerequisites" (Python 3.14, Node 24, ESPHome; the later plans fill these in) and "Home Assistant integration". The integration section covers: - - venv setup and `pip install -r requirements_test.txt`; - - `pytest`; + - venv setup and `pip install -r custom_components/requirements_test.txt`; + - `pytest custom_components/ha_controller/tests`; - running a development Home Assistant, by symlinking `custom_components/ha_controller` into `/custom_components/`; - how hello / set_layout traffic shows up under Developer tools › Events (`esphome.ha_controller_hello`). - **`docs/README.md`:** link the new doc. - **`.claude/agents/ha-integration-reviewer.md`:** - Frontmatter `name: ha-integration-reviewer`, `tools: Read, Grep, Glob, Bash`. - - `description:` "Reviews changes under custom_components/ha_controller and tests/integration against Home Assistant development rules. Use before merging integration changes." + - `description:` "Reviews changes under custom_components/ha_controller and custom_components/ha_controller/tests against Home Assistant development rules. Use before merging integration changes." - Checklist: - async only, with no blocking I/O in the loop; - `entry.runtime_data`, with no new `hass.data` globals beyond the panel flags; @@ -577,11 +585,11 @@ Expected: PASS. - every branch tested; - protocol changes routed to the `protocol-change` skill. - Output: findings as `file:line — issue — fix`. - - **`CLAUDE.md`:** list the agent. + - **`.claude/CLAUDE.md`:** list the agent. - [ ] **Step 6: Commit** ```bash -git add custom_components/ha_controller tests/integration/test_panel.py docs .claude CLAUDE.md +git add custom_components/ha_controller custom_components/ha_controller/tests/test_panel.py docs .claude .claude/CLAUDE.md git commit -m "feat(integration): register the sidebar panel" ``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md index c214665..350c7bf 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md @@ -4,8 +4,8 @@ **Goal:** Build the Home Assistant sidebar panel where the user edits each screen's block map. The map is laid out exactly the way navigation works on the screen ([reference screenshot](../specs/assets/editor-reference.png)). -**Architecture:** A Lit + TypeScript web component bundled by Vite into one ES module. Vite writes it to `custom_components/ha_controller/frontend/ha-controller-panel.js`, which plan 2's `panel.py` serves. -- **Model:** pure functions in `src/model/` hold all editing logic (grid, validation, edits, colours, emoji). Vitest tests them against `protocol/fixtures/`. +**Architecture:** A Lit + TypeScript web component bundled by Vite into one ES module. Vite writes it to `custom_components/ha_controller/frontend/dist/ha-controller-panel.js`, which plan 2's `panel.py` serves. +- **Model:** pure functions in `src/model/` hold all editing logic (grid, validation, edits, colours, emoji). Vitest tests them against `docs/protocol/fixtures/`. - **Components:** they only render and emit events. - **Websocket:** the panel talks to the integration through plan 2's commands. - **Dev harness:** `npm run dev` runs the panel against an in-memory mock `hass`. @@ -27,7 +27,7 @@ - `--divider-color` (fallback `rgba(0,0,0,.12)`) - `--error-color` (fallback `#db4437`) - **Strings:** all UI strings are in English and live in `src/messages.ts`. -- **Versioning:** `frontend/package.json` `version` is `0.1.0`; plan 5's versioning script keeps it in sync. +- **Versioning:** `custom_components/ha_controller/frontend/package.json` `version` is `0.1.0`; plan 5's versioning script keeps it in sync. ## Review Focus @@ -43,10 +43,10 @@ **Files:** - Create: - - `frontend/package.json`, `frontend/package-lock.json`, `frontend/tsconfig.json`, `frontend/vite.config.ts` - - `frontend/src/types.ts`, `frontend/src/model/grid.ts`, `frontend/src/model/validate.ts`, `frontend/src/model/emoji.ts` - - `frontend/test/fixtures.ts`, `frontend/test/grid.test.ts`, `frontend/test/validate.test.ts` -- Modify: `.github/workflows/ci.yml` (job `frontend`), `CLAUDE.md` (commands) + - `custom_components/ha_controller/frontend/package.json`, `custom_components/ha_controller/frontend/package-lock.json`, `custom_components/ha_controller/frontend/tsconfig.json`, `custom_components/ha_controller/frontend/vite.config.ts` + - `custom_components/ha_controller/frontend/src/types.ts`, `custom_components/ha_controller/frontend/src/model/grid.ts`, `custom_components/ha_controller/frontend/src/model/validate.ts`, `custom_components/ha_controller/frontend/src/model/emoji.ts` + - `custom_components/ha_controller/frontend/test/fixtures.ts`, `custom_components/ha_controller/frontend/test/grid.test.ts`, `custom_components/ha_controller/frontend/test/validate.test.ts` +- Modify: `.github/workflows/ci.yml` (job `frontend`), `.claude/CLAUDE.md` (commands) **Interfaces:** - Produces: @@ -67,8 +67,8 @@ - `canDelete(layout, id): {ok: true} | {ok: false, reason: "start" | "disconnects"}` - `gridBounds(cells: Cell[]): {minX, maxX, minY, maxY}` - **`model/validate.ts`:** `validateLayout(layout: unknown, emoji: ReadonlySet): LayoutError[]`. Same phases and order as plan 2 Task 2. - - **`model/emoji.ts`:** `SUPPORTED_EMOJI: readonly string[]` imported from `../../../custom_components/ha_controller/emoji.json`, `EMOJI_SET`, `normalizeEmoji(text): string`. - - **`test/fixtures.ts`:** `validLayouts`, `invalidLayouts` and `colors`, loaded with `import.meta.glob("../../protocol/fixtures/…", {eager: true, import: "default"})`. + - **`model/emoji.ts`:** `SUPPORTED_EMOJI: readonly string[]` imported from `../../../emoji.json` (relative to `src/model/`), `EMOJI_SET`, `normalizeEmoji(text): string`. + - **`test/fixtures.ts`:** `validLayouts`, `invalidLayouts` and `colors`, loaded with `import.meta.glob("../../../../docs/protocol/fixtures/…", {eager: true, import: "default"})`. - [ ] **Step 1: Scaffold the tooling.** - **`package.json`:** `"type": "module"`, `"private": true`, `"version": "0.1.0"`. @@ -77,8 +77,8 @@ - **`tsconfig.json`:** `strict`, `target` and `lib` ES2022 + DOM, `module: ESNext`, `moduleResolution: Bundler`, `experimentalDecorators: true`, `useDefineForClassFields: false`, `resolveJsonModule: true`, `noEmit: true`. - **`vite.config.ts`:** - Library mode: entry `src/ha-controller-panel.ts`, format `es`, file name `ha-controller-panel.js`. - - `outDir: "../custom_components/ha_controller/frontend"`, `emptyOutDir: false`, `target: "es2022"`, with `lit` bundled. - - `server.fs.allow: [".."]`. + - `outDir: "dist"`, `emptyOutDir: true`, `target: "es2022"`, with `lit` bundled. + - `server.fs.allow: ["../../.."]` (the repository root, for the fixtures and `emoji.json`). - `test.environment: "happy-dom"`. Run `npm install`. @@ -106,7 +106,7 @@ for (const [name, c] of Object.entries(invalidLayouts)) expect(validateLayout(c. - [ ] **Step 3: Run the tests to verify they fail** -Run: `npm --prefix frontend test` +Run: `npm --prefix custom_components/ha_controller/frontend test` Expected: FAIL (modules missing). - [ ] **Step 4: Implement `types.ts`, `grid.ts`, `validate.ts` and `emoji.ts`.** @@ -115,19 +115,19 @@ Expected: FAIL (modules missing). - [ ] **Step 5: Run the tests to verify they pass** -Run: `npm --prefix frontend test && npm --prefix frontend run typecheck` +Run: `npm --prefix custom_components/ha_controller/frontend test && npm --prefix custom_components/ha_controller/frontend run typecheck` Expected: PASS. - [ ] **Step 6: Add the CI job.** Add job `frontend` to `.github/workflows/ci.yml`: - - `actions/setup-node@v4` with `node-version: 24`, `cache: npm`, `cache-dependency-path: frontend/package-lock.json`. - - Working directory `frontend`: `npm ci`, `npm test`, `npm run build`. + - `actions/setup-node@v4` with `node-version: 24`, `cache: npm`, `cache-dependency-path: custom_components/ha_controller/frontend/package-lock.json`. + - Working directory `custom_components/ha_controller/frontend`: `npm ci`, `npm test`, `npm run build`. - Add the `npm --prefix frontend …` commands to `CLAUDE.md`. + Add the `npm --prefix custom_components/ha_controller/frontend …` commands to `.claude/CLAUDE.md`. - [ ] **Step 7: Commit** ```bash -git add frontend .github/workflows/ci.yml CLAUDE.md +git add custom_components/ha_controller/frontend .github/workflows/ci.yml .claude/CLAUDE.md git commit -m "feat(panel): add panel tooling, grid model and validation" ``` @@ -136,7 +136,7 @@ git commit -m "feat(panel): add panel tooling, grid model and validation" ### Task 2: Edit operations, colours and emoji **Files:** -- Create: `frontend/src/model/edit.ts`, `frontend/src/model/color.ts`, `frontend/test/edit.test.ts`, `frontend/test/color.test.ts`, `frontend/test/emoji.test.ts` +- Create: `custom_components/ha_controller/frontend/src/model/edit.ts`, `custom_components/ha_controller/frontend/src/model/color.ts`, `custom_components/ha_controller/frontend/test/edit.test.ts`, `custom_components/ha_controller/frontend/test/color.test.ts`, `custom_components/ha_controller/frontend/test/emoji.test.ts` **Interfaces:** - Consumes: `canDelete` (Task 1). @@ -172,20 +172,20 @@ expect(SUPPORTED_EMOJI).toHaveLength(64); expect(normalizeEmoji("❄️")).toBe( - [ ] **Step 2: Run the tests to verify they fail** -Run: `npm --prefix frontend test` +Run: `npm --prefix custom_components/ha_controller/frontend test` Expected: FAIL. - [ ] **Step 3: Implement `edit.ts` and `color.ts`.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `npm --prefix frontend test` +Run: `npm --prefix custom_components/ha_controller/frontend test` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add frontend/src/model frontend/test +git add custom_components/ha_controller/frontend/src/model custom_components/ha_controller/frontend/test git commit -m "feat(panel): add pure layout edit operations" ``` @@ -194,7 +194,7 @@ git commit -m "feat(panel): add pure layout edit operations" ### Task 3: Block map component (`hc-grid`) **Files:** -- Create: `frontend/src/components/hc-grid.ts`, `frontend/test/hc-grid.test.ts` +- Create: `custom_components/ha_controller/frontend/src/components/hc-grid.ts`, `custom_components/ha_controller/frontend/test/hc-grid.test.ts` **Interfaces:** - Consumes: `placeholders`, `gridBounds` and `textColorFor`. @@ -223,20 +223,20 @@ expect(one(el, '.block[data-id="b3"]')!.style.gridColumn).toBe("2"); expect(one( - [ ] **Step 2: Run the tests to verify they fail** -Run: `npm --prefix frontend test` +Run: `npm --prefix custom_components/ha_controller/frontend test` Expected: FAIL. - [ ] **Step 3: Implement `hc-grid.ts`.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `npm --prefix frontend test` +Run: `npm --prefix custom_components/ha_controller/frontend test` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add frontend/src/components/hc-grid.ts frontend/test/hc-grid.test.ts +git add custom_components/ha_controller/frontend/src/components/hc-grid.ts custom_components/ha_controller/frontend/test/hc-grid.test.ts git commit -m "feat(panel): render the block map" ``` @@ -246,9 +246,9 @@ git commit -m "feat(panel): render the block map" **Files:** - Create: - - `frontend/src/messages.ts` - - `frontend/src/components/`: `hc-block-editor.ts`, `hc-item-editor.ts`, `hc-entity-input.ts`, `hc-emoji-picker.ts`, `hc-preview.ts` - - `frontend/test/hc-block-editor.test.ts`, `frontend/test/hc-item-editor.test.ts` + - `custom_components/ha_controller/frontend/src/messages.ts` + - `custom_components/ha_controller/frontend/src/components/`: `hc-block-editor.ts`, `hc-item-editor.ts`, `hc-entity-input.ts`, `hc-emoji-picker.ts`, `hc-preview.ts` + - `custom_components/ha_controller/frontend/test/hc-block-editor.test.ts`, `custom_components/ha_controller/frontend/test/hc-item-editor.test.ts` **Interfaces:** - Consumes: the Task 2 edit operations and `canDelete`. @@ -319,20 +319,20 @@ expect(all(picker, "button.emoji")).toHaveLength(64); - [ ] **Step 2: Run the tests to verify they fail** -Run: `npm --prefix frontend test` +Run: `npm --prefix custom_components/ha_controller/frontend test` Expected: FAIL. - [ ] **Step 3: Implement the five components and `messages.ts`.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `npm --prefix frontend test && npm --prefix frontend run typecheck` +Run: `npm --prefix custom_components/ha_controller/frontend test && npm --prefix custom_components/ha_controller/frontend run typecheck` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add frontend/src frontend/test +git add custom_components/ha_controller/frontend/src custom_components/ha_controller/frontend/test git commit -m "feat(panel): add block and item editors" ``` @@ -342,11 +342,11 @@ git commit -m "feat(panel): add block and item editors" **Files:** - Create: - - `frontend/src/ha-controller-panel.ts`, `frontend/src/api.ts` - - `frontend/dev/index.html`, `frontend/dev/mock-hass.ts` - - `frontend/test/panel.test.ts` + - `custom_components/ha_controller/frontend/src/ha-controller-panel.ts`, `custom_components/ha_controller/frontend/src/api.ts` + - `custom_components/ha_controller/frontend/dev/index.html`, `custom_components/ha_controller/frontend/dev/mock-hass.ts` + - `custom_components/ha_controller/frontend/test/panel.test.ts` - `docs/configuration.md` -- Modify: `docs/README.md`, `docs/development.md` ("Panel" section), `CLAUDE.md` +- Modify: `docs/README.md`, `docs/development.md` ("Panel" section), `.claude/CLAUDE.md` **Interfaces:** - Consumes: plan 2's websocket commands `ha_controller/screens`, `ha_controller/layout/get` and `ha_controller/layout/save`; Tasks 1–4. @@ -394,17 +394,17 @@ test("status line reports update available", ...) // fir - [ ] **Step 2: Run the tests to verify they fail** -Run: `npm --prefix frontend test` +Run: `npm --prefix custom_components/ha_controller/frontend test` Expected: FAIL. - [ ] **Step 3: Implement `api.ts`, `ha-controller-panel.ts` (with `customElements.define` guarded against double definition), `dev/mock-hass.ts` and `dev/index.html`.** - [ ] **Step 4: Run the tests and the build** -Run: `npm --prefix frontend test && npm --prefix frontend run build && test -f custom_components/ha_controller/frontend/ha-controller-panel.js` +Run: `npm --prefix custom_components/ha_controller/frontend test && npm --prefix custom_components/ha_controller/frontend run build && test -f custom_components/ha_controller/frontend/dist/ha-controller-panel.js` Expected: PASS, and the bundle exists. -- [ ] **Step 5: Manual check.** Run `npm --prefix frontend run dev`. Expected: +- [ ] **Step 5: Manual check.** Run `npm --prefix custom_components/ha_controller/frontend run dev`. Expected: - the reference map looks like the screenshot, with 4 blocks and 8 "+"; - clicking "+" right of Kitchen adds "Block 5"; - deleting Hello World is refused with "Other blocks would become unreachable."; @@ -428,6 +428,6 @@ Expected: PASS, and the bundle exists. - [ ] **Step 7: Commit** ```bash -git add frontend docs CLAUDE.md +git add custom_components/ha_controller/frontend docs .claude/CLAUDE.md git commit -m "feat(panel): add panel root with save, status and dev harness" ``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md b/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md index f2108c6..ffb629c 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md @@ -6,7 +6,7 @@ **Architecture:** Two local external components. - `ha_controller`: - - **Pure C++17 modules** with no ESPHome or LVGL headers, unit-tested on the host against `protocol/fixtures/`: `layout`, `states`, `knob`, `format`, `gesture`, `color`, `hold`. + - **Pure C++17 modules** with no ESPHome or LVGL headers, unit-tested on the host against `docs/protocol/fixtures/`: `layout`, `states`, `knob`, `format`, `gesture`, `color`, `hold`. - **LVGL 9.5 modules:** `pager` (gestures, animation, edge hints) and `widgets` (block views). - **`HaController`:** the ESPHome component that glues them to the native API actions and events declared in YAML. - `axp2101_battery`: reads the PMU. @@ -84,7 +84,7 @@ uint32_t text_color_for(uint32_t rgb); // 0x000000 if l - `FetchContent` doctest `v2.4.12` (GIT_TAG) and ArduinoJson `v7.4.2` (GIT_TAG; same major as ESPHome's bundled 7.x). - Target `unit_tests`: every `test_*.cpp` plus the pure `.cpp` files from `../components/ha_controller/`. - Include path `../components`. - - `FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../../protocol/fixtures"`. + - `FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../../docs/protocol/fixtures"`. - `add_test(unit_tests …)`. - [ ] **Step 2: Write the failing tests** @@ -289,7 +289,7 @@ git commit -m "feat(firmware): model edge swipes" - `esphome/components/axp2101_battery/__init__.py`, `axp2101_battery.h`, `axp2101_battery.cpp`, `axp2101_regs.h` - `esphome/tests/test_axp2101.cpp` - `.github/workflows/firmware.yml` -- Modify: `esphome/tests/CMakeLists.txt` (include path for `axp2101_battery`), `CLAUDE.md` (commands) +- Modify: `esphome/tests/CMakeLists.txt` (include path for `axp2101_battery`), `.claude/CLAUDE.md` (commands) **Interfaces:** - Produces: @@ -424,10 +424,10 @@ number: - [ ] **Step 6: Compile** -Run: `python3.13 -m venv .venv-esphome && .venv-esphome/bin/pip install -r esphome/requirements.txt && .venv-esphome/bin/esphome compile esphome/ha-controller.yaml` +Run: `python3.13 -m venv esphome/.venv && esphome/.venv/bin/pip install -r esphome/requirements.txt && esphome/.venv/bin/esphome compile esphome/ha-controller.yaml` Expected: `SUCCESS`, and the image fits the app partition (ESPHome sizes it for 16 MB). If a font option is rejected (e.g. `glyphsets`), replace it with an explicit `glyphs:` string covering U+0020–U+007E, U+00A0–U+017F and `°—…’“”€`. Record the change in `docs/hardware.md` in Task 9. -- [ ] **Step 7: Hardware check.** Flash over USB-C with `.venv-esphome/bin/esphome run esphome/ha-controller.yaml`. Expected: +- [ ] **Step 7: Hardware check.** Flash over USB-C with `esphome/.venv/bin/esphome run esphome/ha-controller.yaml`. Expected: - the round display shows "HA Controller", the version and 💡, centred; - tapping near the top/right/bottom/left edges logs about `(233,5)` / `(460,233)` / `(233,460)` / `(5,233)`. If not, fix `transform` (`mirror_x`, `mirror_y`, `swap_xy`) and repeat; - with a battery: `Battery` reads 0–100 %, `Battery voltage` 3.3–4.3 V, and `Charging` turns on when USB is plugged in; @@ -436,7 +436,7 @@ Expected: `SUCCESS`, and the image fits the app partition (ESPHome sizes it for - Wi-Fi provisioning works through the `HA Controller` access point and its captive portal. - [ ] **Step 8: Add the firmware CI.** In `.github/workflows/firmware.yml`, workflow `Firmware`: - - Triggers: `push` to `main` and `pull_request`, on paths `esphome/**`, `protocol/**`, `custom_components/ha_controller/emoji.json` and `.github/workflows/firmware.yml`. + - Triggers: `push` to `main` and `pull_request`, on paths `esphome/**`, `docs/protocol/**`, `custom_components/ha_controller/emoji.json` and `.github/workflows/firmware.yml`. - Job `host-tests`: `cmake -S esphome/tests -B build/tests`, `cmake --build build/tests`, `ctest --test-dir build/tests --output-on-failure`. - Job `compile`: - `actions/setup-python@v5` with Python 3.13; @@ -444,12 +444,12 @@ Expected: `SUCCESS`, and the image fits the app partition (ESPHome sizes it for - `pip install -r esphome/requirements.txt`; - `esphome compile esphome/ha-controller.yaml`. - Add the host-test and compile commands to `CLAUDE.md`. + Add the host-test and compile commands to `.claude/CLAUDE.md`. - [ ] **Step 9: Commit** ```bash -git add esphome .github/workflows/firmware.yml CLAUDE.md +git add esphome .github/workflows/firmware.yml .claude/CLAUDE.md git commit -m "feat(firmware): bring up the Waveshare AMOLED 1.75 board" ``` @@ -462,7 +462,7 @@ git commit -m "feat(firmware): bring up the Waveshare AMOLED 1.75 board" - `esphome/components/ha_controller/__init__.py`, `ha_controller.h`, `ha_controller.cpp` - `esphome/components/ha_controller/widgets.h`, `widgets.cpp` (placeholder views in this task) - `esphome/simulator.yaml` -- Modify: `esphome/packages/ui.yaml`, `.github/workflows/firmware.yml` (simulator compile), `CLAUDE.md` +- Modify: `esphome/packages/ui.yaml`, `.github/workflows/firmware.yml` (simulator compile), `.claude/CLAUDE.md` **Interfaces:** - Consumes: Tasks 1–2 (parsers), plan 2 (hello handling, `set_layout`/`set_states` callers). @@ -530,22 +530,22 @@ std::unique_ptr make_block_view(lv_obj_t *parent, const Block &block, - [ ] **Step 3: Compile both configs** -Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` Expected: both `SUCCESS`. The simulator needs SDL2: `brew install sdl2` or `apt install libsdl2-dev`. - [ ] **Step 4: End-to-end check with Home Assistant**, using plan 2's integration and plan 3's built panel. - 1. Run `.venv-esphome/bin/esphome run esphome/simulator.yaml`. The window shows "Waiting for Home Assistant". + 1. Run `esphome/.venv/bin/esphome run esphome/simulator.yaml`. The window shows "Waiting for Home Assistant". 2. In Home Assistant, add an ESPHome device on `:6053`, then add the HA Controller integration and pick "HA Controller Simulator". 3. Within 5 s of the connection, the simulator shows "No blocks yet". Developer tools › Events shows `esphome.ha_controller_hello` with reasons `connected` and then `applied`. 4. In the panel, add three blocks and save. The simulator shows the start block's name on its background. 5. Heartbeat hellos arrive every 60 s with a revision equal to the panel's. -- [ ] **Step 5: Extend CI and the docs.** In `firmware.yml` `compile`, add `sudo apt-get install -y libsdl2-dev` and `esphome compile esphome/simulator.yaml`. Add the simulator commands to `CLAUDE.md`. +- [ ] **Step 5: Extend CI and the docs.** In `firmware.yml` `compile`, add `sudo apt-get install -y libsdl2-dev` and `esphome compile esphome/simulator.yaml`. Add the simulator commands to `.claude/CLAUDE.md`. - [ ] **Step 6: Commit** ```bash -git add esphome .github/workflows/firmware.yml CLAUDE.md +git add esphome .github/workflows/firmware.yml .claude/CLAUDE.md git commit -m "feat(firmware): receive layouts and talk to Home Assistant" ``` @@ -587,7 +587,7 @@ class Pager { - [ ] **Step 2: Compile both configs** -Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` Expected: `SUCCESS`. - [ ] **Step 3: Simulator check.** Build the reference map in the panel: Kitchen start, Lights above, Hello World left, Bedroom below Hello World. Expected: @@ -642,7 +642,7 @@ git commit -m "feat(firmware): navigate between blocks with edge swipes" - [ ] **Step 2: Compile both configs** -Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` Expected: `SUCCESS`. - [ ] **Step 3: Simulator + Home Assistant check.** Use the reference map with real or template entities. Expected: @@ -734,7 +734,7 @@ Expected: PASS. - [ ] **Step 5: Implement the component additions and the YAML wiring, then compile both configs** -Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml && .venv-esphome/bin/esphome compile esphome/simulator.yaml` +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` Expected: `SUCCESS`. - [ ] **Step 6: Simulator check.** Expected: @@ -764,7 +764,7 @@ git commit -m "feat(firmware): sleep after the configured delay and wake on touc - `docs/hardware.md` - `.claude/skills/firmware-dev/SKILL.md`, `.claude/skills/add-widget/SKILL.md` - `.claude/agents/firmware-reviewer.md` -- Modify: `esphome/ha-controller.yaml`, `docs/development.md` ("Firmware" section), `docs/README.md`, `CLAUDE.md` +- Modify: `esphome/ha-controller.yaml`, `docs/development.md` ("Firmware" section), `docs/README.md`, `.claude/CLAUDE.md` **Interfaces:** - Produces (used by plan 5): the device API action `install_firmware` (`url: string`, `md5_url: string`): @@ -795,7 +795,7 @@ api: - [ ] **Step 1: Add the action, then compile** -Run: `.venv-esphome/bin/esphome compile esphome/ha-controller.yaml` +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml` Expected: `SUCCESS`. - [ ] **Step 2: OTA check on hardware.** @@ -860,16 +860,16 @@ Expected: `SUCCESS`. - host tests for new pure logic; - both configs compile. - Output: `file:line — issue — fix`. - - **`CLAUDE.md`:** list the skills and the agent. + - **`.claude/CLAUDE.md`:** list the skills and the agent. - [ ] **Step 5: Run every suite** -Run: `pytest && npm --prefix frontend test && ctest --test-dir build/tests --output-on-failure` +Run: `pytest custom_components/ha_controller/tests && pytest .github/scripts/tests && npm --prefix custom_components/ha_controller/frontend test && ctest --test-dir build/tests --output-on-failure` Expected: PASS. - [ ] **Step 6: Commit** ```bash -git add esphome/ha-controller.yaml docs .claude CLAUDE.md +git add esphome/ha-controller.yaml docs .claude .claude/CLAUDE.md git commit -m "feat(firmware): install firmware over the air on request" ``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md index 5f13681..47491f1 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md @@ -9,7 +9,7 @@ - a tag-driven release workflow that publishes the HACS zip, the firmware binaries and the Pages site. **Architecture:** -- **Versioning:** `scripts/versioning.py` owns the version rule. +- **Versioning:** `.github/scripts/versioning.py` owns the version rule. - **Updates:** the integration's `update` platform asks the screen, through plan 4's `install_firmware` action, to download its OTA image for the integration version from GitHub Pages. - **Release scripts:** three small, unit-tested scripts collect the firmware, package the integration and assemble the Pages site from GitHub release assets. - **Workflow:** `release.yml` chains them on a `vX.Y.Z` tag. A manual run is a dry run. @@ -20,7 +20,7 @@ ## Global Constraints -- **Version:** one SemVer `X.Y.Z` in `custom_components/ha_controller/manifest.json`, `esphome/version.yaml`, `frontend/package.json` and `frontend/package-lock.json` (root `version` and `packages[""].version`). Change it only with `scripts/versioning.py bump`. +- **Version:** one SemVer `X.Y.Z` in `custom_components/ha_controller/manifest.json`, `esphome/version.yaml`, `custom_components/ha_controller/frontend/package.json` and `custom_components/ha_controller/frontend/package-lock.json` (root `version` and `packages[""].version`). Change it only with `.github/scripts/versioning.py bump`. - **URLs:** firmware OTA `https://pyxel-dev.github.io/HA-controller/firmware//ha-controller.ota.bin` (+ `.md5`); release notes `https://github.com/pyxel-dev/HA-controller/releases/tag/v`. - **Release assets:** `ha_controller.zip`, `ha-controller-.factory.bin`, `ha-controller-.ota.bin`, `ha-controller-.ota.bin.md5`. The `.md5` file holds exactly 32 lowercase hex characters and no newline. - **Timings:** install timeout 300 s; auto-update at most once per screen and version every 3600 s; auto-update only when the integration version matches `^\d+\.\d+\.\d+$`. @@ -39,8 +39,8 @@ ### Task 1: Version check and bump **Files:** -- Create: `scripts/versioning.py`, `tests/scripts/__init__.py`, `tests/scripts/test_versioning.py` -- Modify: `.github/workflows/ci.yml` (job `versions`), `CLAUDE.md` +- Create: `.github/scripts/versioning.py`, `.github/scripts/tests/__init__.py`, `.github/scripts/tests/test_versioning.py` +- Modify: `.github/workflows/ci.yml` (job `versions`), `.claude/CLAUDE.md` **Interfaces:** - Produces: @@ -68,22 +68,22 @@ def test_main_exit_codes(repo): ... - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/scripts/test_versioning.py -v` +Run: `pytest .github/scripts/tests/test_versioning.py -v` Expected: FAIL. -- [ ] **Step 3: Implement `scripts/versioning.py`.** +- [ ] **Step 3: Implement `.github/scripts/versioning.py`.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/scripts -v && python scripts/versioning.py check` +Run: `pytest .github/scripts/tests -v && python .github/scripts/versioning.py check` Expected: PASS, exit 0. -- [ ] **Step 5: Add CI and the docs.** Add job `versions` to `ci.yml` (setup-python 3.14, `python scripts/versioning.py check`). Add the commands to `CLAUDE.md`, and replace its plan-5 placeholder rule with the real command. +- [ ] **Step 5: Add CI and the docs.** Add job `versions` to `ci.yml` (setup-python 3.14, `python .github/scripts/versioning.py check`). Add the commands to `.claude/CLAUDE.md`, and replace its plan-5 placeholder rule with the real command. - [ ] **Step 6: Commit** ```bash -git add scripts/versioning.py tests/scripts .github/workflows/ci.yml CLAUDE.md +git add .github/scripts/versioning.py .github/scripts/tests .github/workflows/ci.yml .claude/CLAUDE.md git commit -m "build: add single-version check and bump script" ``` @@ -92,7 +92,7 @@ git commit -m "build: add single-version check and bump script" ### Task 2: Firmware update entity, auto-update and options flow **Files:** -- Create: `custom_components/ha_controller/firmware.py`, `custom_components/ha_controller/update.py`, `tests/integration/test_update.py` +- Create: `custom_components/ha_controller/firmware.py`, `custom_components/ha_controller/update.py`, `custom_components/ha_controller/tests/test_update.py` - Modify: - `custom_components/ha_controller/controller.py`, `__init__.py` (`PLATFORMS = [Platform.UPDATE]`), `config_flow.py` (options flow) - `strings.json`, `translations/en.json` @@ -145,20 +145,20 @@ async def test_options_flow_toggles_auto_update(hass): ... - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/integration/test_update.py -v` +Run: `pytest custom_components/ha_controller/tests/test_update.py -v` Expected: FAIL. - [ ] **Step 3: Implement `firmware.py`, the controller additions, `update.py` and the options flow.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest -v && ruff check .` +Run: `pytest custom_components/ha_controller/tests -v && ruff check custom_components` Expected: PASS. - [ ] **Step 5: Commit** ```bash -git add custom_components/ha_controller tests/integration/test_update.py +git add custom_components/ha_controller custom_components/ha_controller/tests/test_update.py git commit -m "feat(integration): keep screen firmware on the integration version" ``` @@ -168,15 +168,15 @@ git commit -m "feat(integration): keep screen firmware on the integration versio **Files:** - Create: - - `scripts/collect_firmware.py`, `scripts/package_integration.py`, `scripts/build_pages.py` + - `.github/scripts/collect_firmware.py`, `.github/scripts/package_integration.py`, `.github/scripts/build_pages.py` - `esphome/web/index.html` - - `tests/scripts/test_release_scripts.py` + - `.github/scripts/tests/test_release_scripts.py` **Interfaces:** -- Consumes: the plan 3 bundle `custom_components/ha_controller/frontend/ha-controller-panel.js`; the ESPHome build tree (`esphome/.esphome/build/**/firmware.factory.bin`, `firmware.ota.bin`). +- Consumes: the plan 3 bundle `custom_components/ha_controller/frontend/dist/ha-controller-panel.js`; the ESPHome build tree (`esphome/.esphome/build/**/firmware.factory.bin`, `firmware.ota.bin`). - Produces (each has an `argparse` CLI with the same parameters): - **`collect(build_dir: Path, version: str, out_dir: Path) -> list[Path]`.** Requires exactly one `*.factory.bin` and one `*.ota.bin` under `build_dir`, otherwise it raises `ValueError`. It writes `ha-controller-.factory.bin`, `ha-controller-.ota.bin` and `ha-controller-.ota.bin.md5`. - - **`package(root: Path, out_file: Path) -> Path`.** Zips the contents of `custom_components/ha_controller/` at the zip root, excluding `__pycache__/`, `*.pyc` and `.gitkeep`. Raises `FileNotFoundError("Build the panel first: npm --prefix frontend run build")` when the bundle is missing. + - **`package(root: Path, out_file: Path) -> Path`.** Zips the contents of `custom_components/ha_controller/` at the zip root, excluding `tests/`, `__pycache__/`, `*.pyc`, and everything under `frontend/` except `frontend/dist/ha-controller-panel.js`. Raises `FileNotFoundError("Build the panel first: npm --prefix custom_components/ha_controller/frontend run build")` when the bundle is missing. - **`build_site(web_dir: Path, releases_dir: Path, latest: str, out_dir: Path) -> None`.** `releases_dir//` holds each release's assets. It writes: - `index.html`, with every `{{VERSION}}` replaced by `latest`; - `.nojekyll`; @@ -209,7 +209,7 @@ git commit -m "feat(integration): keep screen firmware on the integration versio ```python def test_collect_writes_versioned_files_and_md5(tmp_path): ... # .md5 == hashlib.md5(ota).hexdigest(), 32 chars, no newline def test_collect_requires_exactly_one_of_each(tmp_path): ... # none → ValueError; two factory bins → ValueError -def test_package_zips_integration_with_panel(tmp_path): ... # names include "manifest.json", "frontend/ha-controller-panel.js"; no __pycache__ +def test_package_zips_integration_with_panel(tmp_path): ... # names include "manifest.json", "frontend/dist/ha-controller-panel.js"; no __pycache__, tests/, frontend/src or frontend/package.json def test_package_requires_built_panel(tmp_path): ... def test_build_site_manifest(tmp_path): ... # exact dict above for latest 0.2.0 def test_build_site_keeps_every_release(tmp_path): ... # releases 0.1.0 + 0.2.0 → both firmware//ha-controller.ota.bin(.md5) @@ -220,25 +220,25 @@ def test_web_page_template(): ... # real e - [ ] **Step 2: Run the tests to verify they fail** -Run: `pytest tests/scripts/test_release_scripts.py -v` +Run: `pytest .github/scripts/tests/test_release_scripts.py -v` Expected: FAIL. - [ ] **Step 3: Implement the three scripts and `index.html`.** - [ ] **Step 4: Run the tests to verify they pass** -Run: `pytest tests/scripts -v` +Run: `pytest .github/scripts/tests -v` Expected: PASS. - [ ] **Step 5: Preview locally.** - 1. Build a fake site from the scripts' test data: `python scripts/build_pages.py --web esphome/web --releases --latest 0.1.0 --out site`. + 1. Build a fake site from the scripts' test data: `python .github/scripts/build_pages.py --web esphome/web --releases --latest 0.1.0 --out site`. 2. Serve it with `python3 -m http.server -d site`. 3. Open it in Chrome and confirm the page shows "Firmware 0.1.0" and an Install button. - [ ] **Step 6: Commit** ```bash -git add scripts esphome/web tests/scripts +git add .github/scripts esphome/web git commit -m "build: add release packaging scripts and web installer page" ``` @@ -251,7 +251,7 @@ git commit -m "build: add release packaging scripts and web installer page" - `.github/workflows/release.yml` - `docs/getting-started.md`, `docs/updates.md`, `docs/releasing.md` - `.claude/skills/release/SKILL.md` -- Modify: `hacs.json`, `README.md`, `docs/README.md`, `CLAUDE.md` +- Modify: `hacs.json`, `README.md`, `docs/README.md`, `.claude/CLAUDE.md` **Interfaces:** - Consumes: Tasks 1–3, `esphome/requirements.txt` and the `npm` scripts. @@ -261,24 +261,24 @@ git commit -m "build: add release packaging scripts and web installer page" - **Job `build`** (`ubuntu-latest`). Steps, in order: 1. Checkout, then setup-python 3.13 and setup-node 24 with the npm cache. 2. Read the version from `manifest.json` into an output. - 3. `python scripts/versioning.py check`, plus `--tag "$GITHUB_REF_NAME"` on tag runs. - 4. `npm --prefix frontend ci` and `npm --prefix frontend run build`. - 5. `python scripts/package_integration.py --out dist/ha_controller.zip`. + 3. `python .github/scripts/versioning.py check`, plus `--tag "$GITHUB_REF_NAME"` on tag runs. + 4. `npm --prefix custom_components/ha_controller/frontend ci` and `npm --prefix custom_components/ha_controller/frontend run build`. + 5. `python .github/scripts/package_integration.py --out dist/ha_controller.zip`. 6. `pip install -r esphome/requirements.txt` and `esphome compile esphome/ha-controller.yaml`. - 7. `python scripts/collect_firmware.py --build-dir esphome/.esphome/build --version --out dist`. + 7. `python .github/scripts/collect_firmware.py --build-dir esphome/.esphome/build --version --out dist`. 8. `actions/upload-artifact@v4` (`dist`). - **Job `release`** (needs `build`, tag runs only): download the artifact, then `gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --generate-notes --verify-tag` with `GH_TOKEN`. - **Job `pages`** (needs `build` and `release`, tag runs only, environment `github-pages`): 1. Checkout. 2. For every tag from `gh release list --limit 200 --json tagName -q '.[].tagName'`, run `gh release download "$tag" -p 'ha-controller-*' -D "releases/${tag#v}"`. - 3. `python scripts/build_pages.py --web esphome/web --releases releases --latest --out site`. + 3. `python .github/scripts/build_pages.py --web esphome/web --releases releases --latest --out site`. 4. `actions/configure-pages@v5`, `actions/upload-pages-artifact@v3` (`site`) and `actions/deploy-pages@v4`. - [ ] **Step 1: Write the workflow and update `hacs.json`.** - [ ] **Step 2: Dry run.** Push the branch, run "Release" with `workflow_dispatch`, and download the `dist` artifact. Expected: - the `build` job is green and `release`/`pages` are skipped; - - the artifact holds `ha_controller.zip` (with `frontend/ha-controller-panel.js` inside) plus the three `ha-controller-0.1.0.*` files. + - the artifact holds `ha_controller.zip` (with `frontend/dist/ha-controller-panel.js` inside, and no `tests/` or panel sources) plus the three `ha-controller-0.1.0.*` files. - [ ] **Step 3: Write the user docs.** - **`docs/getting-started.md`:** @@ -302,7 +302,7 @@ git commit -m "build: add release packaging scripts and web installer page" - **`docs/releasing.md`:** - One-time setup: Settings › Pages › Source "GitHub Actions"; repository description and topics for HACS. - Steps: - 1. `python scripts/versioning.py bump X.Y.Z` + 1. `python .github/scripts/versioning.py bump X.Y.Z` 2. commit `chore: release X.Y.Z` 3. `git tag vX.Y.Z && git push origin main vX.Y.Z` 4. watch the "Release" workflow @@ -311,7 +311,7 @@ git commit -m "build: add release packaging scripts and web installer page" - **`README.md`:** an "Install" section with the installer URL and the HACS custom repository, and links to `docs/getting-started.md` and `docs/README.md`. - **`docs/README.md`:** link the three new docs. -- [ ] **Step 4: Write `.claude/skills/release/SKILL.md`** and list it in `CLAUDE.md`. +- [ ] **Step 4: Write `.claude/skills/release/SKILL.md`** and list it in `.claude/CLAUDE.md`. - Frontmatter `name: release`. - `description:` "Use when cutting a release or changing the release pipeline: versions, release workflow, GitHub Pages installer, HACS packaging, firmware OTA URLs." - Body: @@ -319,17 +319,17 @@ git commit -m "build: add release packaging scripts and web installer page" - The release steps from `docs/releasing.md`. - What each job produces. - OTA URLs must stay stable (`firmware//ha-controller.ota.bin`), because integrations already installed depend on them. - - Check `pytest tests/scripts` after any script change. + - Check `pytest .github/scripts/tests` after any script change. - [ ] **Step 5: Run every suite** -Run: `pytest && ruff check . && python scripts/versioning.py check && npm --prefix frontend test` +Run: `pytest custom_components/ha_controller/tests && pytest .github/scripts/tests && ruff check custom_components .github/scripts && python .github/scripts/versioning.py check && npm --prefix custom_components/ha_controller/frontend test` Expected: PASS. - [ ] **Step 6: Commit** ```bash -git add .github/workflows/release.yml hacs.json README.md docs .claude CLAUDE.md +git add .github/workflows/release.yml hacs.json README.md docs .claude .claude/CLAUDE.md git commit -m "ci: release integration, firmware and web installer from tags" ``` diff --git a/docs/superpowers/specs/2026-11-16-ha-controller-design.md b/docs/superpowers/specs/2026-11-16-ha-controller-design.md index 3c116d0..4e63a7f 100644 --- a/docs/superpowers/specs/2026-11-16-ha-controller-design.md +++ b/docs/superpowers/specs/2026-11-16-ha-controller-design.md @@ -53,17 +53,18 @@ Turn the Waveshare ESP32-S3-Touch-AMOLED-1.75 into a Home Assistant remote. In a | Path | Content | |---|---| -| `docs/` | User and developer documentation. `docs/superpowers/` holds this spec and the plans. | -| `protocol/fixtures/` | Shared test fixtures: the cross-language contract | -| `custom_components/ha_controller/` | Home Assistant integration (Python) | -| `custom_components/ha_controller/emoji.json` | Canonical list of supported emoji, read by the firmware build, the panel and the integration | -| `custom_components/ha_controller/frontend/` | Built panel bundle (generated, git-ignored) | -| `frontend/` | Panel source (TypeScript, Lit, Vite) | -| `esphome/` | Firmware: device config, packages, simulator config, external components, host tests, web installer page | -| `scripts/` | Versioning, packaging, GitHub Pages site builder | -| `tests/` | Python tests (protocol fixtures, docs, integration, scripts) | -| `.claude/` | Claude Code skills and agents | +The repository root holds no files except `README.md` (GitHub and HACS landing page), `hacs.json` (HACS reads it only at the root) and `.gitignore`. Everything else lives in a folder: + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/protocol/` holds the protocol doc (`README.md`) and its shared fixtures (`fixtures/`), the cross-language contract. `docs/superpowers/` holds this spec and the plans. | +| `custom_components/` | Everything for the Home Assistant integration. HACS allows a single directory here, so development files live inside it, or next to it as plain files. | +| `custom_components/ha_controller/` | The integration (Python). Also holds `emoji.json` (canonical emoji list, also read by the firmware build and the panel), `brand/`, `tests/` (pytest), and `frontend/` (panel source in TypeScript, Lit and Vite, built to `frontend/dist/`, which is git-ignored). | +| `custom_components/pyproject.toml`, `requirements_test.txt`, `__init__.py` | Python test and lint configuration for the integration. The empty `__init__.py` keeps test imports under `custom_components.ha_controller`. | +| `esphome/` | Everything for the firmware: device config, packages, simulator config, external components, C++ host tests, web installer page, `requirements.txt` (ESPHome version) and its venv (`esphome/.venv`, git-ignored) | | `.github/workflows/` | CI, firmware CI, release | +| `.github/scripts/` | Release and repository-check tooling (versioning, packaging, GitHub Pages site builder, docs and fixture checks), with its own `pyproject.toml`, `requirements.txt` and `tests/` | +| `.claude/` | `CLAUDE.md`, Claude Code skills and agents | | `3D_models/`, `files/` | Existing enclosure models (unchanged) | ## 4. Hardware & firmware platform @@ -183,7 +184,7 @@ A custom block with no items shows its name centred. ## 6. Layout model (integration and panel) -The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: +The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `docs/protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: ```json { "version": 1, "start": "b1", "settings": { "sleep_timeout": 20 }, "blocks": [ @@ -235,7 +236,7 @@ Entities that do not exist (yet) are valid; the screen shows them as unavailable ## 7. Device protocol v1 (normative) -`PROTOCOL_VERSION = 1`. `docs/protocol.md` is the living copy of this section. `protocol/fixtures/` pins it with examples, used by the tests of all three implementations. +`PROTOCOL_VERSION = 1`. `docs/protocol/README.md` is the living copy of this section. `docs/protocol/fixtures/` pins it with examples, used by the tests of all three implementations. **7.1 Actions (Home Assistant → screen).** Services `esphome._`: @@ -367,13 +368,13 @@ Anything else is ignored: an unknown block, a custom block, an unparsable value. - **One version:** a single SemVer version `X.Y.Z` for the whole repository, stored in three places: - `custom_components/ha_controller/manifest.json` (`version`) - `esphome/version.yaml` (`substitutions.project_version`) - - `frontend/package.json` (`version`) + - `custom_components/ha_controller/frontend/package.json` (`version`) - `scripts/versioning.py check [--tag vX.Y.Z]` fails CI on any mismatch, and `scripts/versioning.py bump X.Y.Z` rewrites all three. The initial version is `0.1.0`. + `.github/scripts/versioning.py check [--tag vX.Y.Z]` fails CI on any mismatch, and `.github/scripts/versioning.py bump X.Y.Z` rewrites all three. The initial version is `0.1.0`. - **Release:** pushing tag `vX.Y.Z` cuts a release. The release workflow: 1. verifies the versions; 2. builds the panel; - 3. packages `ha_controller.zip` (the contents of `custom_components/ha_controller/`, with the built panel); + 3. packages `ha_controller.zip`: the contents of `custom_components/ha_controller/` without `tests/` and the panel sources, plus the built panel `frontend/dist/ha-controller-panel.js`; 4. compiles the firmware; 5. publishes a GitHub release with `ha_controller.zip`, `ha-controller-X.Y.Z.factory.bin`, `ha-controller-X.Y.Z.ota.bin` and `ha-controller-X.Y.Z.ota.bin.md5`. - **GitHub Pages:** the release workflow then rebuilds `https://pyxel-dev.github.io/HA-controller/` from the release assets: @@ -407,7 +408,7 @@ Anything else is ignored: an unknown block, a custom block, an unparsable value. ## 12. Testing strategy -- **Shared fixtures** in `protocol/fixtures/`, read by the Python, TypeScript and C++ tests: +- **Shared fixtures** in `docs/protocol/fixtures/`, read by the Python, TypeScript and C++ tests: - `layouts/valid` - `layouts/invalid` (expected code + ref) - `payloads/valid` (stored layout + golden payload) @@ -425,7 +426,7 @@ Anything else is ignored: an unknown block, a custom block, an unparsable value. ## 13. Developer guidance (Claude Code) -- `CLAUDE.md`: purpose; rules (English only, one version, protocol changes go through the protocol skill, TDD); repository map; commands. +- `.claude/CLAUDE.md`: purpose; rules (English only, one version, protocol changes go through the protocol skill, TDD); repository map; commands. - Skills (`.claude/skills/`): `protocol-change`, `add-widget`, `firmware-dev`, `release`. - Agents (`.claude/agents/`): `protocol-guardian`, `ha-integration-reviewer`, `firmware-reviewer`. From de75766ab311ea4d90e83b67580933b0d084303b Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 20:56:06 +0100 Subject: [PATCH 05/49] docs: give each folder its own Python environment Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-11-16-ha-controller-1-foundation.md | 2 +- .../plans/2026-11-16-ha-controller-2-integration.md | 1 + docs/superpowers/plans/2026-11-16-ha-controller-5-release.md | 4 ++++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md index 4d40113..015086d 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md @@ -14,7 +14,7 @@ - Everything is written in English: code, comments, docs, UI strings and commit messages. - Repository `pyxel-dev/HA-controller`. Product name "HA Controller". Integration domain `ha_controller`. ESPHome project `pyxel-dev.ha-controller`. -- Python 3.14, pytest, ruff. +- Python 3.14, pytest, ruff. The repository checks run in their own venv `.github/scripts/.venv`, installed from `.github/scripts/requirements.txt`. - Layout model and protocol v1 exactly as spec §6–§7. Golden revisions: `c4aad3fa` (empty), `90538742` (reference), `5387d4ea` (emoji-variation). - `3D_models/` and `files/` stay untouched. diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md index 7968284..9ddbedb 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md @@ -17,6 +17,7 @@ - Domain `ha_controller`, name "HA Controller", `MANUFACTURER = "pyxel-dev"`, `MODEL = "ha-controller"`. - Minimum Home Assistant 2026.10.0. Python 3.14. +- **Python environment:** the integration has its own venv `custom_components/.venv`. Create it with `python3.14 -m venv custom_components/.venv`, install `custom_components/requirements_test.txt`, and run pytest and ruff from it. The repository checks keep their own venv, `.github/scripts/.venv`. - Protocol v1 and constants exactly as spec §6, §7 and §15, defined once in `const.py`. - Events: `esphome.ha_controller_hello` and `esphome.ha_controller_control`. Services: `esphome._`. The integration never registers its own services. - No blocking I/O in the event loop. Read `emoji.json` with `hass.async_add_executor_job`. diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md index 47491f1..b2ae0ab 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md @@ -25,6 +25,10 @@ - **Release assets:** `ha_controller.zip`, `ha-controller-.factory.bin`, `ha-controller-.ota.bin`, `ha-controller-.ota.bin.md5`. The `.md5` file holds exactly 32 lowercase hex characters and no newline. - **Timings:** install timeout 300 s; auto-update at most once per screen and version every 3600 s; auto-update only when the integration version matches `^\d+\.\d+\.\d+$`. - **Strings:** English only. +- **Python environments:** + - release scripts and their tests: `.github/scripts/.venv`; + - integration tests: `custom_components/.venv`; + - ESPHome: `esphome/.venv`. ## Review Focus From a8b33673503a6cdd4c5abb6a155edcfc171b63b2 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 20:57:01 +0100 Subject: [PATCH 06/49] refactor: move tooling out of the repository root Co-Authored-By: Claude Sonnet 5.5 --- .claude/CLAUDE.md | 42 +++++++++++++++++++ .claude/agents/protocol-guardian.md | 10 ++--- .claude/skills/protocol-change/SKILL.md | 8 ++-- .../scripts/pyproject.toml | 1 - .github/scripts/requirements.txt | 2 + {tests => .github/scripts/tests}/__init__.py | 0 .../scripts/tests/test_docs_links.py | 10 +++-- .../scripts/tests/test_protocol_fixtures.py | 6 +-- .github/workflows/ci.yml | 8 ++-- .gitignore | 1 - CLAUDE.md | 42 ------------------- docs/README.md | 2 +- docs/architecture.md | 25 ++++++----- docs/{protocol.md => protocol/README.md} | 33 +++++++++++++-- .../protocol}/fixtures/colors.json | 0 .../fixtures/controls/climate-clamp.json | 0 .../fixtures/controls/climate-set.json | 0 .../fixtures/controls/ignored-bad-value.json | 0 .../controls/ignored-climate-toggle.json | 0 .../controls/ignored-custom-block.json | 0 .../controls/ignored-unknown-block.json | 0 .../fixtures/controls/light-set-over.json | 0 .../fixtures/controls/light-set-zero.json | 0 .../fixtures/controls/light-set.json | 0 .../fixtures/controls/light-toggle.json | 0 .../invalid/coordinate_out_of_range.json | 0 .../layouts/invalid/disconnected.json | 0 .../layouts/invalid/duplicate_id.json | 0 .../layouts/invalid/duplicate_position.json | 0 .../layouts/invalid/invalid_background.json | 0 .../layouts/invalid/invalid_entity-item.json | 0 .../layouts/invalid/invalid_entity.json | 0 .../invalid/invalid_font_size-item.json | 0 .../layouts/invalid/invalid_font_size.json | 0 .../fixtures/layouts/invalid/invalid_id.json | 0 .../layouts/invalid/invalid_item.json | 0 .../layouts/invalid/invalid_name.json | 0 .../invalid/invalid_sleep_timeout.json | 0 .../layouts/invalid/invalid_start-empty.json | 0 .../layouts/invalid/invalid_start.json | 0 .../invalid/invalid_structure-settings.json | 0 .../invalid/invalid_structure-version.json | 0 .../layouts/invalid/invalid_structure.json | 0 .../layouts/invalid/invalid_text.json | 0 .../layouts/invalid/invalid_type.json | 0 .../layouts/invalid/too_many_blocks.json | 0 .../layouts/invalid/too_many_items.json | 0 .../layouts/invalid/unsupported_emoji.json | 0 .../layouts/valid/emoji-variation.json | 0 .../fixtures/layouts/valid/empty.json | 0 .../fixtures/layouts/valid/reference.json | 0 .../fixtures/layouts/valid/single.json | 0 .../payloads/invalid/bad_json-array.json | 0 .../fixtures/payloads/invalid/bad_json.json | 0 .../invalid/invalid_payload-sleep.json | 0 .../invalid/invalid_payload-widget.json | 0 .../payloads/invalid/invalid_payload.json | 0 .../payloads/invalid/unsupported_version.json | 0 .../payloads/valid/emoji-variation.json | 0 .../fixtures/payloads/valid/empty.json | 0 .../fixtures/payloads/valid/reference.json | 0 .../fixtures/states/all-missing.json | 0 .../fixtures/states/climate-defaults.json | 0 .../fixtures/states/climate-heating.json | 0 .../fixtures/states/entity-missing.json | 0 .../fixtures/states/entity-precision.json | 0 .../fixtures/states/light-dimmable-off.json | 0 .../fixtures/states/light-dimmable-on.json | 0 .../fixtures/states/light-onoff.json | 0 .../fixtures/states/light-unavailable.json | 0 protocol/README.md | 28 ------------- requirements_test.txt | 3 -- tests/docs/__init__.py | 0 tests/protocol/__init__.py | 0 74 files changed, 110 insertions(+), 111 deletions(-) create mode 100644 .claude/CLAUDE.md rename pyproject.toml => .github/scripts/pyproject.toml (87%) create mode 100644 .github/scripts/requirements.txt rename {tests => .github/scripts/tests}/__init__.py (100%) rename tests/docs/test_links.py => .github/scripts/tests/test_docs_links.py (80%) rename tests/protocol/test_fixtures.py => .github/scripts/tests/test_protocol_fixtures.py (95%) delete mode 100644 CLAUDE.md rename docs/{protocol.md => protocol/README.md} (79%) rename {protocol => docs/protocol}/fixtures/colors.json (100%) rename {protocol => docs/protocol}/fixtures/controls/climate-clamp.json (100%) rename {protocol => docs/protocol}/fixtures/controls/climate-set.json (100%) rename {protocol => docs/protocol}/fixtures/controls/ignored-bad-value.json (100%) rename {protocol => docs/protocol}/fixtures/controls/ignored-climate-toggle.json (100%) rename {protocol => docs/protocol}/fixtures/controls/ignored-custom-block.json (100%) rename {protocol => docs/protocol}/fixtures/controls/ignored-unknown-block.json (100%) rename {protocol => docs/protocol}/fixtures/controls/light-set-over.json (100%) rename {protocol => docs/protocol}/fixtures/controls/light-set-zero.json (100%) rename {protocol => docs/protocol}/fixtures/controls/light-set.json (100%) rename {protocol => docs/protocol}/fixtures/controls/light-toggle.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/coordinate_out_of_range.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/disconnected.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/duplicate_id.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/duplicate_position.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_background.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_entity-item.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_entity.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_font_size-item.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_font_size.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_id.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_item.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_name.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_sleep_timeout.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_start-empty.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_start.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_structure-settings.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_structure-version.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_structure.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_text.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/invalid_type.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/too_many_blocks.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/too_many_items.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/invalid/unsupported_emoji.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/valid/emoji-variation.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/valid/empty.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/valid/reference.json (100%) rename {protocol => docs/protocol}/fixtures/layouts/valid/single.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/invalid/bad_json-array.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/invalid/bad_json.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/invalid/invalid_payload-sleep.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/invalid/invalid_payload-widget.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/invalid/invalid_payload.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/invalid/unsupported_version.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/valid/emoji-variation.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/valid/empty.json (100%) rename {protocol => docs/protocol}/fixtures/payloads/valid/reference.json (100%) rename {protocol => docs/protocol}/fixtures/states/all-missing.json (100%) rename {protocol => docs/protocol}/fixtures/states/climate-defaults.json (100%) rename {protocol => docs/protocol}/fixtures/states/climate-heating.json (100%) rename {protocol => docs/protocol}/fixtures/states/entity-missing.json (100%) rename {protocol => docs/protocol}/fixtures/states/entity-precision.json (100%) rename {protocol => docs/protocol}/fixtures/states/light-dimmable-off.json (100%) rename {protocol => docs/protocol}/fixtures/states/light-dimmable-on.json (100%) rename {protocol => docs/protocol}/fixtures/states/light-onoff.json (100%) rename {protocol => docs/protocol}/fixtures/states/light-unavailable.json (100%) delete mode 100644 protocol/README.md delete mode 100644 requirements_test.txt delete mode 100644 tests/docs/__init__.py delete mode 100644 tests/protocol/__init__.py diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md new file mode 100644 index 0000000..44c143c --- /dev/null +++ b/.claude/CLAUDE.md @@ -0,0 +1,42 @@ +# HA Controller — guidance for Claude Code + +HA Controller turns the Waveshare ESP32-S3-Touch-AMOLED-1.75 round touch screen into a Home Assistant remote. +It is a custom integration with a sidebar panel, an ESPHome firmware and a GitHub Pages web installer. + +## Rules + +- English only: code, comments, docs and commit messages. +- One version for the whole repository. Change it only with `python .github/scripts/versioning.py bump X.Y.Z` (added in plan 5). +- The protocol is defined in `docs/protocol/README.md` and pinned by `docs/protocol/fixtures/`. +- The repository root holds no files except README.md, hacs.json and .gitignore. Put every new file in the folder that owns it (see the repository map). +- TDD: write the failing test first, then the code. +- Never commit `esphome/secrets.yaml`. +- Specs and plans live in `docs/superpowers/`. + +## Repository map + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/protocol/` holds the protocol doc (`README.md`) and its shared fixtures (`fixtures/`), the cross-language contract. `docs/superpowers/` holds this spec and the plans. | +| `custom_components/` | Everything for the Home Assistant integration. HACS allows a single directory here, so development files live inside it, or next to it as plain files. | +| `custom_components/ha_controller/` | The integration (Python). Also holds `emoji.json` (canonical emoji list, also read by the firmware build and the panel), `brand/`, `tests/` (pytest), and `frontend/` (panel source in TypeScript, Lit and Vite, built to `frontend/dist/`, which is git-ignored). | +| `custom_components/pyproject.toml`, `requirements_test.txt`, `__init__.py` | Python test and lint configuration for the integration. The empty `__init__.py` keeps test imports under `custom_components.ha_controller`. | +| `esphome/` | Everything for the firmware: device config, packages, simulator config, external components, C++ host tests, web installer page, `requirements.txt` (ESPHome version) and its venv (`esphome/.venv`, git-ignored) | +| `.github/workflows/` | CI, firmware CI, release | +| `.github/scripts/` | Release and repository-check tooling (versioning, packaging, GitHub Pages site builder, docs and fixture checks), with its own `pyproject.toml`, `requirements.txt` and `tests/` | +| `.claude/` | `CLAUDE.md`, Claude Code skills and agents | +| `3D_models/`, `files/` | Existing enclosure models (unchanged) | + +## Commands + +```bash +python3.14 -m venv .github/scripts/.venv +.github/scripts/.venv/bin/pip install -r .github/scripts/requirements.txt +.github/scripts/.venv/bin/pytest .github/scripts/tests +.github/scripts/.venv/bin/ruff check .github/scripts +``` + +## Skills and agents + +- Skill `protocol-change` (`.claude/skills/protocol-change/`): checklist for any change that crosses the Home Assistant ↔ screen boundary. +- Agent `protocol-guardian` (`.claude/agents/protocol-guardian.md`): reviews a diff for protocol consistency across docs, fixtures, Python, TypeScript and C++. diff --git a/.claude/agents/protocol-guardian.md b/.claude/agents/protocol-guardian.md index ebc4af8..b51edb3 100644 --- a/.claude/agents/protocol-guardian.md +++ b/.claude/agents/protocol-guardian.md @@ -1,15 +1,15 @@ --- name: protocol-guardian -description: Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol.md, protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging. +description: Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol/README.md, docs/protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging. tools: Read, Grep, Glob, Bash --- You review protocol changes. Read the diff (`git diff main...HEAD`), then check: -- Field names, error codes, limits and constants are identical in `docs/protocol.md`, the Python integration, the TypeScript model and the C++ parsers. -- Fixtures under `protocol/fixtures/` are updated, and each invalid layout fixture still breaks exactly one rule. -- Golden `rev` values are recomputed (see `protocol/README.md`). +- Field names, error codes, limits and constants are identical in `docs/protocol/README.md`, the Python integration, the TypeScript model and the C++ parsers. +- Fixtures under `docs/protocol/fixtures/` are updated, and each invalid layout fixture still breaks exactly one rule. +- Golden `rev` values are recomputed (see `docs/protocol/README.md`). - `PROTOCOL_VERSION` is bumped in `const.py` and `ha_controller.h` on breaking changes. -- `docs/protocol.md` describes the new behaviour. +- `docs/protocol/README.md` describes the new behaviour. Output a list of `file:line — inconsistency — fix`, or "Protocol consistent". diff --git a/.claude/skills/protocol-change/SKILL.md b/.claude/skills/protocol-change/SKILL.md index 7a50e3a..53645df 100644 --- a/.claude/skills/protocol-change/SKILL.md +++ b/.claude/skills/protocol-change/SKILL.md @@ -6,8 +6,8 @@ description: "Use when changing anything that crosses the Home Assistant ↔ scr # Changing the HA ↔ screen protocol 1. Classify the change. The C++ parser rejects unknown `widget`/`kind`/`font` values, so any new value is breaking: bump `PROTOCOL_VERSION` in `custom_components/ha_controller/const.py` and in the firmware's `ha_controller.h`. -2. Edit `docs/protocol.md` first. -3. Update `protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet in `protocol/README.md`. -4. Update the Python code (`layout.py`, `compiler.py`, `states.py`, `controls.py`), the TypeScript model (`frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). -5. Run `pytest`, `npm --prefix frontend test`, the host C++ tests and `esphome compile`. +2. Edit `docs/protocol/README.md` first. +3. Update `docs/protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet in `docs/protocol/README.md`. +4. Update the Python code in `custom_components/ha_controller/` (`layout.py`, `compiler.py`, `states.py`, `controls.py`) with its tests in `custom_components/ha_controller/tests`, the TypeScript model (`custom_components/ha_controller/frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). +5. Run `pytest custom_components/ha_controller/tests`, `pytest .github/scripts/tests`, `npm --prefix custom_components/ha_controller/frontend test`, the host C++ tests and `esphome compile`. 6. Ask the `protocol-guardian` agent to review. diff --git a/pyproject.toml b/.github/scripts/pyproject.toml similarity index 87% rename from pyproject.toml rename to .github/scripts/pyproject.toml index 6e970aa..9fe26ce 100644 --- a/pyproject.toml +++ b/.github/scripts/pyproject.toml @@ -1,6 +1,5 @@ [tool.pytest.ini_options] testpaths = ["tests"] -asyncio_mode = "auto" [tool.ruff] target-version = "py314" diff --git a/.github/scripts/requirements.txt b/.github/scripts/requirements.txt new file mode 100644 index 0000000..71cc539 --- /dev/null +++ b/.github/scripts/requirements.txt @@ -0,0 +1,2 @@ +pytest +ruff diff --git a/tests/__init__.py b/.github/scripts/tests/__init__.py similarity index 100% rename from tests/__init__.py rename to .github/scripts/tests/__init__.py diff --git a/tests/docs/test_links.py b/.github/scripts/tests/test_docs_links.py similarity index 80% rename from tests/docs/test_links.py rename to .github/scripts/tests/test_docs_links.py index aacf285..3e7aa12 100644 --- a/tests/docs/test_links.py +++ b/.github/scripts/tests/test_docs_links.py @@ -3,8 +3,8 @@ import re from pathlib import Path -ROOT = Path(__file__).resolve().parents[2] -DOC_ROOTS = ["README.md", "CLAUDE.md", "docs"] # docs/superpowers/** is excluded +ROOT = Path(__file__).resolve().parents[3] +DOC_ROOTS = ["README.md", ".claude/CLAUDE.md", "docs"] # docs/superpowers/** is excluded EXCLUDED = ROOT / "docs" / "superpowers" LINK_RE = re.compile(r"\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") EXTERNAL_PREFIXES = ("http://", "https://", "mailto:", "#") @@ -41,7 +41,11 @@ def test_docs_index_lists_every_doc(): for t in LINK_RE.findall(index.read_text(encoding="utf-8")) if not t.startswith(EXTERNAL_PREFIXES) } + docs = ROOT / "docs" + candidates = [*docs.glob("*.md"), *docs.glob("*/README.md")] missing = [ - p.name for p in (ROOT / "docs").glob("*.md") if p != index and p.resolve() not in linked + str(p.relative_to(docs)) + for p in candidates + if p != index and EXCLUDED not in p.parents and p.resolve() not in linked ] assert not missing, f"Docs not linked from docs/README.md: {missing}" diff --git a/tests/protocol/test_fixtures.py b/.github/scripts/tests/test_protocol_fixtures.py similarity index 95% rename from tests/protocol/test_fixtures.py rename to .github/scripts/tests/test_protocol_fixtures.py index efa38c4..c85cd13 100644 --- a/tests/protocol/test_fixtures.py +++ b/.github/scripts/tests/test_protocol_fixtures.py @@ -1,11 +1,11 @@ -"""Executable protocol contract: shape and golden values of protocol/fixtures.""" +"""Executable protocol contract: shape and golden values of docs/protocol/fixtures.""" import hashlib import json from pathlib import Path -ROOT = Path(__file__).resolve().parents[2] -FIXTURES = ROOT / "protocol" / "fixtures" +ROOT = Path(__file__).resolve().parents[3] +FIXTURES = ROOT / "docs" / "protocol" / "fixtures" EMOJI = ROOT / "custom_components" / "ha_controller" / "emoji.json" LAYOUT_CODES = { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c79722b..966375b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,13 +6,13 @@ on: pull_request: jobs: - python: + repo-checks: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.14" - - run: pip install -r requirements_test.txt - - run: ruff check . - - run: pytest + - run: pip install -r .github/scripts/requirements.txt + - run: ruff check .github/scripts + - run: pytest .github/scripts/tests diff --git a/.gitignore b/.gitignore index 6fc4a9d..b4e3f1f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ __pycache__/ .venv*/ node_modules/ frontend/coverage/ -custom_components/ha_controller/frontend/*.js esphome/.esphome/ esphome/secrets.yaml build/ diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index d87fa04..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,42 +0,0 @@ -# HA Controller — guidance for Claude Code - -HA Controller turns the Waveshare ESP32-S3-Touch-AMOLED-1.75 round touch screen into a Home Assistant remote. -It is a custom integration with a sidebar panel, an ESPHome firmware and a GitHub Pages web installer. - -## Rules - -- English only: code, comments, docs and commit messages. -- One version for the whole repository. Change it only with `python scripts/versioning.py bump X.Y.Z` (added in plan 5). -- The protocol is defined in `docs/protocol.md` and pinned by `protocol/fixtures/`. -- TDD: write the failing test first, then the code. -- Never commit `esphome/secrets.yaml`. -- Specs and plans live in `docs/superpowers/`. - -## Repository map - -| Path | Content | -|---|---| -| `docs/` | User and developer documentation. `docs/superpowers/` holds this spec and the plans. | -| `protocol/fixtures/` | Shared test fixtures: the cross-language contract | -| `custom_components/ha_controller/` | Home Assistant integration (Python) | -| `custom_components/ha_controller/emoji.json` | Canonical list of supported emoji, read by the firmware build, the panel and the integration | -| `custom_components/ha_controller/frontend/` | Built panel bundle (generated, git-ignored) | -| `frontend/` | Panel source (TypeScript, Lit, Vite) | -| `esphome/` | Firmware: device config, packages, simulator config, external components, host tests, web installer page | -| `scripts/` | Versioning, packaging, GitHub Pages site builder | -| `tests/` | Python tests (protocol fixtures, docs, integration, scripts) | -| `.claude/` | Claude Code skills and agents | -| `.github/workflows/` | CI, firmware CI, release | -| `3D_models/`, `files/` | Existing enclosure models (unchanged) | - -## Commands - -| Command | Purpose | -|---|---| -| `pytest` | Run the Python tests | -| `ruff check .` | Lint the Python code | - -## Skills and agents - -- Skill `protocol-change` (`.claude/skills/protocol-change/`): checklist for any change that crosses the Home Assistant ↔ screen boundary. -- Agent `protocol-guardian` (`.claude/agents/protocol-guardian.md`): reviews a diff for protocol consistency across docs, fixtures, Python, TypeScript and C++. diff --git a/docs/README.md b/docs/README.md index 1fd5cd1..8af78e5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,4 +2,4 @@ - [Architecture](architecture.md): subsystems, data flow and repository layout. - [Design specification](superpowers/specs/2026-11-16-ha-controller-design.md): the approved design for version 1, with the plans in `superpowers/plans/`. -- [Device protocol v1](protocol.md): the normative layout model and device protocol, pinned by `protocol/fixtures/`. +- [Device protocol v1](protocol/README.md): the normative layout model and device protocol, pinned by `docs/protocol/fixtures/`. diff --git a/docs/architecture.md b/docs/architecture.md index 232ae1c..840f552 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,13 +27,13 @@ HA Controller has three parts: a Home Assistant custom integration with a sideba - The integration is the single source of truth for both the layout and the version. The firmware is a generic renderer. - **Integration** (`custom_components/ha_controller/`): stores and validates layouts, compiles them into the device payload, runs the sync engine and exposes the websocket API used by the panel. -- **Panel** (`frontend/`): the block map editor, built with Lit and Vite and served from the integration. +- **Panel** (`custom_components/ha_controller/frontend/`): the block map editor, built with Lit and Vite and served from the integration. - **Firmware** (`esphome/`): a generic renderer. It parses the layout and states it receives, draws the blocks and reports touches as events. -- **Distribution** (`scripts/`, `.github/workflows/`): HACS release zip, firmware builds and the web installer on GitHub Pages. +- **Distribution** (`.github/scripts/`, `.github/workflows/`): HACS release zip, firmware builds and the web installer on GitHub Pages. ## Handshake: hello, layout and states -When the screen connects (or reboots) it fires a `hello` event carrying its firmware version and the protocol version. The integration answers with `set_layout` (the compiled layout payload with its revision) and then `set_states` (the current Home Assistant states of the entities the layout uses). Afterwards it sends `set_states` again whenever a watched entity changes, and `set_layout` whenever the stored layout changes. The exact messages are defined in `docs/protocol.md` and pinned by `protocol/fixtures/`. +When the screen connects (or reboots) it fires a `hello` event carrying its firmware version and the protocol version. When the revision differs, the integration answers with `set_layout` (the compiled layout payload with its revision) and then `set_states` (the current Home Assistant states of the entities the layout uses). The integration pushes the layout only when the hello's revision differs from its own, and after a `connected` hello with the same revision it pushes all states. Afterwards it sends `set_states` again whenever a watched entity changes, and `set_layout` whenever the stored layout changes. The exact messages are defined in `docs/protocol/README.md` and pinned by `docs/protocol/fixtures/`. ## Controls become service calls @@ -45,17 +45,16 @@ The integration version is the single version of the repository. The integration ## Repository layout +The repository root holds no files except `README.md` (GitHub and HACS landing page), `hacs.json` (HACS reads it only at the root) and `.gitignore`. Everything else lives in a folder: + | Path | Content | |---|---| -| `docs/` | User and developer documentation. `docs/superpowers/` holds this spec and the plans. | -| `protocol/fixtures/` | Shared test fixtures: the cross-language contract | -| `custom_components/ha_controller/` | Home Assistant integration (Python) | -| `custom_components/ha_controller/emoji.json` | Canonical list of supported emoji, read by the firmware build, the panel and the integration | -| `custom_components/ha_controller/frontend/` | Built panel bundle (generated, git-ignored) | -| `frontend/` | Panel source (TypeScript, Lit, Vite) | -| `esphome/` | Firmware: device config, packages, simulator config, external components, host tests, web installer page | -| `scripts/` | Versioning, packaging, GitHub Pages site builder | -| `tests/` | Python tests (protocol fixtures, docs, integration, scripts) | -| `.claude/` | Claude Code skills and agents | +| `docs/` | User and developer documentation. `docs/protocol/` holds the protocol doc (`README.md`) and its shared fixtures (`fixtures/`), the cross-language contract. `docs/superpowers/` holds this spec and the plans. | +| `custom_components/` | Everything for the Home Assistant integration. HACS allows a single directory here, so development files live inside it, or next to it as plain files. | +| `custom_components/ha_controller/` | The integration (Python). Also holds `emoji.json` (canonical emoji list, also read by the firmware build and the panel), `brand/`, `tests/` (pytest), and `frontend/` (panel source in TypeScript, Lit and Vite, built to `frontend/dist/`, which is git-ignored). | +| `custom_components/pyproject.toml`, `requirements_test.txt`, `__init__.py` | Python test and lint configuration for the integration. The empty `__init__.py` keeps test imports under `custom_components.ha_controller`. | +| `esphome/` | Everything for the firmware: device config, packages, simulator config, external components, C++ host tests, web installer page, `requirements.txt` (ESPHome version) and its venv (`esphome/.venv`, git-ignored) | | `.github/workflows/` | CI, firmware CI, release | +| `.github/scripts/` | Release and repository-check tooling (versioning, packaging, GitHub Pages site builder, docs and fixture checks), with its own `pyproject.toml`, `requirements.txt` and `tests/` | +| `.claude/` | `CLAUDE.md`, Claude Code skills and agents | | `3D_models/`, `files/` | Existing enclosure models (unchanged) | diff --git a/docs/protocol.md b/docs/protocol/README.md similarity index 79% rename from docs/protocol.md rename to docs/protocol/README.md index 75b4554..9f06f91 100644 --- a/docs/protocol.md +++ b/docs/protocol/README.md @@ -2,7 +2,7 @@ ## 6. Layout model (integration and panel) -The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: +The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `docs/protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: ```json { "version": 1, "start": "b1", "settings": { "sleep_timeout": 20 }, "blocks": [ @@ -54,7 +54,7 @@ Entities that do not exist (yet) are valid; the screen shows them as unavailable ## 7. Device protocol v1 (normative) -`PROTOCOL_VERSION = 1`. `docs/protocol.md` is the living copy of this section. `protocol/fixtures/` pins it with examples, used by the tests of all three implementations. +`PROTOCOL_VERSION = 1`. This page is the living copy of this section. `docs/protocol/fixtures/` pins it with examples, used by the tests of all three implementations. **7.1 Actions (Home Assistant → screen).** Services `esphome._`: @@ -138,4 +138,31 @@ Anything else is ignored: an unknown block, a custom block, an unparsable value. ## Fixtures -The examples that pin this protocol live in [protocol/fixtures](../protocol/README.md). All three implementations test themselves against them. +`fixtures/` is the executable contract of this protocol. The examples pin it, and all three implementations test themselves against them. All files are UTF-8 JSON without a BOM. + +| Folder | Content | Read by | +|---|---|---| +| `fixtures/layouts/valid`, `fixtures/layouts/invalid` | Stored layouts and the validation error each invalid one must produce | pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test` | +| `fixtures/payloads/valid` | A stored layout and the compiled payload (with golden `rev`) | pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test`, doctest in `esphome/tests` | +| `fixtures/payloads/invalid` | Raw strings sent to `set_layout` and the parse error expected | doctest in `esphome/tests` | +| `fixtures/states` | Home Assistant states and the expected update objects | pytest in `custom_components/ha_controller/tests` | +| `fixtures/controls` | Control events and the expected service call | pytest in `custom_components/ha_controller/tests` | +| `fixtures/colors.json` | Background colours and the expected text colour | pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test`, doctest in `esphome/tests` | + +The consumers are: + +- pytest: `custom_components/ha_controller/tests` and `.github/scripts/tests` (the latter checks the fixtures themselves); +- vitest: `custom_components/ha_controller/frontend/test`; +- doctest: `esphome/tests`. + +### One broken rule per invalid fixture + +Each file in `fixtures/layouts/invalid` takes a valid layout and breaks exactly one rule. Its stem is the expected error code, or the code followed by `-` and a suffix when a code has several cases. + +### Canonical revision + +```python +hashlib.sha256(json.dumps(p, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()[:8] +``` + +`p` is the payload without its `rev` key. Recompute the golden `rev` of `fixtures/payloads/valid/*.json` whenever a payload changes. diff --git a/protocol/fixtures/colors.json b/docs/protocol/fixtures/colors.json similarity index 100% rename from protocol/fixtures/colors.json rename to docs/protocol/fixtures/colors.json diff --git a/protocol/fixtures/controls/climate-clamp.json b/docs/protocol/fixtures/controls/climate-clamp.json similarity index 100% rename from protocol/fixtures/controls/climate-clamp.json rename to docs/protocol/fixtures/controls/climate-clamp.json diff --git a/protocol/fixtures/controls/climate-set.json b/docs/protocol/fixtures/controls/climate-set.json similarity index 100% rename from protocol/fixtures/controls/climate-set.json rename to docs/protocol/fixtures/controls/climate-set.json diff --git a/protocol/fixtures/controls/ignored-bad-value.json b/docs/protocol/fixtures/controls/ignored-bad-value.json similarity index 100% rename from protocol/fixtures/controls/ignored-bad-value.json rename to docs/protocol/fixtures/controls/ignored-bad-value.json diff --git a/protocol/fixtures/controls/ignored-climate-toggle.json b/docs/protocol/fixtures/controls/ignored-climate-toggle.json similarity index 100% rename from protocol/fixtures/controls/ignored-climate-toggle.json rename to docs/protocol/fixtures/controls/ignored-climate-toggle.json diff --git a/protocol/fixtures/controls/ignored-custom-block.json b/docs/protocol/fixtures/controls/ignored-custom-block.json similarity index 100% rename from protocol/fixtures/controls/ignored-custom-block.json rename to docs/protocol/fixtures/controls/ignored-custom-block.json diff --git a/protocol/fixtures/controls/ignored-unknown-block.json b/docs/protocol/fixtures/controls/ignored-unknown-block.json similarity index 100% rename from protocol/fixtures/controls/ignored-unknown-block.json rename to docs/protocol/fixtures/controls/ignored-unknown-block.json diff --git a/protocol/fixtures/controls/light-set-over.json b/docs/protocol/fixtures/controls/light-set-over.json similarity index 100% rename from protocol/fixtures/controls/light-set-over.json rename to docs/protocol/fixtures/controls/light-set-over.json diff --git a/protocol/fixtures/controls/light-set-zero.json b/docs/protocol/fixtures/controls/light-set-zero.json similarity index 100% rename from protocol/fixtures/controls/light-set-zero.json rename to docs/protocol/fixtures/controls/light-set-zero.json diff --git a/protocol/fixtures/controls/light-set.json b/docs/protocol/fixtures/controls/light-set.json similarity index 100% rename from protocol/fixtures/controls/light-set.json rename to docs/protocol/fixtures/controls/light-set.json diff --git a/protocol/fixtures/controls/light-toggle.json b/docs/protocol/fixtures/controls/light-toggle.json similarity index 100% rename from protocol/fixtures/controls/light-toggle.json rename to docs/protocol/fixtures/controls/light-toggle.json diff --git a/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json b/docs/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json similarity index 100% rename from protocol/fixtures/layouts/invalid/coordinate_out_of_range.json rename to docs/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json diff --git a/protocol/fixtures/layouts/invalid/disconnected.json b/docs/protocol/fixtures/layouts/invalid/disconnected.json similarity index 100% rename from protocol/fixtures/layouts/invalid/disconnected.json rename to docs/protocol/fixtures/layouts/invalid/disconnected.json diff --git a/protocol/fixtures/layouts/invalid/duplicate_id.json b/docs/protocol/fixtures/layouts/invalid/duplicate_id.json similarity index 100% rename from protocol/fixtures/layouts/invalid/duplicate_id.json rename to docs/protocol/fixtures/layouts/invalid/duplicate_id.json diff --git a/protocol/fixtures/layouts/invalid/duplicate_position.json b/docs/protocol/fixtures/layouts/invalid/duplicate_position.json similarity index 100% rename from protocol/fixtures/layouts/invalid/duplicate_position.json rename to docs/protocol/fixtures/layouts/invalid/duplicate_position.json diff --git a/protocol/fixtures/layouts/invalid/invalid_background.json b/docs/protocol/fixtures/layouts/invalid/invalid_background.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_background.json rename to docs/protocol/fixtures/layouts/invalid/invalid_background.json diff --git a/protocol/fixtures/layouts/invalid/invalid_entity-item.json b/docs/protocol/fixtures/layouts/invalid/invalid_entity-item.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_entity-item.json rename to docs/protocol/fixtures/layouts/invalid/invalid_entity-item.json diff --git a/protocol/fixtures/layouts/invalid/invalid_entity.json b/docs/protocol/fixtures/layouts/invalid/invalid_entity.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_entity.json rename to docs/protocol/fixtures/layouts/invalid/invalid_entity.json diff --git a/protocol/fixtures/layouts/invalid/invalid_font_size-item.json b/docs/protocol/fixtures/layouts/invalid/invalid_font_size-item.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_font_size-item.json rename to docs/protocol/fixtures/layouts/invalid/invalid_font_size-item.json diff --git a/protocol/fixtures/layouts/invalid/invalid_font_size.json b/docs/protocol/fixtures/layouts/invalid/invalid_font_size.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_font_size.json rename to docs/protocol/fixtures/layouts/invalid/invalid_font_size.json diff --git a/protocol/fixtures/layouts/invalid/invalid_id.json b/docs/protocol/fixtures/layouts/invalid/invalid_id.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_id.json rename to docs/protocol/fixtures/layouts/invalid/invalid_id.json diff --git a/protocol/fixtures/layouts/invalid/invalid_item.json b/docs/protocol/fixtures/layouts/invalid/invalid_item.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_item.json rename to docs/protocol/fixtures/layouts/invalid/invalid_item.json diff --git a/protocol/fixtures/layouts/invalid/invalid_name.json b/docs/protocol/fixtures/layouts/invalid/invalid_name.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_name.json rename to docs/protocol/fixtures/layouts/invalid/invalid_name.json diff --git a/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json b/docs/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json rename to docs/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json diff --git a/protocol/fixtures/layouts/invalid/invalid_start-empty.json b/docs/protocol/fixtures/layouts/invalid/invalid_start-empty.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_start-empty.json rename to docs/protocol/fixtures/layouts/invalid/invalid_start-empty.json diff --git a/protocol/fixtures/layouts/invalid/invalid_start.json b/docs/protocol/fixtures/layouts/invalid/invalid_start.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_start.json rename to docs/protocol/fixtures/layouts/invalid/invalid_start.json diff --git a/protocol/fixtures/layouts/invalid/invalid_structure-settings.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure-settings.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_structure-settings.json rename to docs/protocol/fixtures/layouts/invalid/invalid_structure-settings.json diff --git a/protocol/fixtures/layouts/invalid/invalid_structure-version.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure-version.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_structure-version.json rename to docs/protocol/fixtures/layouts/invalid/invalid_structure-version.json diff --git a/protocol/fixtures/layouts/invalid/invalid_structure.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_structure.json rename to docs/protocol/fixtures/layouts/invalid/invalid_structure.json diff --git a/protocol/fixtures/layouts/invalid/invalid_text.json b/docs/protocol/fixtures/layouts/invalid/invalid_text.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_text.json rename to docs/protocol/fixtures/layouts/invalid/invalid_text.json diff --git a/protocol/fixtures/layouts/invalid/invalid_type.json b/docs/protocol/fixtures/layouts/invalid/invalid_type.json similarity index 100% rename from protocol/fixtures/layouts/invalid/invalid_type.json rename to docs/protocol/fixtures/layouts/invalid/invalid_type.json diff --git a/protocol/fixtures/layouts/invalid/too_many_blocks.json b/docs/protocol/fixtures/layouts/invalid/too_many_blocks.json similarity index 100% rename from protocol/fixtures/layouts/invalid/too_many_blocks.json rename to docs/protocol/fixtures/layouts/invalid/too_many_blocks.json diff --git a/protocol/fixtures/layouts/invalid/too_many_items.json b/docs/protocol/fixtures/layouts/invalid/too_many_items.json similarity index 100% rename from protocol/fixtures/layouts/invalid/too_many_items.json rename to docs/protocol/fixtures/layouts/invalid/too_many_items.json diff --git a/protocol/fixtures/layouts/invalid/unsupported_emoji.json b/docs/protocol/fixtures/layouts/invalid/unsupported_emoji.json similarity index 100% rename from protocol/fixtures/layouts/invalid/unsupported_emoji.json rename to docs/protocol/fixtures/layouts/invalid/unsupported_emoji.json diff --git a/protocol/fixtures/layouts/valid/emoji-variation.json b/docs/protocol/fixtures/layouts/valid/emoji-variation.json similarity index 100% rename from protocol/fixtures/layouts/valid/emoji-variation.json rename to docs/protocol/fixtures/layouts/valid/emoji-variation.json diff --git a/protocol/fixtures/layouts/valid/empty.json b/docs/protocol/fixtures/layouts/valid/empty.json similarity index 100% rename from protocol/fixtures/layouts/valid/empty.json rename to docs/protocol/fixtures/layouts/valid/empty.json diff --git a/protocol/fixtures/layouts/valid/reference.json b/docs/protocol/fixtures/layouts/valid/reference.json similarity index 100% rename from protocol/fixtures/layouts/valid/reference.json rename to docs/protocol/fixtures/layouts/valid/reference.json diff --git a/protocol/fixtures/layouts/valid/single.json b/docs/protocol/fixtures/layouts/valid/single.json similarity index 100% rename from protocol/fixtures/layouts/valid/single.json rename to docs/protocol/fixtures/layouts/valid/single.json diff --git a/protocol/fixtures/payloads/invalid/bad_json-array.json b/docs/protocol/fixtures/payloads/invalid/bad_json-array.json similarity index 100% rename from protocol/fixtures/payloads/invalid/bad_json-array.json rename to docs/protocol/fixtures/payloads/invalid/bad_json-array.json diff --git a/protocol/fixtures/payloads/invalid/bad_json.json b/docs/protocol/fixtures/payloads/invalid/bad_json.json similarity index 100% rename from protocol/fixtures/payloads/invalid/bad_json.json rename to docs/protocol/fixtures/payloads/invalid/bad_json.json diff --git a/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json similarity index 100% rename from protocol/fixtures/payloads/invalid/invalid_payload-sleep.json rename to docs/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json diff --git a/protocol/fixtures/payloads/invalid/invalid_payload-widget.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload-widget.json similarity index 100% rename from protocol/fixtures/payloads/invalid/invalid_payload-widget.json rename to docs/protocol/fixtures/payloads/invalid/invalid_payload-widget.json diff --git a/protocol/fixtures/payloads/invalid/invalid_payload.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload.json similarity index 100% rename from protocol/fixtures/payloads/invalid/invalid_payload.json rename to docs/protocol/fixtures/payloads/invalid/invalid_payload.json diff --git a/protocol/fixtures/payloads/invalid/unsupported_version.json b/docs/protocol/fixtures/payloads/invalid/unsupported_version.json similarity index 100% rename from protocol/fixtures/payloads/invalid/unsupported_version.json rename to docs/protocol/fixtures/payloads/invalid/unsupported_version.json diff --git a/protocol/fixtures/payloads/valid/emoji-variation.json b/docs/protocol/fixtures/payloads/valid/emoji-variation.json similarity index 100% rename from protocol/fixtures/payloads/valid/emoji-variation.json rename to docs/protocol/fixtures/payloads/valid/emoji-variation.json diff --git a/protocol/fixtures/payloads/valid/empty.json b/docs/protocol/fixtures/payloads/valid/empty.json similarity index 100% rename from protocol/fixtures/payloads/valid/empty.json rename to docs/protocol/fixtures/payloads/valid/empty.json diff --git a/protocol/fixtures/payloads/valid/reference.json b/docs/protocol/fixtures/payloads/valid/reference.json similarity index 100% rename from protocol/fixtures/payloads/valid/reference.json rename to docs/protocol/fixtures/payloads/valid/reference.json diff --git a/protocol/fixtures/states/all-missing.json b/docs/protocol/fixtures/states/all-missing.json similarity index 100% rename from protocol/fixtures/states/all-missing.json rename to docs/protocol/fixtures/states/all-missing.json diff --git a/protocol/fixtures/states/climate-defaults.json b/docs/protocol/fixtures/states/climate-defaults.json similarity index 100% rename from protocol/fixtures/states/climate-defaults.json rename to docs/protocol/fixtures/states/climate-defaults.json diff --git a/protocol/fixtures/states/climate-heating.json b/docs/protocol/fixtures/states/climate-heating.json similarity index 100% rename from protocol/fixtures/states/climate-heating.json rename to docs/protocol/fixtures/states/climate-heating.json diff --git a/protocol/fixtures/states/entity-missing.json b/docs/protocol/fixtures/states/entity-missing.json similarity index 100% rename from protocol/fixtures/states/entity-missing.json rename to docs/protocol/fixtures/states/entity-missing.json diff --git a/protocol/fixtures/states/entity-precision.json b/docs/protocol/fixtures/states/entity-precision.json similarity index 100% rename from protocol/fixtures/states/entity-precision.json rename to docs/protocol/fixtures/states/entity-precision.json diff --git a/protocol/fixtures/states/light-dimmable-off.json b/docs/protocol/fixtures/states/light-dimmable-off.json similarity index 100% rename from protocol/fixtures/states/light-dimmable-off.json rename to docs/protocol/fixtures/states/light-dimmable-off.json diff --git a/protocol/fixtures/states/light-dimmable-on.json b/docs/protocol/fixtures/states/light-dimmable-on.json similarity index 100% rename from protocol/fixtures/states/light-dimmable-on.json rename to docs/protocol/fixtures/states/light-dimmable-on.json diff --git a/protocol/fixtures/states/light-onoff.json b/docs/protocol/fixtures/states/light-onoff.json similarity index 100% rename from protocol/fixtures/states/light-onoff.json rename to docs/protocol/fixtures/states/light-onoff.json diff --git a/protocol/fixtures/states/light-unavailable.json b/docs/protocol/fixtures/states/light-unavailable.json similarity index 100% rename from protocol/fixtures/states/light-unavailable.json rename to docs/protocol/fixtures/states/light-unavailable.json diff --git a/protocol/README.md b/protocol/README.md deleted file mode 100644 index 6f65acd..0000000 --- a/protocol/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Protocol fixtures - -`fixtures/` is the executable contract of the protocol defined in [docs/protocol.md](../docs/protocol.md). All files are UTF-8 JSON without a BOM. - -## Who reads what - -| Folder | Content | Read by | -|---|---|---| -| `fixtures/layouts/valid`, `fixtures/layouts/invalid` | Stored layouts and the validation error each invalid one must produce | pytest in `tests/integration`, vitest in `frontend/test` | -| `fixtures/payloads/valid` | A stored layout and the compiled payload (with golden `rev`) | pytest in `tests/integration`, vitest in `frontend/test`, doctest in `esphome/tests` | -| `fixtures/payloads/invalid` | Raw strings sent to `set_layout` and the parse error expected | doctest in `esphome/tests` | -| `fixtures/states` | Home Assistant states and the expected update objects | pytest in `tests/integration` | -| `fixtures/controls` | Control events and the expected service call | pytest in `tests/integration` | -| `fixtures/colors.json` | Background colours and the expected text colour | pytest in `tests/integration`, vitest in `frontend/test`, doctest in `esphome/tests` | - -`tests/protocol` checks the fixtures themselves. - -## One broken rule per invalid fixture - -Each file in `layouts/invalid` takes a valid layout and breaks exactly one rule. Its stem is the expected error code, or the code followed by `-` and a suffix when a code has several cases. - -## Canonical revision - -```python -hashlib.sha256(json.dumps(p, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()[:8] -``` - -`p` is the payload without its `rev` key. Recompute the golden `rev` of `payloads/valid/*.json` whenever a payload changes. diff --git a/requirements_test.txt b/requirements_test.txt deleted file mode 100644 index 33489d4..0000000 --- a/requirements_test.txt +++ /dev/null @@ -1,3 +0,0 @@ -pytest -pytest-asyncio -ruff diff --git a/tests/docs/__init__.py b/tests/docs/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/protocol/__init__.py b/tests/protocol/__init__.py deleted file mode 100644 index e69de29..0000000 From 9735236f08d4f78fd244f996301dc46ac1230a85 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:00:41 +0100 Subject: [PATCH 07/49] feat(integration): add integration skeleton and config flow Co-Authored-By: Claude Sonnet 5.5 --- .claude/CLAUDE.md | 7 ++ .github/scripts/make_brand_icon.py | 39 +++++++++++ .github/scripts/requirements.txt | 1 + .github/workflows/ci.yml | 11 +++ .github/workflows/validate.yml | 22 ++++++ custom_components/__init__.py | 0 custom_components/ha_controller/__init__.py | 25 +++++++ .../ha_controller/brand/icon.png | Bin 0 -> 20951 bytes .../ha_controller/brand/icon@2x.png | Bin 0 -> 40945 bytes .../ha_controller/config_flow.py | 58 ++++++++++++++++ custom_components/ha_controller/const.py | 51 ++++++++++++++ custom_components/ha_controller/manifest.json | 14 ++++ custom_components/ha_controller/strings.json | 19 ++++++ .../ha_controller/tests/__init__.py | 0 .../ha_controller/tests/conftest.py | 8 +++ .../ha_controller/tests/helpers.py | 64 ++++++++++++++++++ .../ha_controller/tests/test_config_flow.py | 63 +++++++++++++++++ .../ha_controller/translations/en.json | 19 ++++++ custom_components/pyproject.toml | 12 ++++ custom_components/requirements_test.txt | 3 + hacs.json | 1 + 21 files changed, 417 insertions(+) create mode 100644 .github/scripts/make_brand_icon.py create mode 100644 .github/workflows/validate.yml create mode 100644 custom_components/__init__.py create mode 100644 custom_components/ha_controller/__init__.py create mode 100644 custom_components/ha_controller/brand/icon.png create mode 100644 custom_components/ha_controller/brand/icon@2x.png create mode 100644 custom_components/ha_controller/config_flow.py create mode 100644 custom_components/ha_controller/const.py create mode 100644 custom_components/ha_controller/manifest.json create mode 100644 custom_components/ha_controller/strings.json create mode 100644 custom_components/ha_controller/tests/__init__.py create mode 100644 custom_components/ha_controller/tests/conftest.py create mode 100644 custom_components/ha_controller/tests/helpers.py create mode 100644 custom_components/ha_controller/tests/test_config_flow.py create mode 100644 custom_components/ha_controller/translations/en.json create mode 100644 custom_components/pyproject.toml create mode 100644 custom_components/requirements_test.txt create mode 100644 hacs.json diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 44c143c..f86e414 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -34,6 +34,13 @@ python3.14 -m venv .github/scripts/.venv .github/scripts/.venv/bin/pip install -r .github/scripts/requirements.txt .github/scripts/.venv/bin/pytest .github/scripts/tests .github/scripts/.venv/bin/ruff check .github/scripts +.github/scripts/.venv/bin/python .github/scripts/make_brand_icon.py # regenerate brand icons + +# Integration (own venv, run from the repository root) +python3.14 -m venv custom_components/.venv +custom_components/.venv/bin/pip install -r custom_components/requirements_test.txt +custom_components/.venv/bin/pytest custom_components/ha_controller/tests +custom_components/.venv/bin/ruff check custom_components ``` ## Skills and agents diff --git a/.github/scripts/make_brand_icon.py b/.github/scripts/make_brand_icon.py new file mode 100644 index 0000000..848dc37 --- /dev/null +++ b/.github/scripts/make_brand_icon.py @@ -0,0 +1,39 @@ +"""Generate the integration brand icons (icon.png and icon@2x.png).""" + +from pathlib import Path + +from PIL import Image, ImageDraw + +DESIGN = 512 +OUT = Path(__file__).parents[2] / "custom_components" / "ha_controller" / "brand" + + +def draw(size: int) -> Image.Image: + """Draw the icon at `size` px, scaled from the 512 design.""" + scale = 4 # supersample for smooth edges + px = size * scale + k = px / DESIGN + c = px / 2 + img = Image.new("RGBA", (px, px), (0, 0, 0, 0)) + d = ImageDraw.Draw(img) + + def box(r: float) -> tuple[float, float, float, float]: + return (c - r * k, c - r * k, c + r * k, c + r * k) + + d.ellipse(box(240), fill="#111827") + # Ring and arc are centred on radius 170, so the outer edge is 170 + width / 2. + outer = 170 + 36 / 2 + d.ellipse(box(outer), outline="#374151", width=round(36 * k)) + d.arc(box(outer), 135, 315, fill="#F59E0B", width=round(36 * k)) + d.ellipse(box(40), fill="#F9FAFB") + return img.resize((size, size), Image.LANCZOS) + + +def main() -> None: + OUT.mkdir(parents=True, exist_ok=True) + draw(256).save(OUT / "icon.png") + draw(512).save(OUT / "icon@2x.png") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/requirements.txt b/.github/scripts/requirements.txt index 71cc539..e811611 100644 --- a/.github/scripts/requirements.txt +++ b/.github/scripts/requirements.txt @@ -1,2 +1,3 @@ pytest ruff +pillow diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 966375b..df615a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,3 +16,14 @@ jobs: - run: pip install -r .github/scripts/requirements.txt - run: ruff check .github/scripts - run: pytest .github/scripts/tests + + integration: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.14" + - run: pip install -r custom_components/requirements_test.txt + - run: ruff check custom_components + - run: pytest custom_components/ha_controller/tests diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..d7714d0 --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,22 @@ +name: Validate + +on: + push: + pull_request: + schedule: + - cron: "0 0 * * *" + workflow_dispatch: + +jobs: + hassfest: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: home-assistant/actions/hassfest@master + + hacs: + runs-on: ubuntu-latest + steps: + - uses: hacs/action@main + with: + category: integration diff --git a/custom_components/__init__.py b/custom_components/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_components/ha_controller/__init__.py b/custom_components/ha_controller/__init__.py new file mode 100644 index 0000000..591c2f6 --- /dev/null +++ b/custom_components/ha_controller/__init__.py @@ -0,0 +1,25 @@ +"""The HA Controller integration.""" + +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.typing import ConfigType + +from .const import DOMAIN + +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Set up the integration.""" + return True + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Set up one screen. Filled in by a later task.""" + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Unload one screen. Filled in by a later task.""" + return True diff --git a/custom_components/ha_controller/brand/icon.png b/custom_components/ha_controller/brand/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..b846736932578fab8c3895eb19c62256d13d11fb GIT binary patch literal 20951 zcmV*9Kybf_P)*NklARgaiou zaS3)H#tmbE4L0t!EK9O1*|M}v+TNzTcklmq&V6rpcD2&(&di&(@B3-Bv$L~r-n@6u zxu<>y2oNAZfB*pk1PBlyK!5-N0t5&UAV5_^l==h$l zLL;Ps1|jsR-s`j$wL)MW^gJ>t1ihq32;Bn+%}+qRARwRDS_>uh;~^Oy)=s*|iNtz_ z_jQf{H#$dG3{y%W+ad{21_%^D`3bz5OHgW;pSCQ7@e`$%Yqb<>wNje_(L_S6HKJ0= zggH{yEuAIodOqRzPKFPWb(}elskP&<$-v42-GF#X2)$P*{gkr8&klAy-8F|5A%H8T zaVO^foB@i9KmnAYz}K%jsae`;lN9Q7t;P8OjsegiglOPDC4rn0#3@VLJ%(0uOYUsH z{-~H`zGrI=KBjyAVp>^vZ>7n@P!k$>0lhK|3$1^xrS;3f?(O?#9n(6R6%?TG2o!+7a7|v!68bBxmgP^Jp}@QQ zE1~siLRu|T!ZI!F%9SGeBUwTBD=P>{AI4J(WHgwMpdDud5Kn8Ut(L~^aK!KX`*)7c z5kH{o7FY&8p;8u9rNP_DZ10KY=5_TdBrg7c+LV;0ji>wTG`>aK}Ze6r-#JWsK z@dgcCB86CG7Q7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Pnh2QNxH z!jgr}I2@_7dv~%YPC>BL6iLb2(BH`TvSsQ6C64~KRzbjlUT{nTWA1n zp?3Bd30dHu8k=JSDaT2HVU#=H_$zPA(MMKhmKKX_HU!)#aeb>-AQp|)+YEpot}ijT z-F_F-St(2gyD=Q&EWI9Q-&q@CT2EHKd|WtPZ`L0MKMYeNmp!ic9k92|O}s!dycmk% z&ol|KXqwq`Z|ZoFof<0ZvjOAKG)nm_RcN=u1kB52s-`i6RI^LWg85zskquw3aw+oN znCvuM_=T+aWFbG;m-XY%RtbN%tnP;aVOoTLZ!u@HSt9WC{jxE0fQ7Lg`RGV7zVeU) z*s%GJuVsJP#=&m5;moeXB*;$%r^zR)O%O5Fl^gONzD}|y!$^GXq6ZSv&%+AbeBbwI mUw<($@(-c)|L$9aKD!(^ym9=lM&>&R_}tS*YSn1iM*bg}GGM^~ literal 0 HcmV?d00001 diff --git a/custom_components/ha_controller/config_flow.py b/custom_components/ha_controller/config_flow.py new file mode 100644 index 0000000..32572f6 --- /dev/null +++ b/custom_components/ha_controller/config_flow.py @@ -0,0 +1,58 @@ +"""Config flow for HA Controller.""" + +from typing import Any + +import voluptuous as vol +from homeassistant.config_entries import ConfigFlow, ConfigFlowResult +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import selector + +from .const import CONF_DEVICE_ID, DOMAIN, MANUFACTURER, MODEL + +STEP_USER_SCHEMA = vol.Schema( + { + vol.Required(CONF_DEVICE_ID): selector.DeviceSelector( + selector.DeviceSelectorConfig( + filter=[ + selector.DeviceFilterSelectorConfig( + integration="esphome", manufacturer=MANUFACTURER, model=MODEL + ) + ] + ) + ) + } +) + + +class HaControllerConfigFlow(ConfigFlow, domain=DOMAIN): + """Link one ESPHome screen device per config entry.""" + + VERSION = 1 + + async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: + errors: dict[str, str] = {} + if user_input is not None: + device = dr.async_get(self.hass).async_get(user_input[CONF_DEVICE_ID]) + if device is None or not self._is_screen(device): + errors["base"] = "not_ha_controller" + else: + await self.async_set_unique_id(device.id) + self._abort_if_unique_id_configured() + return self.async_create_entry( + title=device.name_by_user or device.name or "HA Controller", + data={CONF_DEVICE_ID: device.id}, + ) + return self.async_show_form( + step_id="user", + data_schema=self.add_suggested_values_to_schema(STEP_USER_SCHEMA, user_input), + errors=errors, + ) + + def _is_screen(self, device: dr.DeviceEntry) -> bool: + if device.manufacturer != MANUFACTURER or device.model != MODEL: + return False + return any( + (entry := self.hass.config_entries.async_get_entry(entry_id)) is not None + and entry.domain == "esphome" + for entry_id in device.config_entries + ) diff --git a/custom_components/ha_controller/const.py b/custom_components/ha_controller/const.py new file mode 100644 index 0000000..832627d --- /dev/null +++ b/custom_components/ha_controller/const.py @@ -0,0 +1,51 @@ +"""Constants for HA Controller. Protocol v1 values are defined here once.""" + +from datetime import timedelta + +DOMAIN = "ha_controller" +MANUFACTURER = "pyxel-dev" +MODEL = "ha-controller" + +CONF_DEVICE_ID = "device_id" +CONF_AUTO_UPDATE = "auto_update" + +PROTOCOL_VERSION = 1 + +EVENT_HELLO = "esphome.ha_controller_hello" +EVENT_CONTROL = "esphome.ha_controller_control" + +ACTION_SET_LAYOUT = "set_layout" +ACTION_SET_STATES = "set_states" +ACTION_INSTALL_FIRMWARE = "install_firmware" + +MAX_BLOCKS = 32 +MAX_ITEMS = 6 +MAX_NAME_LEN = 32 +MAX_TEXT_LEN = 64 +COORD_LIMIT = 32 +MAX_PAYLOAD_BYTES = 24576 +STATE_CHUNK_BYTES = 8192 + +FONT_SIZES = ("s", "m", "l", "xl") +ENTITY_BLOCK_DOMAINS = ("light", "climate") +ITEM_KINDS = ("text", "emoji", "entity", "battery", "brightness") + +# Screen sleep, in seconds. 0 means never. +DEFAULT_SLEEP_TIMEOUT = 20 +MIN_SLEEP_TIMEOUT = 5 +MAX_SLEEP_TIMEOUT = 3600 + +ONLINE_TIMEOUT = timedelta(seconds=150) +PUSH_RETRY = timedelta(seconds=300) +STATE_COALESCE_SECONDS = 0.2 +INSTALL_TIMEOUT = 300 +AUTO_UPDATE_RETRY = timedelta(seconds=3600) + +PANEL_URL_PATH = "ha-controller" +PANEL_COMPONENT = "ha-controller-panel" +PANEL_TITLE = "HA Controller" +PANEL_ICON = "mdi:remote" +STATIC_URL = "/ha_controller_static" + +FIRMWARE_BASE_URL = "https://pyxel-dev.github.io/HA-controller/firmware" +RELEASE_URL = "https://github.com/pyxel-dev/HA-controller/releases/tag/v{version}" diff --git a/custom_components/ha_controller/manifest.json b/custom_components/ha_controller/manifest.json new file mode 100644 index 0000000..0772eeb --- /dev/null +++ b/custom_components/ha_controller/manifest.json @@ -0,0 +1,14 @@ +{ + "domain": "ha_controller", + "name": "HA Controller", + "after_dependencies": ["esphome"], + "codeowners": ["@pyxel-dev"], + "config_flow": true, + "dependencies": ["frontend", "http", "panel_custom", "websocket_api"], + "documentation": "https://github.com/pyxel-dev/HA-controller/tree/main/docs", + "integration_type": "device", + "iot_class": "local_push", + "issue_tracker": "https://github.com/pyxel-dev/HA-controller/issues", + "requirements": [], + "version": "0.1.0" +} diff --git a/custom_components/ha_controller/strings.json b/custom_components/ha_controller/strings.json new file mode 100644 index 0000000..161c759 --- /dev/null +++ b/custom_components/ha_controller/strings.json @@ -0,0 +1,19 @@ +{ + "config": { + "step": { + "user": { + "title": "Add an HA Controller screen", + "description": "Pick the screen. It must already be added to Home Assistant with the ESPHome integration.", + "data": { + "device_id": "Screen" + } + } + }, + "error": { + "not_ha_controller": "This device is not an HA Controller screen." + }, + "abort": { + "already_configured": "This screen is already set up." + } + } +} diff --git a/custom_components/ha_controller/tests/__init__.py b/custom_components/ha_controller/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_components/ha_controller/tests/conftest.py b/custom_components/ha_controller/tests/conftest.py new file mode 100644 index 0000000..e1e1bb1 --- /dev/null +++ b/custom_components/ha_controller/tests/conftest.py @@ -0,0 +1,8 @@ +"""Shared fixtures for the HA Controller tests.""" + +import pytest + + +@pytest.fixture(autouse=True) +def auto_enable_custom_integrations(enable_custom_integrations): + """Let Home Assistant load the integration from custom_components.""" diff --git a/custom_components/ha_controller/tests/helpers.py b/custom_components/ha_controller/tests/helpers.py new file mode 100644 index 0000000..7a88223 --- /dev/null +++ b/custom_components/ha_controller/tests/helpers.py @@ -0,0 +1,64 @@ +"""Helpers shared by the HA Controller tests.""" + +import json +from pathlib import Path +from typing import Any + +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from custom_components.ha_controller.const import CONF_DEVICE_ID, DOMAIN, MANUFACTURER, MODEL + +NODE = "ha-controller-aabbcc" +FIXTURES = Path(__file__).parents[3] / "docs" / "protocol" / "fixtures" + + +async def register_screen( + hass: HomeAssistant, + *, + name: str = "HA Controller", + manufacturer: str = MANUFACTURER, + model: str = MODEL, + mac: str = "aa:bb:cc:dd:ee:ff", +) -> dr.DeviceEntry: + """Add an ESPHome config entry and a screen device that belongs to it.""" + esphome_entry = MockConfigEntry(domain="esphome", title=name) + esphome_entry.add_to_hass(hass) + return dr.async_get(hass).async_get_or_create( + config_entry_id=esphome_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, mac)}, + name=name, + manufacturer=manufacturer, + model=model, + ) + + +async def setup_screen(hass: HomeAssistant, device: dr.DeviceEntry) -> MockConfigEntry: + """Add and set up the ha_controller entry for a screen device.""" + entry = MockConfigEntry( + domain=DOMAIN, data={CONF_DEVICE_ID: device.id}, unique_id=device.id + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + return entry + + +def hello(device: dr.DeviceEntry, **overrides: Any) -> dict[str, Any]: + """Return a default hello event payload for the screen.""" + data: dict[str, Any] = { + "device_id": device.id, + "node": NODE, + "version": "0.1.0", + "protocol": "1", + "revision": "none", + "reason": "connected", + } + data.update(overrides) + return data + + +def load_fixture(*parts: str) -> Any: + """Read a shared protocol fixture from docs/protocol/fixtures.""" + return json.loads(FIXTURES.joinpath(*parts).read_text(encoding="utf-8")) diff --git a/custom_components/ha_controller/tests/test_config_flow.py b/custom_components/ha_controller/tests/test_config_flow.py new file mode 100644 index 0000000..ad4a82f --- /dev/null +++ b/custom_components/ha_controller/tests/test_config_flow.py @@ -0,0 +1,63 @@ +"""Tests for the HA Controller config flow.""" + +import json +from pathlib import Path + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.data_entry_flow import FlowResultType + +from custom_components.ha_controller.const import DOMAIN + +from .helpers import register_screen, setup_screen + +COMPONENT = Path(__file__).parents[1] + + +async def start_flow_and_submit(hass, user_input): + result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"}) + return await hass.config_entries.flow.async_configure(result["flow_id"], user_input) + + +async def test_user_step_shows_device_selector(hass): + result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"}) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {} + + +async def test_user_step_creates_entry(hass): + device = await register_screen(hass) + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "HA Controller" and result["data"] == {"device_id": device.id} + assert result["result"].unique_id == device.id + + +async def test_user_step_rejects_other_device(hass): + device = await register_screen(hass, model="other") + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "not_ha_controller"} + + +async def test_user_step_aborts_when_already_configured(hass): + device = await register_screen(hass) + await setup_screen(hass, device) + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +async def test_setup_and_unload_entry(hass): + device = await register_screen(hass) + entry = await setup_screen(hass, device) + assert entry.state is ConfigEntryState.LOADED + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.NOT_LOADED + + +def test_strings_match_english_translation(): + strings = json.loads((COMPONENT / "strings.json").read_text(encoding="utf-8")) + english = json.loads((COMPONENT / "translations" / "en.json").read_text(encoding="utf-8")) + assert strings == english diff --git a/custom_components/ha_controller/translations/en.json b/custom_components/ha_controller/translations/en.json new file mode 100644 index 0000000..161c759 --- /dev/null +++ b/custom_components/ha_controller/translations/en.json @@ -0,0 +1,19 @@ +{ + "config": { + "step": { + "user": { + "title": "Add an HA Controller screen", + "description": "Pick the screen. It must already be added to Home Assistant with the ESPHome integration.", + "data": { + "device_id": "Screen" + } + } + }, + "error": { + "not_ha_controller": "This device is not an HA Controller screen." + }, + "abort": { + "already_configured": "This screen is already set up." + } + } +} diff --git a/custom_components/pyproject.toml b/custom_components/pyproject.toml new file mode 100644 index 0000000..0825ec9 --- /dev/null +++ b/custom_components/pyproject.toml @@ -0,0 +1,12 @@ +[tool.pytest.ini_options] +testpaths = ["ha_controller/tests"] +pythonpath = [".."] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" + +[tool.ruff] +target-version = "py314" +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] diff --git a/custom_components/requirements_test.txt b/custom_components/requirements_test.txt new file mode 100644 index 0000000..3b7da4b --- /dev/null +++ b/custom_components/requirements_test.txt @@ -0,0 +1,3 @@ +pytest-homeassistant-custom-component==0.13.375 +home-assistant-frontend==20260930.5 +ruff diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..8f230b3 --- /dev/null +++ b/hacs.json @@ -0,0 +1 @@ +{"name": "HA Controller", "homeassistant": "2026.10.0"} From a7013a27daef47441689ff6a00929ecdfe179b1d Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:03:06 +0100 Subject: [PATCH 08/49] feat(integration): validate layouts against protocol rules Co-Authored-By: Claude Sonnet 5.5 --- custom_components/ha_controller/layout.py | 253 ++++++++++++++++++ .../ha_controller/tests/test_layout.py | 110 ++++++++ 2 files changed, 363 insertions(+) create mode 100644 custom_components/ha_controller/layout.py create mode 100644 custom_components/ha_controller/tests/test_layout.py diff --git a/custom_components/ha_controller/layout.py b/custom_components/ha_controller/layout.py new file mode 100644 index 0000000..21217e9 --- /dev/null +++ b/custom_components/ha_controller/layout.py @@ -0,0 +1,253 @@ +"""Layout model helpers and validation (protocol v1, spec section 6).""" + +from __future__ import annotations + +import json +import re +from collections import deque +from pathlib import Path +from typing import Any, NamedTuple + +from homeassistant.core import HomeAssistant + +from .const import ( + COORD_LIMIT, + DEFAULT_SLEEP_TIMEOUT, + ENTITY_BLOCK_DOMAINS, + FONT_SIZES, + ITEM_KINDS, + MAX_BLOCKS, + MAX_ITEMS, + MAX_NAME_LEN, + MAX_SLEEP_TIMEOUT, + MAX_TEXT_LEN, + MIN_SLEEP_TIMEOUT, +) + +EMOJI_FILE = Path(__file__).parent / "emoji.json" + +_ID_RE = re.compile(r"[a-z][a-z0-9]{0,7}") +_COLOR_RE = re.compile(r"#[0-9A-Fa-f]{6}") +_ENTITY_RE = re.compile(r"[a-z0-9_]+\.[a-z0-9_]+") +_MAX_ATTRIBUTE_LEN = 64 + + +class LayoutError(NamedTuple): + """A validation error; ref is the offending block or item id, or None.""" + + code: str + ref: str | None + + +def empty_layout() -> dict[str, Any]: + """Return the layout of a screen that has no blocks yet.""" + return { + "version": 1, + "start": None, + "settings": {"sleep_timeout": DEFAULT_SLEEP_TIMEOUT}, + "blocks": [], + } + + +def normalize_emoji(text: str) -> str: + """Remove the emoji variation selector U+FE0F.""" + return text.replace("️", "") + + +def load_emoji_file(path: Path) -> frozenset[str]: + """Read the supported emoji list (blocking).""" + return frozenset(json.loads(path.read_text(encoding="utf-8"))) + + +async def async_load_emoji(hass: HomeAssistant) -> frozenset[str]: + """Read the supported emoji list without blocking the event loop.""" + return await hass.async_add_executor_job(load_emoji_file, EMOJI_FILE) + + +def bound_entities(layout: dict[str, Any]) -> dict[str, list[str]]: + """Map entity_id to the ids of the blocks and items bound to it.""" + bound: dict[str, list[str]] = {} + for block in layout["blocks"]: + if block["type"] == "entity": + bound.setdefault(block["entity_id"], []).append(block["id"]) + elif block["type"] == "custom": + for item in block["items"]: + if item["kind"] == "entity": + bound.setdefault(item["entity_id"], []).append(item["id"]) + return bound + + +def _is_int(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +def _is_id(value: Any) -> bool: + return isinstance(value, str) and _ID_RE.fullmatch(value) is not None + + +def _check_structure(layout: Any) -> bool: + if not isinstance(layout, dict): + return False + version = layout.get("version") + if not _is_int(version) or version != 1: + return False + if not isinstance(layout.get("settings"), dict): + return False + blocks = layout.get("blocks") + if not isinstance(blocks, list) or not all(isinstance(b, dict) for b in blocks): + return False + for block in blocks: + if block.get("type") == "custom": + items = block.get("items") + if not isinstance(items, list) or not all(isinstance(i, dict) for i in items): + return False + return True + + +def _valid_entity_item(item: dict[str, Any]) -> bool: + entity_id = item.get("entity_id") + if not isinstance(entity_id, str) or _ENTITY_RE.fullmatch(entity_id) is None: + return False + attribute = item.get("attribute") + return attribute is None or ( + isinstance(attribute, str) and 1 <= len(attribute) <= _MAX_ATTRIBUTE_LEN + ) + + +def _valid_entity_block(block: dict[str, Any]) -> bool: + entity_id = block.get("entity_id") + if not isinstance(entity_id, str) or _ENTITY_RE.fullmatch(entity_id) is None: + return False + return entity_id.split(".", 1)[0] in ENTITY_BLOCK_DOMAINS + + +def _check_item( + item: dict[str, Any], + seen_ids: set[str], + emoji: frozenset[str], + errors: list[LayoutError], +) -> None: + item_id = item.get("id") + ref = item_id if isinstance(item_id, str) else None + if not _is_id(item_id): + errors.append(LayoutError("invalid_id", ref)) + if isinstance(item_id, str): + if item_id in seen_ids: + errors.append(LayoutError("duplicate_id", item_id)) + seen_ids.add(item_id) + kind = item.get("kind") + if kind not in ITEM_KINDS: + errors.append(LayoutError("invalid_item", ref)) + font_size = item.get("font_size") + if font_size is not None and font_size not in FONT_SIZES: + errors.append(LayoutError("invalid_font_size", ref)) + if kind == "text": + text = item.get("text") + if not isinstance(text, str) or not 1 <= len(text) <= MAX_TEXT_LEN: + errors.append(LayoutError("invalid_text", ref)) + elif kind == "emoji": + value = item.get("emoji") + if not isinstance(value, str) or normalize_emoji(value) not in emoji: + errors.append(LayoutError("unsupported_emoji", ref)) + elif kind == "entity" and not _valid_entity_item(item): + errors.append(LayoutError("invalid_entity", ref)) + + +def _check_block( + block: dict[str, Any], + seen_ids: set[str], + positions: set[tuple[int, int]], + emoji: frozenset[str], + errors: list[LayoutError], +) -> None: + block_id = block.get("id") + ref = block_id if isinstance(block_id, str) else None + if not _is_id(block_id): + errors.append(LayoutError("invalid_id", ref)) + if isinstance(block_id, str): + if block_id in seen_ids: + errors.append(LayoutError("duplicate_id", block_id)) + seen_ids.add(block_id) + + x, y = block.get("x"), block.get("y") + if not all(_is_int(v) and -COORD_LIMIT <= v <= COORD_LIMIT for v in (x, y)): + errors.append(LayoutError("coordinate_out_of_range", ref)) + else: + if (x, y) in positions: + errors.append(LayoutError("duplicate_position", ref)) + positions.add((x, y)) + + name = block.get("name") + if not isinstance(name, str) or not 1 <= len(name.strip()) <= MAX_NAME_LEN: + errors.append(LayoutError("invalid_name", ref)) + background = block.get("background") + if not isinstance(background, str) or _COLOR_RE.fullmatch(background) is None: + errors.append(LayoutError("invalid_background", ref)) + if block.get("font_size") not in FONT_SIZES: + errors.append(LayoutError("invalid_font_size", ref)) + + block_type = block.get("type") + if block_type == "entity": + if not _valid_entity_block(block): + errors.append(LayoutError("invalid_entity", ref)) + elif block_type == "custom": + items = block["items"] + if len(items) > MAX_ITEMS: + errors.append(LayoutError("too_many_items", ref)) + for item in items: + _check_item(item, seen_ids, emoji, errors) + else: + errors.append(LayoutError("invalid_type", ref)) + + +def _unreachable(layout: dict[str, Any]) -> list[LayoutError]: + if not layout["blocks"]: + return [] + cells = {(b["x"], b["y"]): b["id"] for b in layout["blocks"]} + start = next(b for b in layout["blocks"] if b["id"] == layout["start"]) + reached = {(start["x"], start["y"])} + queue = deque(reached) + while queue: + x, y = queue.popleft() + for cell in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): + if cell in cells and cell not in reached: + reached.add(cell) + queue.append(cell) + return [ + LayoutError("disconnected", b["id"]) + for b in layout["blocks"] + if (b["x"], b["y"]) not in reached + ] + + +def validate_layout(layout: Any, emoji: frozenset[str]) -> list[LayoutError]: + """Validate a layout; an empty list means it is valid.""" + if not _check_structure(layout): + return [LayoutError("invalid_structure", None)] + + errors: list[LayoutError] = [] + blocks = layout["blocks"] + if len(blocks) > MAX_BLOCKS: + errors.append(LayoutError("too_many_blocks", None)) + timeout = layout["settings"].get("sleep_timeout") + if not _is_int(timeout) or not ( + timeout == 0 or MIN_SLEEP_TIMEOUT <= timeout <= MAX_SLEEP_TIMEOUT + ): + errors.append(LayoutError("invalid_sleep_timeout", None)) + + seen_ids: set[str] = set() + positions: set[tuple[int, int]] = set() + for block in blocks: + _check_block(block, seen_ids, positions, emoji, errors) + + start = layout.get("start") + if start is None: + start_ok = not blocks + else: + start_ok = isinstance(start, str) and any(b.get("id") == start for b in blocks) + if not start_ok: + errors.append(LayoutError("invalid_start", None)) + + if errors: + return errors + return _unreachable(layout) diff --git a/custom_components/ha_controller/tests/test_layout.py b/custom_components/ha_controller/tests/test_layout.py new file mode 100644 index 0000000..1ee67fc --- /dev/null +++ b/custom_components/ha_controller/tests/test_layout.py @@ -0,0 +1,110 @@ +"""Tests for layout validation against the shared protocol fixtures.""" + +import copy +import json +from pathlib import Path +from typing import Any + +import pytest + +from custom_components.ha_controller.const import DEFAULT_SLEEP_TIMEOUT +from custom_components.ha_controller.layout import ( + LayoutError, + async_load_emoji, + bound_entities, + empty_layout, + load_emoji_file, + normalize_emoji, + validate_layout, +) + +from .helpers import FIXTURES, load_fixture + +EMOJI_FILE = Path(__file__).parents[1] / "emoji.json" +EMOJI = load_emoji_file(EMOJI_FILE) +VALID_LAYOUTS = sorted((FIXTURES / "layouts" / "valid").glob("*.json")) +INVALID_LAYOUTS = sorted((FIXTURES / "layouts" / "invalid").glob("*.json")) + + +def reference() -> dict[str, Any]: + return copy.deepcopy(load_fixture("layouts", "valid", "reference.json")) + + +def test_fixture_sets_are_complete() -> None: + assert len(VALID_LAYOUTS) == 4 + assert len(INVALID_LAYOUTS) == 23 + + +@pytest.mark.parametrize("path", VALID_LAYOUTS, ids=lambda p: p.stem) +def test_valid_fixtures(path: Path) -> None: + assert validate_layout(json.loads(path.read_text(encoding="utf-8")), EMOJI) == [] + + +@pytest.mark.parametrize("path", INVALID_LAYOUTS, ids=lambda p: p.stem) +def test_invalid_fixtures(path: Path) -> None: + case = json.loads(path.read_text(encoding="utf-8")) + expect = case["expect"] + assert validate_layout(case["layout"], EMOJI) == [ + LayoutError(expect["code"], expect["ref"]) + ] + + +def test_connectivity_is_skipped_when_fields_are_invalid() -> None: + layout = reference() + layout["blocks"][0]["name"] = "" + layout["blocks"][1]["y"] = -5 # would be disconnected + assert validate_layout(layout, EMOJI) == [LayoutError("invalid_name", "b1")] + + +def test_normalize_emoji_strips_variation_selector() -> None: + assert normalize_emoji("❄️") == "❄" + + +def test_bound_entities_reference() -> None: + assert bound_entities(reference()) == { + "light.kitchen": ["b1"], + "light.living_room": ["b2"], + "sensor.outdoor_temperature": ["i3"], + "climate.bedroom": ["b4"], + } + + +def test_bool_is_not_a_coordinate() -> None: + layout = reference() + layout["blocks"][0]["x"] = True + assert LayoutError("coordinate_out_of_range", "b1") in validate_layout(layout, EMOJI) + + +@pytest.mark.parametrize( + ("value", "ok"), + [(0, True), (5, True), (3600, True), (4, False), (3601, False), (True, False), ("20", False)], +) +def test_sleep_timeout_bounds(value: Any, ok: bool) -> None: + layout = reference() + layout["settings"]["sleep_timeout"] = value + expected = [] if ok else [LayoutError("invalid_sleep_timeout", None)] + assert validate_layout(layout, EMOJI) == expected + + +def test_non_dict_layout_is_invalid_structure() -> None: + assert validate_layout([], EMOJI) == [LayoutError("invalid_structure", None)] + + +def test_empty_layout_is_valid() -> None: + layout = empty_layout() + assert layout == { + "version": 1, + "start": None, + "settings": {"sleep_timeout": DEFAULT_SLEEP_TIMEOUT}, + "blocks": [], + } + assert validate_layout(layout, EMOJI) == [] + + +def test_load_emoji_file() -> None: + assert "💡" in EMOJI + assert len(EMOJI) == 64 + + +async def test_async_load_emoji(hass) -> None: + assert await async_load_emoji(hass) == EMOJI From 2f83d9484ecbe60e50cad2ffb050907e22234e23 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:05:58 +0100 Subject: [PATCH 09/49] test(protocol): pin length counting to Unicode code points Co-Authored-By: Claude Opus 5.5 --- docs/protocol/README.md | 2 ++ .../layouts/invalid/invalid_name-astral.json | 32 +++++++++++++++++++ .../fixtures/layouts/valid/astral-text.json | 26 +++++++++++++++ .../plans/2026-11-16-ha-controller-3-panel.md | 2 +- .../specs/2026-11-16-ha-controller-design.md | 2 ++ 5 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 docs/protocol/fixtures/layouts/invalid/invalid_name-astral.json create mode 100644 docs/protocol/fixtures/layouts/valid/astral-text.json diff --git a/docs/protocol/README.md b/docs/protocol/README.md index 9f06f91..32bbb5c 100644 --- a/docs/protocol/README.md +++ b/docs/protocol/README.md @@ -50,6 +50,8 @@ Validation returns a list of `{code, ref}`, where `ref` is the offending block o | `unsupported_emoji` | Emoji item: after removing U+FE0F, the value is an entry of `emoji.json` | | `payload_too_large` | The compiled payload (§7.3) is larger than 24 576 UTF-8 bytes. Checked by the integration only. | +Lengths count Unicode code points (Python `len`, JavaScript `Array.from(text).length`), and names are trimmed of Unicode whitespace (`str.strip()`, `String.prototype.trim()`). The fixtures `astral-text` (valid) and `invalid_name-astral` pin this. + Entities that do not exist (yet) are valid; the screen shows them as unavailable. ## 7. Device protocol v1 (normative) diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_name-astral.json b/docs/protocol/fixtures/layouts/invalid/invalid_name-astral.json new file mode 100644 index 0000000..99bd713 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_name-astral.json @@ -0,0 +1,32 @@ +{ + "expect": { + "code": "invalid_name", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋", + "font_size": null + } + ] + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/valid/astral-text.json b/docs/protocol/fixtures/layouts/valid/astral-text.json new file mode 100644 index 0000000..2ab4436 --- /dev/null +++ b/docs/protocol/fixtures/layouts/valid/astral-text.json @@ -0,0 +1,26 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋", + "font_size": null + } + ] + } + ] +} diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md index 350c7bf..e929817 100644 --- a/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md +++ b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md @@ -66,7 +66,7 @@ - `reachable(blocks: Block[], start: string | null): Set` - `canDelete(layout, id): {ok: true} | {ok: false, reason: "start" | "disconnects"}` - `gridBounds(cells: Cell[]): {minX, maxX, minY, maxY}` - - **`model/validate.ts`:** `validateLayout(layout: unknown, emoji: ReadonlySet): LayoutError[]`. Same phases and order as plan 2 Task 2. + - **`model/validate.ts`:** `validateLayout(layout: unknown, emoji: ReadonlySet): LayoutError[]`. Same phases and order as plan 2 Task 2. Lengths count code points (`Array.from(text).length`, never `.length`), and names use `trim()`. - **`model/emoji.ts`:** `SUPPORTED_EMOJI: readonly string[]` imported from `../../../emoji.json` (relative to `src/model/`), `EMOJI_SET`, `normalizeEmoji(text): string`. - **`test/fixtures.ts`:** `validLayouts`, `invalidLayouts` and `colors`, loaded with `import.meta.glob("../../../../docs/protocol/fixtures/…", {eager: true, import: "default"})`. diff --git a/docs/superpowers/specs/2026-11-16-ha-controller-design.md b/docs/superpowers/specs/2026-11-16-ha-controller-design.md index 4e63a7f..354433f 100644 --- a/docs/superpowers/specs/2026-11-16-ha-controller-design.md +++ b/docs/superpowers/specs/2026-11-16-ha-controller-design.md @@ -232,6 +232,8 @@ Validation returns a list of `{code, ref}`, where `ref` is the offending block o | `unsupported_emoji` | Emoji item: after removing U+FE0F, the value is an entry of `emoji.json` | | `payload_too_large` | The compiled payload (§7.3) is larger than 24 576 UTF-8 bytes. Checked by the integration only. | +Lengths count Unicode code points (Python `len`, JavaScript `Array.from(text).length`), and names are trimmed of Unicode whitespace (`str.strip()`, `String.prototype.trim()`). The fixtures `astral-text` (valid) and `invalid_name-astral` pin this. + Entities that do not exist (yet) are valid; the screen shows them as unavailable. ## 7. Device protocol v1 (normative) From be7d0c5872b1632f60ce8e168b034a27f0a9e70b Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:07:22 +0100 Subject: [PATCH 10/49] test(integration): make layout fixture checks robust Co-Authored-By: Claude Haiku 5.5 --- custom_components/ha_controller/layout.py | 8 +++- .../ha_controller/tests/test_layout.py | 37 +++++++++++++++++-- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/custom_components/ha_controller/layout.py b/custom_components/ha_controller/layout.py index 21217e9..f7811c2 100644 --- a/custom_components/ha_controller/layout.py +++ b/custom_components/ha_controller/layout.py @@ -104,9 +104,13 @@ def _check_structure(layout: Any) -> bool: return True +def _is_entity_id(value: Any) -> bool: + return isinstance(value, str) and _ENTITY_RE.fullmatch(value) is not None + + def _valid_entity_item(item: dict[str, Any]) -> bool: entity_id = item.get("entity_id") - if not isinstance(entity_id, str) or _ENTITY_RE.fullmatch(entity_id) is None: + if not _is_entity_id(entity_id): return False attribute = item.get("attribute") return attribute is None or ( @@ -116,7 +120,7 @@ def _valid_entity_item(item: dict[str, Any]) -> bool: def _valid_entity_block(block: dict[str, Any]) -> bool: entity_id = block.get("entity_id") - if not isinstance(entity_id, str) or _ENTITY_RE.fullmatch(entity_id) is None: + if not _is_entity_id(entity_id): return False return entity_id.split(".", 1)[0] in ENTITY_BLOCK_DOMAINS diff --git a/custom_components/ha_controller/tests/test_layout.py b/custom_components/ha_controller/tests/test_layout.py index 1ee67fc..a72cb09 100644 --- a/custom_components/ha_controller/tests/test_layout.py +++ b/custom_components/ha_controller/tests/test_layout.py @@ -30,9 +30,39 @@ def reference() -> dict[str, Any]: return copy.deepcopy(load_fixture("layouts", "valid", "reference.json")) +SPEC_ERROR_CODES = frozenset( + { + "invalid_structure", + "too_many_blocks", + "invalid_sleep_timeout", + "invalid_id", + "duplicate_id", + "coordinate_out_of_range", + "duplicate_position", + "invalid_start", + "disconnected", + "invalid_name", + "invalid_background", + "invalid_font_size", + "invalid_type", + "invalid_entity", + "too_many_items", + "invalid_item", + "invalid_text", + "unsupported_emoji", + } +) + + def test_fixture_sets_are_complete() -> None: - assert len(VALID_LAYOUTS) == 4 - assert len(INVALID_LAYOUTS) == 23 + assert VALID_LAYOUTS + assert INVALID_LAYOUTS + covered = { + json.loads(path.read_text(encoding="utf-8"))["expect"]["code"] + for path in INVALID_LAYOUTS + } + missing = sorted(SPEC_ERROR_CODES - covered) + assert not missing, f"no invalid fixture for error codes: {missing}" @pytest.mark.parametrize("path", VALID_LAYOUTS, ids=lambda p: p.stem) @@ -102,8 +132,9 @@ def test_empty_layout_is_valid() -> None: def test_load_emoji_file() -> None: + with EMOJI_FILE.open(encoding="utf-8") as handle: + assert EMOJI == frozenset(json.load(handle)) assert "💡" in EMOJI - assert len(EMOJI) == 64 async def test_async_load_emoji(hass) -> None: From ef0bcc973ea7791a4bcfd66c61b9345074ccd73d Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:08:49 +0100 Subject: [PATCH 11/49] feat(integration): compile layouts into device payloads Co-Authored-By: Claude Sonnet 5.5 --- custom_components/ha_controller/compiler.py | 68 ++++++++++++++++++ .../ha_controller/tests/test_compiler.py | 70 +++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 custom_components/ha_controller/compiler.py create mode 100644 custom_components/ha_controller/tests/test_compiler.py diff --git a/custom_components/ha_controller/compiler.py b/custom_components/ha_controller/compiler.py new file mode 100644 index 0000000..3579496 --- /dev/null +++ b/custom_components/ha_controller/compiler.py @@ -0,0 +1,68 @@ +"""Compile a stored layout into the compact payload sent to the screen.""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any + +from .const import PROTOCOL_VERSION +from .layout import normalize_emoji + + +def _compile_item(item: dict[str, Any], block_font: str) -> dict[str, Any]: + kind = item["kind"] + out: dict[str, Any] = { + "id": item["id"], + "kind": kind, + "font": item["font_size"] or block_font, + } + if kind == "text": + out["text"] = item["text"] + elif kind == "emoji": + out["text"] = normalize_emoji(item["emoji"]) + return out + + +def _compile_block(block: dict[str, Any]) -> dict[str, Any]: + out: dict[str, Any] = { + "id": block["id"], + "x": block["x"], + "y": block["y"], + "name": block["name"].strip(), + "bg": block["background"].lstrip("#").upper(), + "font": block["font_size"], + } + if block["type"] == "entity": + out["widget"] = block["entity_id"].split(".", 1)[0] + else: + out["widget"] = "custom" + out["items"] = [_compile_item(i, block["font_size"]) for i in block["items"]] + return out + + +def payload_revision(payload: dict[str, Any]) -> str: + """Return the 8-hex-char revision of a payload, ignoring any `rev` key.""" + body = {k: v for k, v in payload.items() if k != "rev"} + text = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(text.encode("utf-8")).hexdigest()[:8] + + +def compile_layout(layout: dict[str, Any]) -> dict[str, Any]: + """Compile a valid stored layout into a payload including its `rev`.""" + payload: dict[str, Any] = { + "v": PROTOCOL_VERSION, + "start": layout["start"], + "sleep": layout["settings"]["sleep_timeout"], + "blocks": [_compile_block(b) for b in layout["blocks"]], + } + return { + "v": PROTOCOL_VERSION, + "rev": payload_revision(payload), + **{k: v for k, v in payload.items() if k != "v"}, + } + + +def encode_payload(payload: dict[str, Any]) -> str: + """Return the compact JSON transport encoding of a payload.""" + return json.dumps(payload, separators=(",", ":"), ensure_ascii=False) diff --git a/custom_components/ha_controller/tests/test_compiler.py b/custom_components/ha_controller/tests/test_compiler.py new file mode 100644 index 0000000..2d19d14 --- /dev/null +++ b/custom_components/ha_controller/tests/test_compiler.py @@ -0,0 +1,70 @@ +"""Tests for the layout compiler against the shared protocol fixtures.""" + +from typing import Any + +import pytest + +from custom_components.ha_controller.compiler import ( + compile_layout, + encode_payload, + payload_revision, +) +from custom_components.ha_controller.const import MAX_PAYLOAD_BYTES + +from .helpers import FIXTURES, load_fixture + +VALID_PAYLOADS = sorted((FIXTURES / "payloads" / "valid").glob("*.json")) + + +def load_layout(stem: str) -> dict[str, Any]: + return load_fixture("layouts", "valid", f"{stem}.json") + + +@pytest.mark.parametrize("path", VALID_PAYLOADS, ids=lambda p: p.stem) +def test_golden_payloads(path): + case = load_fixture("payloads", "valid", path.name) + assert compile_layout(load_layout(case["layout"])) == case["payload"] + + +def test_revision_ignores_rev_key(): + payload = {"v": 1, "rev": "zzz", "start": None, "sleep": 20, "blocks": []} + assert payload_revision(payload) == "c4aad3fa" + + +def test_names_are_trimmed(): + layout = load_layout("single") + layout["blocks"][0]["name"] = f" {layout['blocks'][0]['name']}\t" + assert ( + compile_layout(layout)["blocks"][0]["name"] + == compile_layout(load_layout("single"))["blocks"][0]["name"].strip() + ) + + +def test_encode_payload_is_compact_utf8(): + text = encode_payload(compile_layout(load_layout("reference"))) + assert ", " not in text and ": " not in text and "👋" in text + + +def test_huge_layout_exceeds_payload_limit(): + huge = { + "version": 1, + "start": "b0", + "settings": {"sleep_timeout": 20}, + "blocks": [ + { + "id": f"b{n}", + "x": n, + "y": 0, + "name": "é" * 32, + "background": "#112233", + "font_size": "m", + "type": "custom", + "items": [ + {"id": f"i{n}_{k}", "kind": "text", "text": "é" * 64, "font_size": None} + for k in range(6) + ], + } + for n in range(32) + ], + } + assert len(encode_payload(compile_layout(huge)).encode()) > MAX_PAYLOAD_BYTES From 7b2b1ccc7bc0322e314f79471f316afbf8fc4287 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:11:55 +0100 Subject: [PATCH 12/49] feat(integration): build screen state updates Co-Authored-By: Claude Sonnet 5.5 --- custom_components/ha_controller/states.py | 128 ++++++++++++++++++ .../ha_controller/tests/test_states.py | 65 +++++++++ 2 files changed, 193 insertions(+) create mode 100644 custom_components/ha_controller/states.py create mode 100644 custom_components/ha_controller/tests/test_states.py diff --git a/custom_components/ha_controller/states.py b/custom_components/ha_controller/states.py new file mode 100644 index 0000000..1469a83 --- /dev/null +++ b/custom_components/ha_controller/states.py @@ -0,0 +1,128 @@ +"""Build the display-ready state updates the screen receives.""" + +import json +from collections.abc import Collection +from typing import Any + +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .const import STATE_CHUNK_BYTES + +MISSING_TEXT = "—" +MAX_TEXT_LENGTH = 64 +_UNUSABLE = (STATE_UNAVAILABLE, STATE_UNKNOWN) + + +def _precision(hass: HomeAssistant, entity_id: str) -> int | None: + entry = er.async_get(hass).async_get(entity_id) + if entry is None: + return None + options = entry.options.get("sensor") or {} + precision = options.get("display_precision") + if precision is None: + precision = options.get("suggested_display_precision") + return precision + + +def format_entity_text(hass: HomeAssistant, entity_id: str, attribute: str | None) -> str: + """Return the display text of an entity item.""" + state = hass.states.get(entity_id) + if state is None or state.state in _UNUSABLE: + return MISSING_TEXT + if attribute: + if attribute not in state.attributes: + return MISSING_TEXT + return str(state.attributes[attribute])[:MAX_TEXT_LENGTH] + text = state.state + precision = _precision(hass, entity_id) + if precision is not None: + try: + text = f"{float(text):.{int(precision)}f}" + except ValueError: + pass + unit = state.attributes.get("unit_of_measurement") + if unit: + text = f"{text} {unit}" + return text[:MAX_TEXT_LENGTH] + + +def _light_update(block_id: str, state: Any) -> dict[str, Any]: + modes = state.attributes.get("supported_color_modes") or [] + dimmable = any(mode != "onoff" for mode in modes) + is_on = state.state == "on" + brightness = None + if dimmable: + brightness = round((state.attributes.get("brightness") or 255) * 100 / 255) if is_on else 0 + return {"id": block_id, "available": True, "on": is_on, "brightness": brightness} + + +def _climate_update(hass: HomeAssistant, block_id: str, state: Any) -> dict[str, Any]: + attrs = state.attributes + unit = hass.config.units.temperature_unit + current = attrs.get("current_temperature") + action = attrs.get("hvac_action") or state.state + action = str(action).replace("_", " ") + return { + "id": block_id, + "available": True, + "target": attrs.get("temperature"), + "min": attrs.get("min_temp", 7), + "max": attrs.get("max_temp", 35), + "step": attrs.get("target_temp_step") or (0.5 if unit == "°C" else 1), + "unit": unit, + "current": MISSING_TEXT if current is None else f"{current} {unit}", + "action": action[:1].upper() + action[1:], + } + + +def build_updates( + hass: HomeAssistant, layout: dict[str, Any], entity_ids: Collection[str] | None = None +) -> list[dict[str, Any]]: + """Build the updates for the bound entities, in layout order.""" + wanted = None if entity_ids is None else set(entity_ids) + updates: list[dict[str, Any]] = [] + for block in layout["blocks"]: + if block["type"] == "entity": + entity_id = block["entity_id"] + if wanted is not None and entity_id not in wanted: + continue + state = hass.states.get(entity_id) + if state is None or state.state in _UNUSABLE: + updates.append({"id": block["id"], "available": False}) + elif entity_id.startswith("light."): + updates.append(_light_update(block["id"], state)) + elif entity_id.startswith("climate."): + updates.append(_climate_update(hass, block["id"], state)) + else: + updates.append({"id": block["id"], "available": True}) + elif block["type"] == "custom": + for item in block["items"]: + if item["kind"] != "entity": + continue + if wanted is not None and item["entity_id"] not in wanted: + continue + text = format_entity_text(hass, item["entity_id"], item.get("attribute")) + updates.append({"id": item["id"], "text": text}) + return updates + + +def chunk_updates(updates: list[dict[str, Any]], max_bytes: int = STATE_CHUNK_BYTES) -> list[str]: + """Split updates into JSON arrays of at most max_bytes bytes each.""" + + def encode(items: list[dict[str, Any]]) -> str: + return json.dumps(items, separators=(",", ":"), ensure_ascii=False) + + chunks: list[str] = [] + current: list[dict[str, Any]] = [] + for update in updates: + candidate = [*current, update] + if current and len(encode(candidate).encode("utf-8")) > max_bytes: + chunks.append(encode(current)) + current = [update] + else: + current = candidate + if current: + chunks.append(encode(current)) + return chunks diff --git a/custom_components/ha_controller/tests/test_states.py b/custom_components/ha_controller/tests/test_states.py new file mode 100644 index 0000000..227c035 --- /dev/null +++ b/custom_components/ha_controller/tests/test_states.py @@ -0,0 +1,65 @@ +"""Tests for the screen state builders.""" + +import json + +import pytest +from homeassistant.helpers import entity_registry as er +from homeassistant.util.unit_system import METRIC_SYSTEM + +from custom_components.ha_controller.const import STATE_CHUNK_BYTES +from custom_components.ha_controller.states import ( + build_updates, + chunk_updates, + format_entity_text, +) + +from .helpers import FIXTURES, load_fixture +from .test_compiler import load_layout + +STATE_FIXTURES = sorted((FIXTURES / "states").glob("*.json")) + + +@pytest.mark.parametrize("path", STATE_FIXTURES, ids=lambda p: p.stem) +async def test_state_fixtures(hass, path): + case = load_fixture("states", path.name) + hass.config.units = METRIC_SYSTEM + registry = er.async_get(hass) + for entity_id, options in case.get("registry_options", {}).items(): + domain, object_id = entity_id.split(".", 1) + entry = registry.async_get_or_create( + domain, "test", object_id, suggested_object_id=object_id + ) + assert entry.entity_id == entity_id + for option_domain, value in options.items(): + registry.async_update_entity_options(entity_id, option_domain, value) + # Set states after registering: the registry avoids ids that already have a state. + for entity_id, s in case["hass_states"].items(): + hass.states.async_set(entity_id, s["state"], s["attributes"]) + updates = build_updates(hass, load_layout(case["layout"]), case["entity_ids"]) + assert updates == case["updates"] + + +async def test_entity_text_truncated_to_64(hass): + hass.states.async_set("sensor.long", "x" * 100) + assert len(format_entity_text(hass, "sensor.long", None)) == 64 + + +async def test_entity_text_uses_attribute(hass): + hass.states.async_set("sensor.phone", "ok", {"battery": 80, "unit_of_measurement": "%"}) + assert format_entity_text(hass, "sensor.phone", "battery") == "80" + assert format_entity_text(hass, "sensor.phone", "missing") == "—" + + +def test_chunk_updates_splits_by_size(): + updates = [{"id": f"i{n}", "text": "x" * 40} for n in range(300)] + chunks = chunk_updates(updates, STATE_CHUNK_BYTES) + assert len(chunks) > 1 + assert all(len(c.encode("utf-8")) <= STATE_CHUNK_BYTES for c in chunks) + assert [u for c in chunks for u in json.loads(c)] == updates + + +def test_chunk_updates_keeps_oversize_update_alone(): + big = {"id": "i1", "text": "x" * 200} + small = {"id": "i2", "text": "y"} + chunks = chunk_updates([small, big, small], 100) + assert [json.loads(c) for c in chunks] == [[small], [big], [small]] From 207c22dc77b5bc5100206c9f71fae61650526c21 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:14:59 +0100 Subject: [PATCH 13/49] =?UTF-8?q?fix(integration):=20reuse=20MAX=5FTEXT=5F?= =?UTF-8?q?LEN=20and=20cover=20=C2=B0F=20and=20suggested=20precision?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Haiku 5.5 --- custom_components/ha_controller/states.py | 7 ++-- .../ha_controller/tests/test_states.py | 38 ++++++++++++++++++- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/custom_components/ha_controller/states.py b/custom_components/ha_controller/states.py index 1469a83..fc825bf 100644 --- a/custom_components/ha_controller/states.py +++ b/custom_components/ha_controller/states.py @@ -8,10 +8,9 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er -from .const import STATE_CHUNK_BYTES +from .const import MAX_TEXT_LEN, STATE_CHUNK_BYTES MISSING_TEXT = "—" -MAX_TEXT_LENGTH = 64 _UNUSABLE = (STATE_UNAVAILABLE, STATE_UNKNOWN) @@ -34,7 +33,7 @@ def format_entity_text(hass: HomeAssistant, entity_id: str, attribute: str | Non if attribute: if attribute not in state.attributes: return MISSING_TEXT - return str(state.attributes[attribute])[:MAX_TEXT_LENGTH] + return str(state.attributes[attribute])[:MAX_TEXT_LEN] text = state.state precision = _precision(hass, entity_id) if precision is not None: @@ -45,7 +44,7 @@ def format_entity_text(hass: HomeAssistant, entity_id: str, attribute: str | Non unit = state.attributes.get("unit_of_measurement") if unit: text = f"{text} {unit}" - return text[:MAX_TEXT_LENGTH] + return text[:MAX_TEXT_LEN] def _light_update(block_id: str, state: Any) -> dict[str, Any]: diff --git a/custom_components/ha_controller/tests/test_states.py b/custom_components/ha_controller/tests/test_states.py index 227c035..17d6a92 100644 --- a/custom_components/ha_controller/tests/test_states.py +++ b/custom_components/ha_controller/tests/test_states.py @@ -4,7 +4,7 @@ import pytest from homeassistant.helpers import entity_registry as er -from homeassistant.util.unit_system import METRIC_SYSTEM +from homeassistant.util.unit_system import METRIC_SYSTEM, US_CUSTOMARY_SYSTEM from custom_components.ha_controller.const import STATE_CHUNK_BYTES from custom_components.ha_controller.states import ( @@ -63,3 +63,39 @@ def test_chunk_updates_keeps_oversize_update_alone(): small = {"id": "i2", "text": "y"} chunks = chunk_updates([small, big, small], 100) assert [json.loads(c) for c in chunks] == [[small], [big], [small]] + + +async def test_climate_fahrenheit_defaults(hass): + hass.config.units = US_CUSTOMARY_SYSTEM + hass.states.async_set( + "climate.bedroom", + "heat", + {"temperature": 70, "current_temperature": 68, "min_temp": 45, "max_temp": 95}, + ) + updates = build_updates(hass, load_layout("reference"), ["climate.bedroom"]) + assert updates == [ + { + "id": "b4", + "available": True, + "target": 70, + "min": 45, + "max": 95, + "step": 1, + "unit": "°F", + "current": "68 °F", + "action": "Heat", + } + ] + + +async def test_entity_text_uses_suggested_precision(hass): + registry = er.async_get(hass) + registry.async_get_or_create( + "sensor", "test", "outdoor_temperature", suggested_object_id="outdoor_temperature" + ) + registry.async_update_entity_options( + "sensor.outdoor_temperature", "sensor", {"suggested_display_precision": 2} + ) + hass.states.async_set("sensor.outdoor_temperature", "3.14159", {"unit_of_measurement": "kW"}) + updates = build_updates(hass, load_layout("reference"), ["sensor.outdoor_temperature"]) + assert [u for u in updates if u["id"] == "i3"] == [{"id": "i3", "text": "3.14 kW"}] From 6bb7a48fdc630dbacea0127aacf58e07dc51a2e9 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:18:38 +0100 Subject: [PATCH 14/49] feat(integration): sync layouts and states with the screen Co-Authored-By: Claude Sonnet 5.5 --- custom_components/ha_controller/__init__.py | 30 +- custom_components/ha_controller/controller.py | 291 ++++++++++++++++++ custom_components/ha_controller/store.py | 31 ++ .../ha_controller/tests/test_controller.py | 275 +++++++++++++++++ 4 files changed, 623 insertions(+), 4 deletions(-) create mode 100644 custom_components/ha_controller/controller.py create mode 100644 custom_components/ha_controller/store.py create mode 100644 custom_components/ha_controller/tests/test_controller.py diff --git a/custom_components/ha_controller/__init__.py b/custom_components/ha_controller/__init__.py index 591c2f6..f5108e2 100644 --- a/custom_components/ha_controller/__init__.py +++ b/custom_components/ha_controller/__init__.py @@ -4,22 +4,44 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.typing import ConfigType +from homeassistant.loader import async_get_integration from .const import DOMAIN +from .controller import ScreenController +from .layout import async_load_emoji +from .store import LayoutStore CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) +type HaControllerConfigEntry = ConfigEntry[ScreenController] + async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the integration.""" return True -async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: - """Set up one screen. Filled in by a later task.""" +async def async_setup_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> bool: + """Set up one screen.""" + integration = await async_get_integration(hass, DOMAIN) + controller = ScreenController( + hass, + entry, + LayoutStore(hass, entry.entry_id), + await async_load_emoji(hass), + str(integration.version), + ) + await controller.async_start() + entry.runtime_data = controller return True -async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: - """Unload one screen. Filled in by a later task.""" +async def async_unload_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> bool: + """Unload one screen.""" + await entry.runtime_data.async_stop() return True + + +async def async_remove_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> None: + """Delete the stored layout of a removed screen.""" + await LayoutStore(hass, entry.entry_id).async_remove() diff --git a/custom_components/ha_controller/controller.py b/custom_components/ha_controller/controller.py new file mode 100644 index 0000000..9acba8c --- /dev/null +++ b/custom_components/ha_controller/controller.py @@ -0,0 +1,291 @@ +"""Per-screen controller: owns the layout and keeps the screen in sync.""" + +import logging +from collections.abc import Callable, Collection +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.event import async_call_later, async_track_state_change_event +from homeassistant.util import dt as dt_util + +from .compiler import compile_layout, encode_payload +from .const import ( + ACTION_SET_LAYOUT, + ACTION_SET_STATES, + CONF_DEVICE_ID, + EVENT_HELLO, + MAX_PAYLOAD_BYTES, + ONLINE_TIMEOUT, + PROTOCOL_VERSION, + PUSH_RETRY, + STATE_COALESCE_SECONDS, +) +from .layout import LayoutError, bound_entities, empty_layout, validate_layout +from .states import build_updates, chunk_updates +from .store import LayoutStore + +_LOGGER = logging.getLogger(__name__) + +REASON_CONNECTED = "connected" +NO_REVISION = "none" + + +@dataclass +class DeviceStatus: + """What the screen last told us about itself.""" + + node: str | None = None + version: str | None = None + revision: str | None = None + protocol: int | None = None + last_seen: datetime | None = None + + def online(self) -> bool: + """Return True when a hello arrived within the online timeout.""" + return self.last_seen is not None and dt_util.utcnow() - self.last_seen <= ONLINE_TIMEOUT + + +class InvalidLayout(HomeAssistantError): + """Raised when a layout cannot be saved.""" + + def __init__(self, errors: list[LayoutError]) -> None: + super().__init__(", ".join(f"{e.code}@{e.ref}" for e in errors)) + self.errors = errors + + +def _parse_protocol(value: Any) -> int | None: + try: + return int(value) + except TypeError, ValueError: + return None + + +class ScreenController: + """Owns the stored layout of one screen and pushes it to the device.""" + + def __init__( + self, + hass: HomeAssistant, + entry: ConfigEntry, + store: LayoutStore, + emoji: frozenset[str], + integration_version: str, + ) -> None: + self.hass = hass + self.entry = entry + self._store = store + self._emoji = emoji + self._integration_version = integration_version + self._layout: dict[str, Any] = empty_layout() + self._payload: dict[str, Any] = compile_layout(self._layout) + self._device = DeviceStatus() + self._last_push: tuple[str, datetime] | None = None + self._listeners: list[CALLBACK_TYPE] = [] + self._unsub_hello: CALLBACK_TYPE | None = None + self._unsub_states: CALLBACK_TYPE | None = None + self._cancel_flush: CALLBACK_TYPE | None = None + self._pending: set[str] = set() + + @property + def device_id(self) -> str: + return self.entry.data[CONF_DEVICE_ID] + + @property + def layout(self) -> dict[str, Any]: + return self._layout + + @property + def revision(self) -> str: + return self._payload["rev"] + + @property + def device(self) -> DeviceStatus: + return self._device + + @property + def integration_version(self) -> str: + return self._integration_version + + async def async_start(self) -> None: + """Load the layout and subscribe to the screen and its entities.""" + stored = await self._store.async_load() + if stored is not None: + errors = validate_layout(stored, self._emoji) + if errors: + _LOGGER.warning( + "Ignoring invalid stored layout for %s: %s", + self.entry.title, + ", ".join(f"{e.code}@{e.ref}" for e in errors), + ) + else: + self._set_layout(stored) + self._track_entities() + device_id = self.device_id + + @callback + def _is_ours(event_data: dict[str, Any] | Any) -> bool: + return event_data.get("device_id") == device_id + + self._unsub_hello = self.hass.bus.async_listen( + EVENT_HELLO, self._async_hello_event, event_filter=_is_ours + ) + + async def async_stop(self) -> None: + """Cancel every subscription and pending timer.""" + if self._unsub_hello is not None: + self._unsub_hello() + self._unsub_hello = None + self._untrack_entities() + if self._cancel_flush is not None: + self._cancel_flush() + self._cancel_flush = None + self._pending.clear() + self._listeners.clear() + + @callback + def async_add_listener(self, cb: Callable[[], None]) -> CALLBACK_TYPE: + """Call cb after every hello is recorded.""" + self._listeners.append(cb) + + @callback + def _remove() -> None: + if cb in self._listeners: + self._listeners.remove(cb) + + return _remove + + def _set_layout(self, layout: dict[str, Any]) -> None: + self._layout = layout + self._payload = compile_layout(layout) + self._track_entities() + + def _untrack_entities(self) -> None: + if self._unsub_states is not None: + self._unsub_states() + self._unsub_states = None + + def _track_entities(self) -> None: + self._untrack_entities() + entity_ids = list(bound_entities(self._layout)) + if entity_ids: + self._unsub_states = async_track_state_change_event( + self.hass, entity_ids, self._state_changed + ) + + def _can_push_states(self) -> bool: + return ( + self._device.node is not None + and self._device.protocol == PROTOCOL_VERSION + and self._device.online() + ) + + @callback + def _state_changed(self, event: Event) -> None: + if not self._can_push_states(): + return + self._pending.add(event.data["entity_id"]) + if self._cancel_flush is None: + self._cancel_flush = async_call_later( + self.hass, STATE_COALESCE_SECONDS, self._async_flush + ) + + async def _async_flush(self, _now: datetime) -> None: + self._cancel_flush = None + entity_ids, self._pending = self._pending, set() + if entity_ids and self._can_push_states(): + await self.async_push_states(entity_ids) + + async def async_save_layout(self, layout: dict[str, Any]) -> tuple[str, bool]: + """Validate, store and (when the screen is online) push a layout.""" + errors = validate_layout(layout, self._emoji) + if errors: + raise InvalidLayout(errors) + payload = compile_layout(layout) + if len(encode_payload(payload).encode("utf-8")) > MAX_PAYLOAD_BYTES: + raise InvalidLayout([LayoutError("payload_too_large", None)]) + await self._store.async_save(layout) + self._set_layout(layout) + pushed = False + if self._device.protocol == PROTOCOL_VERSION and self._device.online(): + pushed = await self.async_push_layout() + return self.revision, pushed + + async def async_handle_hello(self, data: dict[str, Any]) -> None: + """Record a hello and resync the screen (spec §7.5).""" + revision = data.get("revision") + self._device = DeviceStatus( + node=data.get("node") or self._device.node, + version=data.get("version"), + revision=None if revision in (None, NO_REVISION) else revision, + protocol=_parse_protocol(data.get("protocol")), + last_seen=dt_util.utcnow(), + ) + for cb in list(self._listeners): + cb() + if self._device.protocol != PROTOCOL_VERSION: + return + connected = data.get("reason") == REASON_CONNECTED + if revision != self.revision: + if connected or not self._recently_pushed(): + await self.async_push_layout() + elif connected: + await self.async_push_states() + + async def _async_hello_event(self, event: Event) -> None: + await self.async_handle_hello(event.data) + + def _recently_pushed(self) -> bool: + if self._last_push is None: + return False + revision, when = self._last_push + return revision == self.revision and dt_util.utcnow() - when < PUSH_RETRY + + async def async_push_layout(self) -> bool: + """Send the layout, then all states. Return True on success.""" + self._last_push = (self.revision, dt_util.utcnow()) + ok = await self.async_call_device( + ACTION_SET_LAYOUT, {"layout": encode_payload(self._payload)} + ) + return ok and await self.async_push_states() + + async def async_push_states(self, entity_ids: Collection[str] | None = None) -> bool: + """Send the state updates for entity_ids (all when None).""" + updates = build_updates(self.hass, self._layout, entity_ids) + for chunk in chunk_updates(updates): + if not await self.async_call_device(ACTION_SET_STATES, {"states": chunk}): + return False + return True + + async def async_call_device(self, action: str, data: dict[str, Any]) -> bool: + """Call an ESPHome service of the screen. Return False on failure.""" + node = self._device.node + if node is None: + return False + service = f"{node.replace('-', '_')}_{action}" + try: + await self.hass.services.async_call("esphome", service, data, blocking=True) + except HomeAssistantError as err: + _LOGGER.warning("Calling esphome.%s failed: %s", service, err) + return False + return True + + def status(self) -> dict[str, Any]: + """Return this screen as one ha_controller/screens item.""" + device = self._device + return { + "entry_id": self.entry.entry_id, + "title": self.entry.title, + "device_id": self.device_id, + "online": device.online(), + "firmware_version": device.version, + "integration_version": self._integration_version, + "protocol_ok": None + if device.last_seen is None + else device.protocol == PROTOCOL_VERSION, + "revision": self.revision, + "device_revision": device.revision, + } diff --git a/custom_components/ha_controller/store.py b/custom_components/ha_controller/store.py new file mode 100644 index 0000000..47211b4 --- /dev/null +++ b/custom_components/ha_controller/store.py @@ -0,0 +1,31 @@ +"""Persistent storage of one screen's layout.""" + +from typing import Any + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.storage import Store + +from .const import DOMAIN + +STORAGE_VERSION = 1 + + +class LayoutStore: + """Wrap the Home Assistant store that keeps a screen's layout.""" + + def __init__(self, hass: HomeAssistant, entry_id: str) -> None: + self._store: Store[dict[str, Any]] = Store( + hass, STORAGE_VERSION, f"{DOMAIN}.layout.{entry_id}" + ) + + async def async_load(self) -> dict[str, Any] | None: + """Return the stored layout, or None when nothing was saved yet.""" + return await self._store.async_load() + + async def async_save(self, layout: dict[str, Any]) -> None: + """Persist the layout.""" + await self._store.async_save(layout) + + async def async_remove(self) -> None: + """Delete the stored layout.""" + await self._store.async_remove() diff --git a/custom_components/ha_controller/tests/test_controller.py b/custom_components/ha_controller/tests/test_controller.py new file mode 100644 index 0000000..dbab06d --- /dev/null +++ b/custom_components/ha_controller/tests/test_controller.py @@ -0,0 +1,275 @@ +"""Tests for the layout store and the screen sync engine.""" + +import json +from datetime import timedelta + +from homeassistant.exceptions import HomeAssistantError +from pytest_homeassistant_custom_component.common import ( + MockConfigEntry, + async_fire_time_changed, + async_mock_service, +) + +from custom_components.ha_controller.const import DOMAIN +from custom_components.ha_controller.controller import InvalidLayout +from custom_components.ha_controller.layout import LayoutError + +from .helpers import NODE, hello, register_screen, setup_screen +from .test_compiler import load_layout + +REFERENCE_REV = "90538742" + + +def mock_screen(hass): + layouts = async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_layout") + states = async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_states") + return layouts, states + + +async def start(hass, *, saved=True): + """Set up a screen, optionally with the reference layout saved (offline).""" + device = await register_screen(hass) + entry = await setup_screen(hass, device) + if saved: + await entry.runtime_data.async_save_layout(load_layout("reference")) + return device, entry, entry.runtime_data + + +async def send_hello(hass, device, **overrides): + hass.bus.async_fire("esphome.ha_controller_hello", hello(device, **overrides)) + await hass.async_block_till_done() + + +async def test_hello_with_unknown_revision_pushes_layout_and_states(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision="none", reason="heartbeat") + assert len(layouts) == 1 + assert json.loads(layouts[0].data["layout"])["rev"] == REFERENCE_REV + assert len(states) >= 1 + + +async def test_hello_connected_with_current_revision_pushes_states_only(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="connected") + assert layouts == [] + assert len(states) >= 1 + + +async def test_heartbeat_with_current_revision_pushes_nothing(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert layouts == [] + assert states == [] + + +async def test_stale_revision_is_retried_at_most_every_300s(hass, freezer): + layouts, _ = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, reason="heartbeat") + freezer.tick(timedelta(seconds=299)) + await send_hello(hass, device, reason="heartbeat") + assert len(layouts) == 1 + freezer.tick(timedelta(seconds=2)) + await send_hello(hass, device, reason="heartbeat") + assert len(layouts) == 2 + await send_hello(hass, device, reason="connected") + assert len(layouts) == 3 + + +async def test_hello_with_other_protocol_pushes_nothing(hass): + layouts, states = mock_screen(hass) + device, entry, controller = await start(hass) + await send_hello(hass, device, protocol="2", reason="connected") + assert layouts == [] + assert states == [] + assert controller.status()["protocol_ok"] is False + + +async def test_hello_from_other_device_is_ignored(hass): + layouts, _ = mock_screen(hass) + device, _, controller = await start(hass) + other = await register_screen(hass, name="Other", mac="11:22:33:44:55:66") + await send_hello(hass, other) + assert layouts == [] + assert controller.device.last_seen is None + assert controller.status()["protocol_ok"] is None + + +async def test_state_changes_are_coalesced(hass, freezer): + _, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + hass.states.async_set("light.kitchen", "on", {"brightness": 255}) + freezer.tick(timedelta(milliseconds=100)) + hass.states.async_set("light.living_room", "on", {"brightness": 255}) + await hass.async_block_till_done() + assert states == [] + freezer.tick(timedelta(milliseconds=300)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert len(states) == 1 + ids = {u["id"] for u in json.loads(states[0].data["states"])} + assert ids == {"b1", "b2"} + + +async def test_state_change_not_pushed_when_offline(hass, freezer): + _, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + freezer.tick(timedelta(seconds=151)) + hass.states.async_set("light.kitchen", "on", {"brightness": 255}) + freezer.tick(timedelta(seconds=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert states == [] + + +async def test_save_layout_pushes_when_online(hass): + layouts, states = mock_screen(hass) + device, entry, controller = await start(hass, saved=False) + await send_hello(hass, device, revision="none", reason="heartbeat") + assert (await controller.async_save_layout(load_layout("reference"))) == ( + REFERENCE_REV, + True, + ) + assert json.loads(layouts[-1].data["layout"])["rev"] == REFERENCE_REV + assert len(states) >= 1 + + +async def test_save_layout_offline_returns_not_pushed(hass, hass_storage): + layouts, _ = mock_screen(hass) + _, entry, controller = await start(hass, saved=False) + result = await controller.async_save_layout(load_layout("reference")) + assert result == (REFERENCE_REV, False) + assert layouts == [] + key = f"{DOMAIN}.layout.{entry.entry_id}" + assert hass_storage[key]["data"] == load_layout("reference") + + +async def test_save_invalid_layout_raises(hass): + _, _, controller = await start(hass, saved=False) + layout = load_layout("reference") + layout["blocks"][1]["name"] = "" + try: + await controller.async_save_layout(layout) + except InvalidLayout as err: + assert err.errors == [LayoutError("invalid_name", "b2")] + else: + raise AssertionError("InvalidLayout not raised") + assert controller.revision != REFERENCE_REV + + +async def test_save_too_large_layout_raises_payload_too_large(hass): + _, _, controller = await start(hass, saved=False) + text = "漢" * 64 + layout = { + "version": 1, + "start": "b0", + "settings": {"sleep_timeout": 20}, + "blocks": [ + { + "id": f"b{n}", + "x": n, + "y": 0, + "name": "Big", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [ + {"id": f"i{n}x{k}", "kind": "text", "text": text, "font_size": None} + for k in range(6) + ], + } + for n in range(32) + ], + } + try: + await controller.async_save_layout(layout) + except InvalidLayout as err: + assert err.errors == [LayoutError("payload_too_large", None)] + else: + raise AssertionError("InvalidLayout not raised") + + +async def test_push_failure_is_logged_not_raised(hass, caplog): + async def fail(call): + raise HomeAssistantError("boom") + + hass.services.async_register("esphome", "ha_controller_aabbcc_set_layout", fail) + device, _, controller = await start(hass) + await send_hello(hass, device, reason="heartbeat") + assert await controller.async_push_layout() is False + assert "ha_controller_aabbcc_set_layout" in caplog.text + assert "boom" in caplog.text + + +async def test_call_device_without_hello_returns_false(hass): + layouts, _ = mock_screen(hass) + _, _, controller = await start(hass) + assert await controller.async_call_device("set_layout", {"layout": "{}"}) is False + assert layouts == [] + + +async def test_invalid_stored_layout_falls_back_to_empty(hass, hass_storage, caplog): + device = await register_screen(hass) + entry = MockConfigEntry(domain=DOMAIN, data={"device_id": device.id}, unique_id=device.id) + entry.add_to_hass(hass) + key = f"{DOMAIN}.layout.{entry.entry_id}" + stored = {"version": 1, "start": "zz", "settings": {"sleep_timeout": 20}, "blocks": "bad"} + hass_storage[key] = {"version": 1, "minor_version": 1, "key": key, "data": stored} + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + controller = entry.runtime_data + assert controller.layout["blocks"] == [] + assert "Ignoring invalid stored layout" in caplog.text + assert hass_storage[key]["data"] == stored + + +async def test_layout_survives_reload(hass): + _, entry, _ = await start(hass) + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert entry.runtime_data.layout == load_layout("reference") + assert entry.runtime_data.revision == REFERENCE_REV + + +async def test_remove_entry_deletes_storage(hass, hass_storage): + _, entry, _ = await start(hass) + key = f"{DOMAIN}.layout.{entry.entry_id}" + assert key in hass_storage + await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + assert key not in hass_storage + + +async def test_listeners_are_notified_on_hello(hass): + mock_screen(hass) + device, _, controller = await start(hass) + calls = [] + remove = controller.async_add_listener(lambda: calls.append(1)) + await send_hello(hass, device, reason="heartbeat") + assert calls == [1] + remove() + await send_hello(hass, device, reason="heartbeat") + assert calls == [1] + + +async def test_status_reports_device(hass): + mock_screen(hass) + device, entry, controller = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert controller.status() == { + "entry_id": entry.entry_id, + "title": entry.title, + "device_id": device.id, + "online": True, + "firmware_version": "0.1.0", + "integration_version": "0.1.0", + "protocol_ok": True, + "revision": REFERENCE_REV, + "device_revision": REFERENCE_REV, + } + assert controller.device.node == NODE From 9e13b23378cde2ab6800f474e31a527e470a890f Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:30:00 +0100 Subject: [PATCH 15/49] docs(protocol): resync states on the first hello after a restart Co-Authored-By: Claude Opus 5.5 --- docs/protocol/README.md | 2 +- docs/superpowers/specs/2026-11-16-ha-controller-design.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/protocol/README.md b/docs/protocol/README.md index 32bbb5c..449dce8 100644 --- a/docs/protocol/README.md +++ b/docs/protocol/README.md @@ -106,7 +106,7 @@ An unavailable or missing entity sends `{"id": …, "available": false}`. Entity - **On a hello from the screen's `device_id`:** record the node, version, protocol, revision and time. Then: - If `protocol ≠ 1`, push nothing (auto-update may run, §11). - Else, if `revision ≠` the current revision, push the layout and then all states. Push immediately when `reason = connected`. Otherwise push at most once per 300 s for the same revision. - - Else, if `reason = connected`, push all states. + - Else, if `reason = connected`, or this is the first hello since the integration (re)started, push all states. After an integration reload the ESPHome connection stays up, so no `connected` hello arrives. - **Entity state changes:** coalesced for 200 ms, then pushed for the changed entities. This only happens while the screen is online (a hello within the last 150 s) and on protocol 1. - **Saving a layout:** pushes it immediately if the screen is online. diff --git a/docs/superpowers/specs/2026-11-16-ha-controller-design.md b/docs/superpowers/specs/2026-11-16-ha-controller-design.md index 354433f..1f055e3 100644 --- a/docs/superpowers/specs/2026-11-16-ha-controller-design.md +++ b/docs/superpowers/specs/2026-11-16-ha-controller-design.md @@ -288,7 +288,7 @@ An unavailable or missing entity sends `{"id": …, "available": false}`. Entity - **On a hello from the screen's `device_id`:** record the node, version, protocol, revision and time. Then: - If `protocol ≠ 1`, push nothing (auto-update may run, §11). - Else, if `revision ≠` the current revision, push the layout and then all states. Push immediately when `reason = connected`. Otherwise push at most once per 300 s for the same revision. - - Else, if `reason = connected`, push all states. + - Else, if `reason = connected`, or this is the first hello since the integration (re)started, push all states. After an integration reload the ESPHome connection stays up, so no `connected` hello arrives. - **Entity state changes:** coalesced for 200 ms, then pushed for the changed entities. This only happens while the screen is online (a hello within the last 150 s) and on protocol 1. - **Saving a layout:** pushes it immediately if the screen is online. From e6ed3600ae1d75ab05a33173082f14780e143b1d Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:30:52 +0100 Subject: [PATCH 16/49] fix(integration): resync states after restart and harden device calls Co-Authored-By: Claude Sonnet 5.5 --- custom_components/ha_controller/controller.py | 17 +++-- .../ha_controller/tests/test_controller.py | 71 +++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/custom_components/ha_controller/controller.py b/custom_components/ha_controller/controller.py index 9acba8c..f6dc4ca 100644 --- a/custom_components/ha_controller/controller.py +++ b/custom_components/ha_controller/controller.py @@ -6,6 +6,7 @@ from datetime import datetime from typing import Any +import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError @@ -49,11 +50,16 @@ def online(self) -> bool: return self.last_seen is not None and dt_util.utcnow() - self.last_seen <= ONLINE_TIMEOUT +def format_layout_errors(errors: list[LayoutError]) -> str: + """Format errors as `code@ref` (empty ref when None), comma separated.""" + return ", ".join(f"{e.code}@{e.ref or ''}" for e in errors) + + class InvalidLayout(HomeAssistantError): """Raised when a layout cannot be saved.""" def __init__(self, errors: list[LayoutError]) -> None: - super().__init__(", ".join(f"{e.code}@{e.ref}" for e in errors)) + super().__init__(format_layout_errors(errors)) self.errors = errors @@ -89,6 +95,7 @@ def __init__( self._unsub_states: CALLBACK_TYPE | None = None self._cancel_flush: CALLBACK_TYPE | None = None self._pending: set[str] = set() + self._first_hello_seen = False @property def device_id(self) -> str: @@ -119,7 +126,7 @@ async def async_start(self) -> None: _LOGGER.warning( "Ignoring invalid stored layout for %s: %s", self.entry.title, - ", ".join(f"{e.code}@{e.ref}" for e in errors), + format_layout_errors(errors), ) else: self._set_layout(stored) @@ -228,7 +235,9 @@ async def async_handle_hello(self, data: dict[str, Any]) -> None: cb() if self._device.protocol != PROTOCOL_VERSION: return - connected = data.get("reason") == REASON_CONNECTED + first_hello = not self._first_hello_seen + self._first_hello_seen = True + connected = data.get("reason") == REASON_CONNECTED or first_hello if revision != self.revision: if connected or not self._recently_pushed(): await self.async_push_layout() @@ -268,7 +277,7 @@ async def async_call_device(self, action: str, data: dict[str, Any]) -> bool: service = f"{node.replace('-', '_')}_{action}" try: await self.hass.services.async_call("esphome", service, data, blocking=True) - except HomeAssistantError as err: + except (HomeAssistantError, vol.Invalid) as err: _LOGGER.warning("Calling esphome.%s failed: %s", service, err) return False return True diff --git a/custom_components/ha_controller/tests/test_controller.py b/custom_components/ha_controller/tests/test_controller.py index dbab06d..dfa43ac 100644 --- a/custom_components/ha_controller/tests/test_controller.py +++ b/custom_components/ha_controller/tests/test_controller.py @@ -3,6 +3,7 @@ import json from datetime import timedelta +import voluptuous as vol from homeassistant.exceptions import HomeAssistantError from pytest_homeassistant_custom_component.common import ( MockConfigEntry, @@ -60,11 +61,24 @@ async def test_hello_connected_with_current_revision_pushes_states_only(hass): async def test_heartbeat_with_current_revision_pushes_nothing(hass): layouts, states = mock_screen(hass) device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") # first hello + states.clear() await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") assert layouts == [] assert states == [] +async def test_first_hello_after_start_pushes_states(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert layouts == [] + assert len(states) == 1 + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert layouts == [] + assert len(states) == 1 + + async def test_stale_revision_is_retried_at_most_every_300s(hass, freezer): layouts, _ = mock_screen(hass) device, _, _ = await start(hass) @@ -102,6 +116,7 @@ async def test_state_changes_are_coalesced(hass, freezer): _, states = mock_screen(hass) device, _, _ = await start(hass) await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + states.clear() hass.states.async_set("light.kitchen", "on", {"brightness": 255}) freezer.tick(timedelta(milliseconds=100)) hass.states.async_set("light.living_room", "on", {"brightness": 255}) @@ -119,6 +134,7 @@ async def test_state_change_not_pushed_when_offline(hass, freezer): _, states = mock_screen(hass) device, _, _ = await start(hass) await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + states.clear() freezer.tick(timedelta(seconds=151)) hass.states.async_set("light.kitchen", "on", {"brightness": 255}) freezer.tick(timedelta(seconds=1)) @@ -273,3 +289,58 @@ async def test_status_reports_device(hass): "device_revision": REFERENCE_REV, } assert controller.device.node == NODE + + +async def test_service_schema_error_is_logged_not_raised(hass, caplog): + hass.services.async_register( + "esphome", + "ha_controller_aabbcc_set_layout", + lambda call: None, + schema=vol.Schema({vol.Required("other"): str}), + ) + device, _, controller = await start(hass, saved=False) + await send_hello(hass, device, revision="none", reason="heartbeat") + result = await controller.async_save_layout(load_layout("reference")) + assert result == (REFERENCE_REV, False) + assert "ha_controller_aabbcc_set_layout" in caplog.text + + +def test_invalid_layout_message_format(): + assert str(InvalidLayout([LayoutError("payload_too_large", None)])) == "payload_too_large@" + errors = [LayoutError("invalid_name", "b2"), LayoutError("disconnected", "b4")] + assert str(InvalidLayout(errors)) == "invalid_name@b2, disconnected@b4" + + +async def test_new_revision_is_pushed_despite_recent_push(hass, freezer): + layouts, _ = mock_screen(hass) + device, _, controller = await start(hass, saved=False) + layout_a = load_layout("reference") + await controller.async_save_layout(layout_a) + await send_hello(hass, device, revision="none", reason="heartbeat") + assert len(layouts) == 1 + freezer.tick(timedelta(seconds=151)) + layout_b = json.loads(json.dumps(layout_a)) + layout_b["blocks"] = layout_b["blocks"][:-1] + _, pushed = await controller.async_save_layout(layout_b) + assert pushed is False + assert controller.revision != REFERENCE_REV + assert len(layouts) == 1 + freezer.tick(timedelta(seconds=1)) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert len(layouts) == 2 + assert json.loads(layouts[1].data["layout"])["rev"] == controller.revision + + +async def test_stop_cancels_pending_flush(hass, freezer): + _, states = mock_screen(hass) + device, entry, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + states.clear() + hass.states.async_set("light.kitchen", "on", {"brightness": 255}) + await hass.async_block_till_done() + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + freezer.tick(timedelta(seconds=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert states == [] From d60b00aaeee82c8bf5d2924a1a40d348d59fc3ea Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:32:47 +0100 Subject: [PATCH 17/49] feat(integration): map screen controls to service calls Co-Authored-By: Claude Sonnet 5.5 --- custom_components/ha_controller/controller.py | 24 +++++- custom_components/ha_controller/controls.py | 69 ++++++++++++++++ .../ha_controller/tests/test_controls.py | 82 +++++++++++++++++++ 3 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 custom_components/ha_controller/controls.py create mode 100644 custom_components/ha_controller/tests/test_controls.py diff --git a/custom_components/ha_controller/controller.py b/custom_components/ha_controller/controller.py index f6dc4ca..1af343e 100644 --- a/custom_components/ha_controller/controller.py +++ b/custom_components/ha_controller/controller.py @@ -1,7 +1,7 @@ """Per-screen controller: owns the layout and keeps the screen in sync.""" import logging -from collections.abc import Callable, Collection +from collections.abc import Callable, Collection, Mapping from dataclasses import dataclass from datetime import datetime from typing import Any @@ -18,6 +18,7 @@ ACTION_SET_LAYOUT, ACTION_SET_STATES, CONF_DEVICE_ID, + EVENT_CONTROL, EVENT_HELLO, MAX_PAYLOAD_BYTES, ONLINE_TIMEOUT, @@ -25,6 +26,7 @@ PUSH_RETRY, STATE_COALESCE_SECONDS, ) +from .controls import resolve_control from .layout import LayoutError, bound_entities, empty_layout, validate_layout from .states import build_updates, chunk_updates from .store import LayoutStore @@ -92,6 +94,7 @@ def __init__( self._last_push: tuple[str, datetime] | None = None self._listeners: list[CALLBACK_TYPE] = [] self._unsub_hello: CALLBACK_TYPE | None = None + self._unsub_control: CALLBACK_TYPE | None = None self._unsub_states: CALLBACK_TYPE | None = None self._cancel_flush: CALLBACK_TYPE | None = None self._pending: set[str] = set() @@ -140,12 +143,18 @@ def _is_ours(event_data: dict[str, Any] | Any) -> bool: self._unsub_hello = self.hass.bus.async_listen( EVENT_HELLO, self._async_hello_event, event_filter=_is_ours ) + self._unsub_control = self.hass.bus.async_listen( + EVENT_CONTROL, self._async_control_event, event_filter=_is_ours + ) async def async_stop(self) -> None: """Cancel every subscription and pending timer.""" if self._unsub_hello is not None: self._unsub_hello() self._unsub_hello = None + if self._unsub_control is not None: + self._unsub_control() + self._unsub_control = None self._untrack_entities() if self._cancel_flush is not None: self._cancel_flush() @@ -247,6 +256,19 @@ async def async_handle_hello(self, data: dict[str, Any]) -> None: async def _async_hello_event(self, event: Event) -> None: await self.async_handle_hello(event.data) + async def _async_control_event(self, event: Event) -> None: + await self.async_handle_control(event.data) + + async def async_handle_control(self, data: Mapping[str, Any]) -> None: + """Run the service call a control event maps to (spec §7.6).""" + call = resolve_control(self._layout, self.hass, data) + if call is None: + return + try: + await self.hass.services.async_call(call.domain, call.service, call.data, blocking=True) + except (HomeAssistantError, vol.Invalid) as err: + _LOGGER.warning("Calling %s.%s failed: %s", call.domain, call.service, err) + def _recently_pushed(self) -> bool: if self._last_push is None: return False diff --git a/custom_components/ha_controller/controls.py b/custom_components/ha_controller/controls.py new file mode 100644 index 0000000..4f8920e --- /dev/null +++ b/custom_components/ha_controller/controls.py @@ -0,0 +1,69 @@ +"""Map screen control events to Home Assistant service calls (spec §7.6).""" + +from __future__ import annotations + +import math +from collections.abc import Mapping +from typing import Any, NamedTuple + +from homeassistant.core import HomeAssistant + +DEFAULT_MIN_TEMP = 7 +DEFAULT_MAX_TEMP = 35 + + +class ControlCall(NamedTuple): + """A service call to make for a control event.""" + + domain: str + service: str + data: dict[str, Any] + + +def _parse_value(raw: Any) -> float | None: + try: + value = float(raw) + except TypeError, ValueError: + return None + return value if math.isfinite(value) else None + + +def _bound(hass: HomeAssistant, entity_id: str, attribute: str, default: float) -> float: + state = hass.states.get(entity_id) + value = _parse_value(state.attributes.get(attribute)) if state else None + return default if value is None else value + + +def resolve_control( + layout: dict[str, Any], hass: HomeAssistant, data: Mapping[str, Any] +) -> ControlCall | None: + """Return the service call for a control event, or None to ignore it.""" + block = next((b for b in layout["blocks"] if b["id"] == data.get("block")), None) + if block is None or block["type"] != "entity": + return None + entity_id = block["entity_id"] + domain = entity_id.split(".", 1)[0] + op = data.get("op") + if domain == "light": + if op == "toggle": + return ControlCall("light", "toggle", {"entity_id": entity_id}) + if op == "set": + value = _parse_value(data.get("value")) + if value is None: + return None + if value <= 0: + return ControlCall("light", "turn_off", {"entity_id": entity_id}) + pct = round(min(max(value, 1), 100)) + return ControlCall("light", "turn_on", {"entity_id": entity_id, "brightness_pct": pct}) + elif domain == "climate" and op == "set": + value = _parse_value(data.get("value")) + if value is None: + return None + low = _bound(hass, entity_id, "min_temp", DEFAULT_MIN_TEMP) + high = _bound(hass, entity_id, "max_temp", DEFAULT_MAX_TEMP) + return ControlCall( + "climate", + "set_temperature", + {"entity_id": entity_id, "temperature": min(max(value, low), high)}, + ) + return None diff --git a/custom_components/ha_controller/tests/test_controls.py b/custom_components/ha_controller/tests/test_controls.py new file mode 100644 index 0000000..e827f8f --- /dev/null +++ b/custom_components/ha_controller/tests/test_controls.py @@ -0,0 +1,82 @@ +"""Tests for the control event mapping.""" + +import logging + +import pytest +from homeassistant.exceptions import HomeAssistantError +from pytest_homeassistant_custom_component.common import async_mock_service + +from custom_components.ha_controller.const import EVENT_CONTROL +from custom_components.ha_controller.controls import resolve_control + +from .helpers import FIXTURES, load_fixture, register_screen, setup_screen +from .test_compiler import load_layout + +CONTROL_FIXTURES = sorted((FIXTURES / "controls").glob("*.json")) + + +@pytest.mark.parametrize("path", CONTROL_FIXTURES, ids=lambda p: p.stem) +async def test_control_fixtures(hass, path): + case = load_fixture("controls", path.name) + for entity_id, s in case["hass_states"].items(): + hass.states.async_set(entity_id, s["state"], s["attributes"]) + call = resolve_control(load_layout(case["layout"]), hass, case["event"]) + assert (call and call._asdict()) == case["expect_call"] + + +async def test_climate_defaults_without_state(hass): + event = {"block": "b4", "item": "", "op": "set", "value": "50"} + call = resolve_control(load_layout("reference"), hass, event) + assert call.data["temperature"] == 35 + event["value"] = "1" + assert resolve_control(load_layout("reference"), hass, event).data["temperature"] == 7 + + +async def test_non_finite_value_is_ignored(hass): + event = {"block": "b2", "item": "", "op": "set", "value": "nan"} + assert resolve_control(load_layout("reference"), hass, event) is None + event["value"] = "inf" + assert resolve_control(load_layout("reference"), hass, event) is None + + +async def start(hass): + device = await register_screen(hass) + entry = await setup_screen(hass, device) + await entry.runtime_data.async_save_layout(load_layout("reference")) + return device + + +def control(device_id, **overrides): + data = {"device_id": device_id, "block": "b1", "item": "", "op": "toggle", "value": "0"} + data.update(overrides) + return data + + +async def test_control_event_calls_service(hass): + calls = async_mock_service(hass, "light", "toggle") + device = await start(hass) + hass.bus.async_fire(EVENT_CONTROL, control(device.id)) + await hass.async_block_till_done() + assert len(calls) == 1 + assert calls[0].data == {"entity_id": "light.kitchen"} + + +async def test_control_from_other_device_is_ignored(hass): + calls = async_mock_service(hass, "light", "toggle") + await start(hass) + hass.bus.async_fire(EVENT_CONTROL, control("other-device")) + await hass.async_block_till_done() + assert calls == [] + + +async def test_service_error_is_swallowed(hass, caplog): + def fail(call): + raise HomeAssistantError("boom") + + hass.services.async_register("light", "turn_on", fail) + device = await start(hass) + with caplog.at_level(logging.WARNING): + hass.bus.async_fire(EVENT_CONTROL, control(device.id, block="b2", op="set", value="50")) + await hass.async_block_till_done() + assert "light.turn_on" in caplog.text + assert "boom" in caplog.text From 4fb6ee547497b06dae3791bb86a5d507d4f1009f Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:35:06 +0100 Subject: [PATCH 18/49] feat(integration): add websocket API for the panel Co-Authored-By: Claude Sonnet 5.5 --- custom_components/ha_controller/__init__.py | 2 + .../ha_controller/tests/test_websocket.py | 155 ++++++++++++++++++ custom_components/ha_controller/websocket.py | 86 ++++++++++ 3 files changed, 243 insertions(+) create mode 100644 custom_components/ha_controller/tests/test_websocket.py create mode 100644 custom_components/ha_controller/websocket.py diff --git a/custom_components/ha_controller/__init__.py b/custom_components/ha_controller/__init__.py index f5108e2..1a55ae0 100644 --- a/custom_components/ha_controller/__init__.py +++ b/custom_components/ha_controller/__init__.py @@ -10,6 +10,7 @@ from .controller import ScreenController from .layout import async_load_emoji from .store import LayoutStore +from .websocket import async_register_websocket CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) @@ -18,6 +19,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the integration.""" + async_register_websocket(hass) return True diff --git a/custom_components/ha_controller/tests/test_websocket.py b/custom_components/ha_controller/tests/test_websocket.py new file mode 100644 index 0000000..71a500f --- /dev/null +++ b/custom_components/ha_controller/tests/test_websocket.py @@ -0,0 +1,155 @@ +"""Tests for the websocket API used by the panel.""" + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.setup import async_setup_component +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from custom_components.ha_controller.const import DOMAIN + +from .helpers import register_screen, setup_screen +from .test_compiler import load_layout + +REFERENCE_REV = "90538742" + + +async def start(hass, *, name="HA Controller", mac="aa:bb:cc:dd:ee:ff", saved=True): + device = await register_screen(hass, name=name, mac=mac) + entry = await setup_screen(hass, device) + hass.config_entries.async_update_entry(entry, title=name) + if saved: + await entry.runtime_data.async_save_layout(load_layout("reference")) + return entry + + +async def test_screens_lists_entries(hass, hass_ws_client): + second = await start(hass, name="Bedroom", mac="aa:bb:cc:dd:ee:01", saved=False) + first = await start(hass, name="Attic", mac="aa:bb:cc:dd:ee:02", saved=False) + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/screens"}) + msg = await client.receive_json() + assert msg["success"] + assert msg["result"] == { + "screens": [first.runtime_data.status(), second.runtime_data.status()] + } + + +async def test_screens_skips_unloaded_entries(hass, hass_ws_client): + entry = await start(hass, saved=False) + await hass.config_entries.async_unload(entry.entry_id) + assert entry.state is ConfigEntryState.NOT_LOADED + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/screens"}) + msg = await client.receive_json() + assert msg["result"] == {"screens": []} + + +async def test_layout_get_returns_stored_layout(hass, hass_ws_client): + entry = await start(hass) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + {"type": "ha_controller/layout/get", "entry_id": entry.entry_id} + ) + msg = await client.receive_json() + assert msg["success"] + assert msg["result"] == {"layout": load_layout("reference")} + + +async def test_layout_get_unknown_entry_returns_not_found(hass, hass_ws_client): + assert await async_setup_component(hass, DOMAIN, {}) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + {"type": "ha_controller/layout/get", "entry_id": "missing"} + ) + msg = await client.receive_json() + assert not msg["success"] + assert msg["error"]["code"] == "not_found" + + +async def test_layout_get_foreign_entry_returns_not_found(hass, hass_ws_client): + assert await async_setup_component(hass, DOMAIN, {}) + other = MockConfigEntry(domain="other") + other.add_to_hass(hass) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + {"type": "ha_controller/layout/get", "entry_id": other.entry_id} + ) + msg = await client.receive_json() + assert msg["error"]["code"] == "not_found" + + +async def test_layout_get_unloaded_entry_returns_not_found(hass, hass_ws_client): + entry = await start(hass, saved=False) + await hass.config_entries.async_unload(entry.entry_id) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + {"type": "ha_controller/layout/get", "entry_id": entry.entry_id} + ) + msg = await client.receive_json() + assert msg["error"]["code"] == "not_found" + + +async def test_layout_save_valid(hass, hass_ws_client): + entry = await start(hass, saved=False) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + { + "type": "ha_controller/layout/save", + "entry_id": entry.entry_id, + "layout": load_layout("reference"), + } + ) + msg = await client.receive_json() + assert msg["success"] + assert msg["result"] == {"revision": REFERENCE_REV, "pushed": False} + assert entry.runtime_data.layout == load_layout("reference") + + +async def test_layout_save_invalid(hass, hass_ws_client): + entry = await start(hass, saved=False) + layout = load_layout("reference") + layout["blocks"][1]["name"] = "" + client = await hass_ws_client(hass) + await client.send_json_auto_id( + { + "type": "ha_controller/layout/save", + "entry_id": entry.entry_id, + "layout": layout, + } + ) + msg = await client.receive_json() + assert not msg["success"] + assert msg["error"] == {"code": "invalid_layout", "message": "invalid_name@b2"} + + +async def test_layout_save_unknown_entry_returns_not_found(hass, hass_ws_client): + assert await async_setup_component(hass, DOMAIN, {}) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + { + "type": "ha_controller/layout/save", + "entry_id": "missing", + "layout": load_layout("reference"), + } + ) + msg = await client.receive_json() + assert msg["error"]["code"] == "not_found" + + +async def test_commands_require_admin(hass, hass_ws_client, hass_admin_user): + entry = await start(hass) + hass_admin_user.groups = [] + client = await hass_ws_client(hass) + commands = [ + {"type": "ha_controller/screens"}, + {"type": "ha_controller/layout/get", "entry_id": entry.entry_id}, + { + "type": "ha_controller/layout/save", + "entry_id": entry.entry_id, + "layout": load_layout("reference"), + }, + ] + for command in commands: + await client.send_json_auto_id(command) + msg = await client.receive_json() + assert not msg["success"] + assert msg["error"]["code"] == "unauthorized" diff --git a/custom_components/ha_controller/websocket.py b/custom_components/ha_controller/websocket.py new file mode 100644 index 0000000..4f4f8e5 --- /dev/null +++ b/custom_components/ha_controller/websocket.py @@ -0,0 +1,86 @@ +"""Websocket API used by the HA Controller panel.""" + +from typing import Any + +import voluptuous as vol +from homeassistant.components import websocket_api +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant, callback + +from .const import DOMAIN +from .controller import InvalidLayout, ScreenController, format_layout_errors + + +@callback +def async_register_websocket(hass: HomeAssistant) -> None: + """Register the panel commands.""" + websocket_api.async_register_command(hass, ws_screens) + websocket_api.async_register_command(hass, ws_layout_get) + websocket_api.async_register_command(hass, ws_layout_save) + + +def _get_controller( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> ScreenController | None: + """Return the controller of a loaded entry, or send not_found.""" + entry = hass.config_entries.async_get_entry(msg["entry_id"]) + if entry is None or entry.domain != DOMAIN or entry.state is not ConfigEntryState.LOADED: + connection.send_error(msg["id"], websocket_api.ERR_NOT_FOUND, "Screen not found") + return None + return entry.runtime_data + + +@websocket_api.websocket_command({vol.Required("type"): "ha_controller/screens"}) +@websocket_api.require_admin +@callback +def ws_screens( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> None: + """List the loaded screens.""" + entries = sorted( + ( + entry + for entry in hass.config_entries.async_entries(DOMAIN) + if entry.state is ConfigEntryState.LOADED + ), + key=lambda entry: entry.title, + ) + connection.send_result( + msg["id"], {"screens": [entry.runtime_data.status() for entry in entries]} + ) + + +@websocket_api.websocket_command( + {vol.Required("type"): "ha_controller/layout/get", vol.Required("entry_id"): str} +) +@websocket_api.require_admin +@callback +def ws_layout_get( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> None: + """Return the stored layout of a screen.""" + if (controller := _get_controller(hass, connection, msg)) is not None: + connection.send_result(msg["id"], {"layout": controller.layout}) + + +@websocket_api.websocket_command( + { + vol.Required("type"): "ha_controller/layout/save", + vol.Required("entry_id"): str, + vol.Required("layout"): dict, + } +) +@websocket_api.require_admin +@websocket_api.async_response +async def ws_layout_save( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> None: + """Validate, store and push a layout.""" + if (controller := _get_controller(hass, connection, msg)) is None: + return + try: + revision, pushed = await controller.async_save_layout(msg["layout"]) + except InvalidLayout as err: + connection.send_error(msg["id"], "invalid_layout", format_layout_errors(err.errors)) + return + connection.send_result(msg["id"], {"revision": revision, "pushed": pushed}) From 2363c4ef98a196fd29b59421d8c0066716635114 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:37:04 +0100 Subject: [PATCH 19/49] feat(integration): register the sidebar panel Co-Authored-By: Claude Sonnet 5.5 --- .claude/CLAUDE.md | 1 + .claude/agents/ha-integration-reviewer.md | 19 +++++ custom_components/ha_controller/__init__.py | 9 +++ custom_components/ha_controller/panel.py | 45 ++++++++++++ .../ha_controller/tests/test_panel.py | 69 +++++++++++++++++++ docs/README.md | 1 + docs/development.md | 47 +++++++++++++ 7 files changed, 191 insertions(+) create mode 100644 .claude/agents/ha-integration-reviewer.md create mode 100644 custom_components/ha_controller/panel.py create mode 100644 custom_components/ha_controller/tests/test_panel.py create mode 100644 docs/development.md diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index f86e414..4d72a74 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -47,3 +47,4 @@ custom_components/.venv/bin/ruff check custom_components - Skill `protocol-change` (`.claude/skills/protocol-change/`): checklist for any change that crosses the Home Assistant ↔ screen boundary. - Agent `protocol-guardian` (`.claude/agents/protocol-guardian.md`): reviews a diff for protocol consistency across docs, fixtures, Python, TypeScript and C++. +- Agent `ha-integration-reviewer` (`.claude/agents/ha-integration-reviewer.md`): reviews integration changes against Home Assistant development rules. diff --git a/.claude/agents/ha-integration-reviewer.md b/.claude/agents/ha-integration-reviewer.md new file mode 100644 index 0000000..566d427 --- /dev/null +++ b/.claude/agents/ha-integration-reviewer.md @@ -0,0 +1,19 @@ +--- +name: ha-integration-reviewer +description: Reviews changes under custom_components/ha_controller and custom_components/ha_controller/tests against Home Assistant development rules. Use before merging integration changes. +tools: Read, Grep, Glob, Bash +--- + +You review changes to the Home Assistant integration. Read the diff (`git diff main...HEAD -- custom_components`), then check: + +- Async only: no blocking I/O (file access, `requests`, `time.sleep`) in the event loop. +- State lives in `entry.runtime_data`; no new `hass.data` globals beyond the panel flags. +- Every listener and timer is removed on unload. +- Event handlers filter by `device_id`. +- Service call errors are caught. +- Constants come from `const.py`, not literals. +- User-facing strings are English and live in `strings.json` and `translations/en.json`. +- Every branch has a test. +- A change that crosses the Home Assistant ↔ screen boundary goes through the `protocol-change` skill. + +Report findings as `file:line — issue — fix`, one per line. Say so when there are none. diff --git a/custom_components/ha_controller/__init__.py b/custom_components/ha_controller/__init__.py index 1a55ae0..a56483b 100644 --- a/custom_components/ha_controller/__init__.py +++ b/custom_components/ha_controller/__init__.py @@ -9,6 +9,7 @@ from .const import DOMAIN from .controller import ScreenController from .layout import async_load_emoji +from .panel import async_register_panel, async_unregister_panel from .store import LayoutStore from .websocket import async_register_websocket @@ -35,12 +36,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) ) await controller.async_start() entry.runtime_data = controller + await async_register_panel(hass, controller.integration_version) return True async def async_unload_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> bool: """Unload one screen.""" await entry.runtime_data.async_stop() + others = [ + other + for other in hass.config_entries.async_loaded_entries(DOMAIN) + if other.entry_id != entry.entry_id + ] + if not others: + async_unregister_panel(hass) return True diff --git a/custom_components/ha_controller/panel.py b/custom_components/ha_controller/panel.py new file mode 100644 index 0000000..e291df5 --- /dev/null +++ b/custom_components/ha_controller/panel.py @@ -0,0 +1,45 @@ +"""Sidebar panel registration.""" + +import logging +from pathlib import Path + +from homeassistant.components import frontend, panel_custom +from homeassistant.components.http import StaticPathConfig +from homeassistant.core import HomeAssistant, callback + +from .const import DOMAIN, PANEL_COMPONENT, PANEL_ICON, PANEL_TITLE, PANEL_URL_PATH, STATIC_URL + +_LOGGER = logging.getLogger(__name__) + +BUNDLE = Path(__file__).parent / "frontend" / "dist" / "ha-controller-panel.js" +STATIC_REGISTERED = f"{DOMAIN}_static_registered" + + +async def async_register_panel(hass: HomeAssistant, version: str) -> None: + """Serve the panel bundle and add the sidebar panel.""" + if not hass.data.get(STATIC_REGISTERED): + hass.data[STATIC_REGISTERED] = True + await hass.http.async_register_static_paths( + [StaticPathConfig(f"{STATIC_URL}/ha-controller-panel.js", str(BUNDLE), True)] + ) + if not await hass.async_add_executor_job(BUNDLE.is_file): + _LOGGER.warning("The panel bundle %s is missing; build it with npm", BUNDLE) + + if PANEL_URL_PATH in hass.data.get(frontend.DATA_PANELS, {}): + return + await panel_custom.async_register_panel( + hass, + frontend_url_path=PANEL_URL_PATH, + webcomponent_name=PANEL_COMPONENT, + sidebar_title=PANEL_TITLE, + sidebar_icon=PANEL_ICON, + module_url=f"{STATIC_URL}/ha-controller-panel.js?v={version}", + require_admin=True, + config={}, + ) + + +@callback +def async_unregister_panel(hass: HomeAssistant) -> None: + """Remove the sidebar panel.""" + frontend.async_remove_panel(hass, PANEL_URL_PATH, warn_if_unknown=False) diff --git a/custom_components/ha_controller/tests/test_panel.py b/custom_components/ha_controller/tests/test_panel.py new file mode 100644 index 0000000..e5d558b --- /dev/null +++ b/custom_components/ha_controller/tests/test_panel.py @@ -0,0 +1,69 @@ +"""Tests for the sidebar panel registration.""" + +from unittest.mock import AsyncMock, patch + +from homeassistant.components import frontend +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component + +from custom_components.ha_controller.const import PANEL_URL_PATH + +from .helpers import register_screen, setup_screen + + +async def test_panel_registered_on_setup(hass: HomeAssistant) -> None: + """The panel is registered for admins with the first entry.""" + await setup_screen(hass, await register_screen(hass)) + + panel = hass.data[frontend.DATA_PANELS][PANEL_URL_PATH] + assert panel.require_admin is True + assert panel.sidebar_title == "HA Controller" + assert panel.sidebar_icon == "mdi:remote" + + +async def test_panel_kept_while_another_entry_is_loaded(hass: HomeAssistant) -> None: + """Unloading one of two entries keeps the panel.""" + first = await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:01")) + await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:02")) + + assert await hass.config_entries.async_unload(first.entry_id) + await hass.async_block_till_done() + + assert PANEL_URL_PATH in hass.data[frontend.DATA_PANELS] + + +async def test_panel_removed_when_last_entry_unloaded(hass: HomeAssistant) -> None: + """Unloading the last entry removes the panel.""" + entry = await setup_screen(hass, await register_screen(hass)) + + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + + assert PANEL_URL_PATH not in hass.data[frontend.DATA_PANELS] + + +async def test_static_path_registered_once(hass: HomeAssistant) -> None: + """The bundle route is registered once for several entries.""" + assert await async_setup_component(hass, "http", {}) + with patch.object(hass.http, "async_register_static_paths", AsyncMock()) as register: + await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:01")) + await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:02")) + + ours = [ + config + for call in register.await_args_list + for config in call.args[0] + if config.url_path.startswith("/ha_controller_static") + ] + assert len(ours) == 1 + assert ours[0].url_path == "/ha_controller_static/ha-controller-panel.js" + assert ours[0].path.endswith("frontend/dist/ha-controller-panel.js") + assert ours[0].cache_headers is True + + +async def test_missing_bundle_warns(hass: HomeAssistant, caplog) -> None: + """A missing bundle only logs a warning.""" + entry = await setup_screen(hass, await register_screen(hass)) + + assert entry.state.name == "LOADED" + assert "bundle" in caplog.text diff --git a/docs/README.md b/docs/README.md index 8af78e5..8b6700c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3,3 +3,4 @@ - [Architecture](architecture.md): subsystems, data flow and repository layout. - [Design specification](superpowers/specs/2026-11-16-ha-controller-design.md): the approved design for version 1, with the plans in `superpowers/plans/`. - [Device protocol v1](protocol/README.md): the normative layout model and device protocol, pinned by `docs/protocol/fixtures/`. +- [Development](development.md): environments, tests and running a development Home Assistant. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..3737ce3 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,47 @@ +# Development + +## Prerequisites + +- Python 3.14 (integration tests and repository checks). +- Node 24 (panel build, filled in by plan 3). +- ESPHome (firmware build, filled in by plan 4). + +Each part of the repository has its own virtual environment: the integration uses `custom_components/.venv`, the repository checks use `.github/scripts/.venv`. + +## Home Assistant integration + +Create the environment and install the test requirements from the repository root: + +```bash +python3.14 -m venv custom_components/.venv +custom_components/.venv/bin/pip install -r custom_components/requirements_test.txt +``` + +Run the tests and the linter: + +```bash +custom_components/.venv/bin/pytest custom_components/ha_controller/tests +custom_components/.venv/bin/ruff check custom_components +``` + +### Running a development Home Assistant + +Symlink the integration into the configuration directory of a development Home Assistant, then restart it: + +```bash +ln -s "$PWD/custom_components/ha_controller" /custom_components/ha_controller +``` + +Add the integration from Settings › Devices & services. The sidebar panel only shows up once the panel bundle has been built; until then Home Assistant logs a warning that the bundle is missing. + +### Watching the traffic + +The screen reports itself with ESPHome events. Open Developer tools › Events, listen to `esphome.ha_controller_hello` and reconnect the screen: every hello shows up there, followed by the layout the integration sends back with `set_layout`. + +## Panel + +Filled in by plan 3. + +## Firmware + +Filled in by plan 4. From 94e9796585e7de697f189d8a73e3a660874a1a38 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:39:34 +0100 Subject: [PATCH 20/49] feat(panel): add panel tooling, grid model and validation Co-Authored-By: Claude Sonnet 5.5 --- .claude/CLAUDE.md | 6 + .github/workflows/ci.yml | 16 + .../ha_controller/frontend/package-lock.json | 1752 +++++++++++++++++ .../ha_controller/frontend/package.json | 21 + .../ha_controller/frontend/src/model/emoji.ts | 9 + .../ha_controller/frontend/src/model/grid.ts | 66 + .../frontend/src/model/validate.ts | 155 ++ .../ha_controller/frontend/src/types.ts | 65 + .../ha_controller/frontend/test/fixtures.ts | 20 + .../ha_controller/frontend/test/grid.test.ts | 57 + .../frontend/test/validate.test.ts | 22 + .../ha_controller/frontend/tsconfig.json | 15 + .../ha_controller/frontend/vite.config.ts | 16 + 13 files changed, 2220 insertions(+) create mode 100644 custom_components/ha_controller/frontend/package-lock.json create mode 100644 custom_components/ha_controller/frontend/package.json create mode 100644 custom_components/ha_controller/frontend/src/model/emoji.ts create mode 100644 custom_components/ha_controller/frontend/src/model/grid.ts create mode 100644 custom_components/ha_controller/frontend/src/model/validate.ts create mode 100644 custom_components/ha_controller/frontend/src/types.ts create mode 100644 custom_components/ha_controller/frontend/test/fixtures.ts create mode 100644 custom_components/ha_controller/frontend/test/grid.test.ts create mode 100644 custom_components/ha_controller/frontend/test/validate.test.ts create mode 100644 custom_components/ha_controller/frontend/tsconfig.json create mode 100644 custom_components/ha_controller/frontend/vite.config.ts diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 4d72a74..1c280e9 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -41,6 +41,12 @@ python3.14 -m venv custom_components/.venv custom_components/.venv/bin/pip install -r custom_components/requirements_test.txt custom_components/.venv/bin/pytest custom_components/ha_controller/tests custom_components/.venv/bin/ruff check custom_components + +# Panel (Node 24, run from the repository root) +npm --prefix custom_components/ha_controller/frontend ci +npm --prefix custom_components/ha_controller/frontend test +npm --prefix custom_components/ha_controller/frontend run typecheck +npm --prefix custom_components/ha_controller/frontend run build ``` ## Skills and agents diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df615a1..908441d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,3 +27,19 @@ jobs: - run: pip install -r custom_components/requirements_test.txt - run: ruff check custom_components - run: pytest custom_components/ha_controller/tests + + frontend: + runs-on: ubuntu-latest + defaults: + run: + working-directory: custom_components/ha_controller/frontend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: custom_components/ha_controller/frontend/package-lock.json + - run: npm ci + - run: npm test + - run: npm run build diff --git a/custom_components/ha_controller/frontend/package-lock.json b/custom_components/ha_controller/frontend/package-lock.json new file mode 100644 index 0000000..cdbc800 --- /dev/null +++ b/custom_components/ha_controller/frontend/package-lock.json @@ -0,0 +1,1752 @@ +{ + "name": "ha-controller-panel", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ha-controller-panel", + "version": "0.1.0", + "dependencies": { + "lit": "^3.3.3" + }, + "devDependencies": { + "happy-dom": "^21.0.4", + "typescript": "^7.0.2", + "vite": "^8.3.8", + "vitest": "^5.1.0" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@lit-labs/ssr-dom-shim": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz", + "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@lit/reactive-element": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz", + "integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/happy-dom": { + "version": "21.0.4", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.4.tgz", + "integrity": "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lit": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.3.tgz", + "integrity": "sha512-fycuvZg/hkpozL00lm1pEJH5nN/lr9ZXd6mJI2HSN4+Bzc+LDNdEApJ6HFbPkdFNHLvOplIIuJvxkS4XUxqirw==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit/reactive-element": "^2.1.0", + "lit-element": "^4.2.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-element": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz", + "integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0", + "@lit/reactive-element": "^2.1.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-html": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.3.tgz", + "integrity": "sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==", + "license": "BSD-3-Clause", + "dependencies": { + "@types/trusted-types": "^2.0.2" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/custom_components/ha_controller/frontend/package.json b/custom_components/ha_controller/frontend/package.json new file mode 100644 index 0000000..be5858d --- /dev/null +++ b/custom_components/ha_controller/frontend/package.json @@ -0,0 +1,21 @@ +{ + "name": "ha-controller-panel", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --open dev/index.html", + "build": "tsc --noEmit && vite build", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "lit": "^3.3.3" + }, + "devDependencies": { + "happy-dom": "^21.0.4", + "typescript": "^7.0.2", + "vite": "^8.3.8", + "vitest": "^5.1.0" + } +} diff --git a/custom_components/ha_controller/frontend/src/model/emoji.ts b/custom_components/ha_controller/frontend/src/model/emoji.ts new file mode 100644 index 0000000..b0fe5ba --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/emoji.ts @@ -0,0 +1,9 @@ +import emoji from "../../../emoji.json"; + +export const SUPPORTED_EMOJI: readonly string[] = emoji; +export const EMOJI_SET: ReadonlySet = new Set(SUPPORTED_EMOJI); + +/** Remove the emoji variation selector U+FE0F. */ +export function normalizeEmoji(text: string): string { + return text.replaceAll("️", ""); +} diff --git a/custom_components/ha_controller/frontend/src/model/grid.ts b/custom_components/ha_controller/frontend/src/model/grid.ts new file mode 100644 index 0000000..40b8e38 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/grid.ts @@ -0,0 +1,66 @@ +import type {Block, Cell, Layout} from "../types"; + +const LIMIT = 32; +const DIRECTIONS: readonly Cell[] = [ + {x: 1, y: 0}, + {x: -1, y: 0}, + {x: 0, y: 1}, + {x: 0, y: -1}, +]; + +const key = (x: number, y: number): string => `${x},${y}`; + +/** Empty cells next to a block, within the coordinate limit, sorted by y then x. */ +export function placeholders(layout: Layout): Cell[] { + const {blocks} = layout; + if (blocks.length === 0) return [{x: 0, y: 0}]; + if (blocks.length >= LIMIT) return []; + const taken = new Set(blocks.map((b) => key(b.x, b.y))); + const found = new Map(); + for (const block of blocks) { + for (const d of DIRECTIONS) { + const x = block.x + d.x; + const y = block.y + d.y; + if (Math.abs(x) > LIMIT || Math.abs(y) > LIMIT) continue; + const k = key(x, y); + if (!taken.has(k)) found.set(k, {x, y}); + } + } + return [...found.values()].sort((a, b) => a.y - b.y || a.x - b.x); +} + +/** Ids of the blocks reachable from the start block through adjacent blocks. */ +export function reachable(blocks: Block[], start: string | null): Set { + const first = blocks.find((b) => b.id === start); + if (!first) return new Set(); + const byCell = new Map(blocks.map((b) => [key(b.x, b.y), b])); + const seen = new Set([first.id]); + const queue = [first]; + while (queue.length > 0) { + const current = queue.shift() as Block; + for (const d of DIRECTIONS) { + const next = byCell.get(key(current.x + d.x, current.y + d.y)); + if (next && !seen.has(next.id)) { + seen.add(next.id); + queue.push(next); + } + } + } + return seen; +} + +export type DeleteCheck = {ok: true} | {ok: false; reason: "start" | "disconnects"}; + +export function canDelete(layout: Layout, id: string): DeleteCheck { + if (layout.blocks.length > 1 && layout.start === id) return {ok: false, reason: "start"}; + const rest = layout.blocks.filter((b) => b.id !== id); + if (rest.length === 0) return {ok: true}; + const seen = reachable(rest, layout.start); + return rest.every((b) => seen.has(b.id)) ? {ok: true} : {ok: false, reason: "disconnects"}; +} + +export function gridBounds(cells: Cell[]): {minX: number; maxX: number; minY: number; maxY: number} { + const xs = cells.map((c) => c.x); + const ys = cells.map((c) => c.y); + return {minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys)}; +} diff --git a/custom_components/ha_controller/frontend/src/model/validate.ts b/custom_components/ha_controller/frontend/src/model/validate.ts new file mode 100644 index 0000000..e2bf8e8 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/validate.ts @@ -0,0 +1,155 @@ +import type {Block, LayoutError} from "../types"; +import {normalizeEmoji} from "./emoji"; +import {reachable} from "./grid"; + +const MAX_BLOCKS = 32; +const MAX_ITEMS = 6; +const MAX_NAME_LEN = 32; +const MAX_TEXT_LEN = 64; +const MAX_ATTRIBUTE_LEN = 64; +const COORD_LIMIT = 32; +const MIN_SLEEP_TIMEOUT = 5; +const MAX_SLEEP_TIMEOUT = 3600; +const FONT_SIZES = ["s", "m", "l", "xl"]; +const ITEM_KINDS = ["text", "emoji", "entity", "battery", "brightness"]; +const ENTITY_BLOCK_DOMAINS = ["light", "climate"]; + +const ID_RE = /^[a-z][a-z0-9]{0,7}$/; +const COLOR_RE = /^#[0-9A-Fa-f]{6}$/; +const ENTITY_RE = /^[a-z0-9_]+\.[a-z0-9_]+$/; + +type Obj = Record; + +const isObj = (v: unknown): v is Obj => typeof v === "object" && v !== null && !Array.isArray(v); +const isInt = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v); +const isId = (v: unknown): v is string => typeof v === "string" && ID_RE.test(v); +const isEntityId = (v: unknown): v is string => typeof v === "string" && ENTITY_RE.test(v); +const cpLen = (s: string): number => Array.from(s).length; +const refOf = (v: unknown): string | null => (typeof v === "string" ? v : null); + +function checkStructure(layout: unknown): layout is Obj & {settings: Obj; blocks: Obj[]} { + if (!isObj(layout) || layout.version !== 1 || !isObj(layout.settings)) return false; + const blocks = layout.blocks; + if (!Array.isArray(blocks) || !blocks.every(isObj)) return false; + for (const block of blocks as Obj[]) { + if (block.type === "custom") { + const items = block.items; + if (!Array.isArray(items) || !items.every(isObj)) return false; + } + } + return true; +} + +function validEntityItem(item: Obj): boolean { + if (!isEntityId(item.entity_id)) return false; + const attr = item.attribute; + return attr === undefined || attr === null || + (typeof attr === "string" && cpLen(attr) >= 1 && cpLen(attr) <= MAX_ATTRIBUTE_LEN); +} + +function validEntityBlock(block: Obj): boolean { + const id = block.entity_id; + return isEntityId(id) && ENTITY_BLOCK_DOMAINS.includes(id.split(".", 1)[0]); +} + +function checkItem(item: Obj, seen: Set, emoji: ReadonlySet, errors: LayoutError[]): void { + const ref = refOf(item.id); + if (!isId(item.id)) errors.push({code: "invalid_id", ref}); + if (typeof item.id === "string") { + if (seen.has(item.id)) errors.push({code: "duplicate_id", ref: item.id}); + seen.add(item.id); + } + const kind = item.kind; + if (typeof kind !== "string" || !ITEM_KINDS.includes(kind)) errors.push({code: "invalid_item", ref}); + const fontSize = item.font_size; + if (fontSize !== undefined && fontSize !== null && + (typeof fontSize !== "string" || !FONT_SIZES.includes(fontSize))) { + errors.push({code: "invalid_font_size", ref}); + } + if (kind === "text") { + const text = item.text; + if (typeof text !== "string" || cpLen(text) < 1 || cpLen(text) > MAX_TEXT_LEN) { + errors.push({code: "invalid_text", ref}); + } + } else if (kind === "emoji") { + const value = item.emoji; + if (typeof value !== "string" || !emoji.has(normalizeEmoji(value))) { + errors.push({code: "unsupported_emoji", ref}); + } + } else if (kind === "entity" && !validEntityItem(item)) { + errors.push({code: "invalid_entity", ref}); + } +} + +function checkBlock( + block: Obj, seen: Set, positions: Set, emoji: ReadonlySet, errors: LayoutError[], +): void { + const ref = refOf(block.id); + if (!isId(block.id)) errors.push({code: "invalid_id", ref}); + if (typeof block.id === "string") { + if (seen.has(block.id)) errors.push({code: "duplicate_id", ref: block.id}); + seen.add(block.id); + } + + const {x, y} = block; + if (![x, y].every((v) => isInt(v) && Math.abs(v) <= COORD_LIMIT)) { + errors.push({code: "coordinate_out_of_range", ref}); + } else { + const k = `${x},${y}`; + if (positions.has(k)) errors.push({code: "duplicate_position", ref}); + positions.add(k); + } + + const name = block.name; + if (typeof name !== "string" || cpLen(name.trim()) < 1 || cpLen(name.trim()) > MAX_NAME_LEN) { + errors.push({code: "invalid_name", ref}); + } + if (typeof block.background !== "string" || !COLOR_RE.test(block.background)) { + errors.push({code: "invalid_background", ref}); + } + if (typeof block.font_size !== "string" || !FONT_SIZES.includes(block.font_size)) { + errors.push({code: "invalid_font_size", ref}); + } + + if (block.type === "entity") { + if (!validEntityBlock(block)) errors.push({code: "invalid_entity", ref}); + } else if (block.type === "custom") { + const items = block.items as Obj[]; + if (items.length > MAX_ITEMS) errors.push({code: "too_many_items", ref}); + for (const item of items) checkItem(item, seen, emoji, errors); + } else { + errors.push({code: "invalid_type", ref}); + } +} + +function unreachable(layout: Obj & {blocks: Obj[]}): LayoutError[] { + if (layout.blocks.length === 0) return []; + const blocks = layout.blocks as unknown as Block[]; + const seen = reachable(blocks, layout.start as string); + return blocks.filter((b) => !seen.has(b.id)).map((b) => ({code: "disconnected", ref: b.id})); +} + +/** Validate a layout; an empty list means it is valid. Mirrors layout.py. */ +export function validateLayout(layout: unknown, emoji: ReadonlySet): LayoutError[] { + if (!checkStructure(layout)) return [{code: "invalid_structure", ref: null}]; + + const errors: LayoutError[] = []; + const blocks = layout.blocks; + if (blocks.length > MAX_BLOCKS) errors.push({code: "too_many_blocks", ref: null}); + const timeout = layout.settings.sleep_timeout; + if (!isInt(timeout) || !(timeout === 0 || (timeout >= MIN_SLEEP_TIMEOUT && timeout <= MAX_SLEEP_TIMEOUT))) { + errors.push({code: "invalid_sleep_timeout", ref: null}); + } + + const seen = new Set(); + const positions = new Set(); + for (const block of blocks) checkBlock(block, seen, positions, emoji, errors); + + const start = layout.start; + const startOk = start === undefined || start === null + ? blocks.length === 0 + : typeof start === "string" && blocks.some((b) => b.id === start); + if (!startOk) errors.push({code: "invalid_start", ref: null}); + + return errors.length > 0 ? errors : unreachable(layout); +} diff --git a/custom_components/ha_controller/frontend/src/types.ts b/custom_components/ha_controller/frontend/src/types.ts new file mode 100644 index 0000000..7c01e8a --- /dev/null +++ b/custom_components/ha_controller/frontend/src/types.ts @@ -0,0 +1,65 @@ +export type FontSize = "s" | "m" | "l" | "xl"; +export type ItemKind = "text" | "emoji" | "entity" | "battery" | "brightness"; + +export interface Item { + id: string; + kind: ItemKind; + font_size: FontSize | null; + text?: string; + emoji?: string; + entity_id?: string; + attribute?: string | null; +} + +export interface Block { + id: string; + x: number; + y: number; + name: string; + background: string; + font_size: FontSize; + type: "entity" | "custom"; + entity_id?: string; + items?: Item[]; +} + +export interface Layout { + version: 1; + start: string | null; + settings: {sleep_timeout: number}; + blocks: Block[]; +} + +export interface LayoutError { + code: string; + ref: string | null; +} + +export interface Cell { + x: number; + y: number; +} + +/** Screen status as sent by the websocket API (spec section 8). */ +export interface ScreenInfo { + device_id: string; + name: string; + online: boolean; + firmware_version: string | null; + battery: number | null; + charging: boolean | null; + brightness: number | null; + layout: Layout; + [key: string]: unknown; +} + +export interface HassEntity { + entity_id: string; + state: string; + attributes: Record; +} + +export interface Hass { + states: Record; + callWS(msg: {type: string; [key: string]: unknown}): Promise; +} diff --git a/custom_components/ha_controller/frontend/test/fixtures.ts b/custom_components/ha_controller/frontend/test/fixtures.ts new file mode 100644 index 0000000..c2533c9 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/fixtures.ts @@ -0,0 +1,20 @@ +import type {Layout, LayoutError} from "../src/types"; + +function byName(modules: Record): Record { + return Object.fromEntries( + Object.entries(modules).map(([path, value]) => [path.split("/").pop()!.replace(/\.json$/, ""), value]), + ); +} + +export const validLayouts = byName( + import.meta.glob("../../../../docs/protocol/fixtures/layouts/valid/*.json", {eager: true, import: "default"}), +); + +export const invalidLayouts = byName( + import.meta.glob<{expect: LayoutError; layout: unknown}>( + "../../../../docs/protocol/fixtures/layouts/invalid/*.json", {eager: true, import: "default"}), +); + +export const colors = Object.values( + import.meta.glob<{bg: string; text: string}[]>("../../../../docs/protocol/fixtures/colors.json", {eager: true, import: "default"}), +)[0]; diff --git a/custom_components/ha_controller/frontend/test/grid.test.ts b/custom_components/ha_controller/frontend/test/grid.test.ts new file mode 100644 index 0000000..bb7da4e --- /dev/null +++ b/custom_components/ha_controller/frontend/test/grid.test.ts @@ -0,0 +1,57 @@ +import {describe, expect, it} from "vitest"; +import {canDelete, gridBounds, placeholders} from "../src/model/grid"; +import type {Block, Cell, Layout} from "../src/types"; +import {validLayouts} from "./fixtures"; + +const block = (id: string, x: number, y: number): Block => ({ + id, x, y, name: id, background: "#000000", font_size: "m", type: "custom", items: [], +}); +const layoutOf = (blocks: Block[]): Layout => ({ + version: 1, start: blocks[0]?.id ?? null, settings: {sleep_timeout: 20}, blocks, +}); +const cellsOf = (layout: Layout): Cell[] => layout.blocks.map(({x, y}) => ({x, y})); + +describe("fixtures", () => { + it("are loaded", () => { + expect(Object.keys(validLayouts).length).toBeGreaterThan(0); + }); +}); + +describe("placeholders", () => { + it("offers the origin for an empty layout", () => { + expect(placeholders(validLayouts.empty)).toEqual([{x: 0, y: 0}]); + }); + it("finds the 8 plus cells of the reference screenshot", () => { + expect(placeholders(validLayouts.reference)).toEqual([ + {x: 0, y: -2}, {x: -1, y: -1}, {x: 1, y: -1}, {x: -2, y: 0}, + {x: 1, y: 0}, {x: -2, y: 1}, {x: 0, y: 1}, {x: -1, y: 2}]); + }); + it("offers nothing at 32 blocks", () => { + const row = Array.from({length: 32}, (_, i) => block(`b${i}`, i, 0)); + expect(placeholders(layoutOf(row))).toEqual([]); + }); + it("stays within the coordinate limit", () => { + expect(placeholders(layoutOf([block("b1", 32, 0)]))).not.toContainEqual({x: 33, y: 0}); + }); +}); + +describe("canDelete", () => { + it("refuses the start block", () => { + expect(canDelete(validLayouts.reference, "b1")).toEqual({ok: false, reason: "start"}); + }); + it("refuses a block that disconnects another", () => { + expect(canDelete(validLayouts.reference, "b3")).toEqual({ok: false, reason: "disconnects"}); + }); + it("allows a leaf block", () => { + expect(canDelete(validLayouts.reference, "b2")).toEqual({ok: true}); + }); + it("allows deleting the only block", () => { + expect(canDelete(validLayouts.single, "b1")).toEqual({ok: true}); + }); +}); + +describe("gridBounds", () => { + it("bounds a single cell", () => { + expect(gridBounds(cellsOf(validLayouts.single))).toEqual({minX: 3, maxX: 3, minY: -2, maxY: -2}); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/validate.test.ts b/custom_components/ha_controller/frontend/test/validate.test.ts new file mode 100644 index 0000000..977605d --- /dev/null +++ b/custom_components/ha_controller/frontend/test/validate.test.ts @@ -0,0 +1,22 @@ +import {describe, expect, it} from "vitest"; +import {EMOJI_SET} from "../src/model/emoji"; +import {validateLayout} from "../src/model/validate"; +import {colors, invalidLayouts, validLayouts} from "./fixtures"; + +describe("validateLayout", () => { + it("has fixtures", () => { + expect(Object.keys(validLayouts).length).toBeGreaterThan(0); + expect(Object.keys(invalidLayouts).length).toBeGreaterThan(0); + expect(colors.length).toBeGreaterThan(0); + }); + for (const [name, layout] of Object.entries(validLayouts)) { + it(`accepts valid/${name}`, () => { + expect(validateLayout(layout, EMOJI_SET)).toEqual([]); + }); + } + for (const [name, c] of Object.entries(invalidLayouts)) { + it(`rejects invalid/${name}`, () => { + expect(validateLayout(c.layout, EMOJI_SET)).toEqual([c.expect]); + }); + } +}); diff --git a/custom_components/ha_controller/frontend/tsconfig.json b/custom_components/ha_controller/frontend/tsconfig.json new file mode 100644 index 0000000..9b685a7 --- /dev/null +++ b/custom_components/ha_controller/frontend/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "experimentalDecorators": true, + "useDefineForClassFields": false, + "resolveJsonModule": true, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["src", "test", "vite.config.ts"] +} diff --git a/custom_components/ha_controller/frontend/vite.config.ts b/custom_components/ha_controller/frontend/vite.config.ts new file mode 100644 index 0000000..b94db59 --- /dev/null +++ b/custom_components/ha_controller/frontend/vite.config.ts @@ -0,0 +1,16 @@ +import {defineConfig} from "vitest/config"; + +export default defineConfig({ + build: { + lib: { + entry: "src/ha-controller-panel.ts", + formats: ["es"], + fileName: () => "ha-controller-panel.js", + }, + outDir: "dist", + emptyOutDir: true, + target: "es2022", + }, + server: {fs: {allow: ["../../.."]}}, + test: {environment: "happy-dom"}, +}); From f619031587411905af7e718a0d07684348994a31 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:41:51 +0100 Subject: [PATCH 21/49] feat(panel): add pure layout edit operations Co-Authored-By: Claude Sonnet 5.5 --- .../ha_controller/frontend/src/model/color.ts | 15 +++ .../ha_controller/frontend/src/model/edit.ts | 95 +++++++++++++++++++ .../ha_controller/frontend/src/model/emoji.ts | 2 +- .../ha_controller/frontend/src/model/grid.ts | 6 +- .../frontend/src/model/limits.ts | 4 + .../frontend/src/model/validate.ts | 4 +- .../ha_controller/frontend/test/color.test.ts | 10 ++ .../ha_controller/frontend/test/edit.test.ts | 86 +++++++++++++++++ .../ha_controller/frontend/test/emoji.test.ts | 13 +++ 9 files changed, 228 insertions(+), 7 deletions(-) create mode 100644 custom_components/ha_controller/frontend/src/model/color.ts create mode 100644 custom_components/ha_controller/frontend/src/model/edit.ts create mode 100644 custom_components/ha_controller/frontend/src/model/limits.ts create mode 100644 custom_components/ha_controller/frontend/test/color.test.ts create mode 100644 custom_components/ha_controller/frontend/test/edit.test.ts create mode 100644 custom_components/ha_controller/frontend/test/emoji.test.ts diff --git a/custom_components/ha_controller/frontend/src/model/color.ts b/custom_components/ha_controller/frontend/src/model/color.ts new file mode 100644 index 0000000..3d234eb --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/color.ts @@ -0,0 +1,15 @@ +const channel = (value: number): number => { + const c = value / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; +}; + +/** WCAG relative luminance of a #RRGGBB colour. */ +function luminance(hex: string): number { + const n = parseInt(hex.slice(1), 16); + return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255); +} + +/** Black text on light backgrounds, white on dark ones (spec section 5.5). */ +export function textColorFor(bg: string): "#000000" | "#FFFFFF" { + return luminance(bg) > 0.3 ? "#000000" : "#FFFFFF"; +} diff --git a/custom_components/ha_controller/frontend/src/model/edit.ts b/custom_components/ha_controller/frontend/src/model/edit.ts new file mode 100644 index 0000000..ba0b659 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/edit.ts @@ -0,0 +1,95 @@ +import type {Block, Cell, Item, ItemKind, Layout} from "../types"; +import {canDelete} from "./grid"; +import {MAX_BLOCKS} from "./limits"; + +export const PALETTE: readonly string[] = [ + "#C94F3D", "#4F86DD", "#5B9E4D", "#7B2FA0", "#E08A2E", "#2E9E8F", "#D2477A", "#5C6BC0", +]; + +const suffix = (id: string, prefix: string): number => + id.startsWith(prefix) && /^\d+$/.test(id.slice(prefix.length)) ? Number(id.slice(prefix.length)) : 0; + +/** One plus the highest numeric suffix among block and item ids with this prefix. */ +export function nextId(layout: Layout, prefix: "b" | "i"): string { + let max = 0; + for (const block of layout.blocks) { + max = Math.max(max, suffix(block.id, prefix)); + for (const item of block.items ?? []) max = Math.max(max, suffix(item.id, prefix)); + } + return `${prefix}${max + 1}`; +} + +export function addBlock(layout: Layout, cell: Cell): {layout: Layout; id: string} { + if (layout.blocks.length >= MAX_BLOCKS) throw new Error("too_many_blocks"); + const id = nextId(layout, "b"); + const block: Block = { + id, + x: cell.x, + y: cell.y, + name: `Block ${suffix(id, "b")}`, + background: PALETTE[layout.blocks.length % PALETTE.length], + font_size: "m", + type: "custom", + items: [], + }; + return {layout: {...layout, start: layout.start ?? id, blocks: [...layout.blocks, block]}, id}; +} + +export function deleteBlock(layout: Layout, id: string): Layout { + const check = canDelete(layout, id); + if (!check.ok) throw new Error(check.reason); + const blocks = layout.blocks.filter((b) => b.id !== id); + return {...layout, start: blocks.length === 0 ? null : layout.start, blocks}; +} + +export function setStart(layout: Layout, id: string): Layout { + return {...layout, start: id}; +} + +export function updateBlock(layout: Layout, id: string, patch: Partial): Layout { + return {...layout, blocks: layout.blocks.map((b) => (b.id === id ? {...b, ...patch} : b))}; +} + +export function setSleepTimeout(layout: Layout, seconds: number): Layout { + return {...layout, settings: {...layout.settings, sleep_timeout: seconds}}; +} + +function withItems(layout: Layout, blockId: string, change: (items: Item[]) => Item[]): Layout { + return { + ...layout, + blocks: layout.blocks.map((b) => (b.id === blockId ? {...b, items: change(b.items ?? [])} : b)), + }; +} + +const DEFAULT_ITEMS: Record> = { + text: {text: "Text"}, + emoji: {emoji: "💡"}, + entity: {entity_id: "", attribute: null}, + battery: {}, + brightness: {}, +}; + +export function addItem(layout: Layout, blockId: string, kind: ItemKind): {layout: Layout; id: string} { + const id = nextId(layout, "i"); + const item: Item = {id, kind, ...DEFAULT_ITEMS[kind], font_size: null}; + return {layout: withItems(layout, blockId, (items) => [...items, item]), id}; +} + +export function updateItem(layout: Layout, blockId: string, itemId: string, patch: Partial): Layout { + return withItems(layout, blockId, (items) => items.map((i) => (i.id === itemId ? {...i, ...patch} : i))); +} + +export function removeItem(layout: Layout, blockId: string, itemId: string): Layout { + return withItems(layout, blockId, (items) => items.filter((i) => i.id !== itemId)); +} + +export function moveItem(layout: Layout, blockId: string, itemId: string, delta: -1 | 1): Layout { + return withItems(layout, blockId, (items) => { + const from = items.findIndex((i) => i.id === itemId); + const to = from + delta; + if (from < 0 || to < 0 || to >= items.length) return items; + const next = [...items]; + [next[from], next[to]] = [next[to], next[from]]; + return next; + }); +} diff --git a/custom_components/ha_controller/frontend/src/model/emoji.ts b/custom_components/ha_controller/frontend/src/model/emoji.ts index b0fe5ba..6bce298 100644 --- a/custom_components/ha_controller/frontend/src/model/emoji.ts +++ b/custom_components/ha_controller/frontend/src/model/emoji.ts @@ -5,5 +5,5 @@ export const EMOJI_SET: ReadonlySet = new Set(SUPPORTED_EMOJI); /** Remove the emoji variation selector U+FE0F. */ export function normalizeEmoji(text: string): string { - return text.replaceAll("️", ""); + return text.replaceAll("\uFE0F", ""); } diff --git a/custom_components/ha_controller/frontend/src/model/grid.ts b/custom_components/ha_controller/frontend/src/model/grid.ts index 40b8e38..0baf3e7 100644 --- a/custom_components/ha_controller/frontend/src/model/grid.ts +++ b/custom_components/ha_controller/frontend/src/model/grid.ts @@ -1,6 +1,6 @@ import type {Block, Cell, Layout} from "../types"; +import {COORD_LIMIT, MAX_BLOCKS} from "./limits"; -const LIMIT = 32; const DIRECTIONS: readonly Cell[] = [ {x: 1, y: 0}, {x: -1, y: 0}, @@ -14,14 +14,14 @@ const key = (x: number, y: number): string => `${x},${y}`; export function placeholders(layout: Layout): Cell[] { const {blocks} = layout; if (blocks.length === 0) return [{x: 0, y: 0}]; - if (blocks.length >= LIMIT) return []; + if (blocks.length >= MAX_BLOCKS) return []; const taken = new Set(blocks.map((b) => key(b.x, b.y))); const found = new Map(); for (const block of blocks) { for (const d of DIRECTIONS) { const x = block.x + d.x; const y = block.y + d.y; - if (Math.abs(x) > LIMIT || Math.abs(y) > LIMIT) continue; + if (Math.abs(x) > COORD_LIMIT || Math.abs(y) > COORD_LIMIT) continue; const k = key(x, y); if (!taken.has(k)) found.set(k, {x, y}); } diff --git a/custom_components/ha_controller/frontend/src/model/limits.ts b/custom_components/ha_controller/frontend/src/model/limits.ts new file mode 100644 index 0000000..67074a5 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/limits.ts @@ -0,0 +1,4 @@ +/** Layout limits shared with the Python validator (spec section 6). */ +export const MAX_BLOCKS = 32; +export const MAX_ITEMS = 6; +export const COORD_LIMIT = 32; diff --git a/custom_components/ha_controller/frontend/src/model/validate.ts b/custom_components/ha_controller/frontend/src/model/validate.ts index e2bf8e8..e1113c6 100644 --- a/custom_components/ha_controller/frontend/src/model/validate.ts +++ b/custom_components/ha_controller/frontend/src/model/validate.ts @@ -1,13 +1,11 @@ import type {Block, LayoutError} from "../types"; import {normalizeEmoji} from "./emoji"; import {reachable} from "./grid"; +import {COORD_LIMIT, MAX_BLOCKS, MAX_ITEMS} from "./limits"; -const MAX_BLOCKS = 32; -const MAX_ITEMS = 6; const MAX_NAME_LEN = 32; const MAX_TEXT_LEN = 64; const MAX_ATTRIBUTE_LEN = 64; -const COORD_LIMIT = 32; const MIN_SLEEP_TIMEOUT = 5; const MAX_SLEEP_TIMEOUT = 3600; const FONT_SIZES = ["s", "m", "l", "xl"]; diff --git a/custom_components/ha_controller/frontend/test/color.test.ts b/custom_components/ha_controller/frontend/test/color.test.ts new file mode 100644 index 0000000..5b3340c --- /dev/null +++ b/custom_components/ha_controller/frontend/test/color.test.ts @@ -0,0 +1,10 @@ +import {describe, expect, it} from "vitest"; +import {textColorFor} from "../src/model/color"; +import {colors} from "./fixtures"; + +describe("textColorFor", () => { + it("matches the shared vectors", () => { + expect(colors.length).toBeGreaterThan(0); + for (const c of colors) expect(textColorFor(c.bg)).toBe(c.text); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/edit.test.ts b/custom_components/ha_controller/frontend/test/edit.test.ts new file mode 100644 index 0000000..e2e9949 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/edit.test.ts @@ -0,0 +1,86 @@ +import {describe, expect, it} from "vitest"; +import { + PALETTE, addBlock, addItem, deleteBlock, moveItem, nextId, removeItem, setSleepTimeout, setStart, + updateBlock, updateItem, +} from "../src/model/edit"; +import type {Layout} from "../src/types"; +import {validLayouts} from "./fixtures"; + +const ref = validLayouts.reference; +const itemIds = (l: Layout, blockId: string): string[] => + (l.blocks.find((b) => b.id === blockId)?.items ?? []).map((i) => i.id); + +describe("edit operations", () => { + it("has an 8 colour palette", () => expect(PALETTE).toHaveLength(8)); + + it("nextId continues the highest suffix", () => { + expect(nextId(ref, "i")).toBe("i6"); + expect(nextId(ref, "b")).toBe("b5"); + expect(nextId(validLayouts.empty, "b")).toBe("b1"); + }); + + it("addBlock", () => { + const r = addBlock(ref, {x: 1, y: 0}); + expect(r.id).toBe("b5"); + expect(r.layout.blocks.at(-1)).toMatchObject({ + x: 1, y: 0, name: "Block 5", background: "#E08A2E", font_size: "m", type: "custom", items: [], + }); + expect(r.layout.start).toBe("b1"); + expect(addBlock(validLayouts.empty, {x: 0, y: 0}).layout).toMatchObject({ + start: "b1", blocks: [{id: "b1", background: "#C94F3D"}], + }); + }); + + it("deleteBlock", () => { + expect(deleteBlock(validLayouts.single, "b1")).toEqual({ + version: 1, start: null, settings: {sleep_timeout: 0}, blocks: [], + }); + expect(deleteBlock(ref, "b4").blocks.map((b) => b.id)).toEqual(["b1", "b2", "b3"]); + expect(() => deleteBlock(ref, "b3")).toThrow(); + expect(() => deleteBlock(ref, "b1")).toThrow(); + }); + + it("setStart, updateBlock, setSleepTimeout", () => { + expect(setStart(ref, "b2").start).toBe("b2"); + expect(updateBlock(ref, "b2", {name: "X"}).blocks[1].name).toBe("X"); + expect(setSleepTimeout(ref, 45).settings).toEqual({sleep_timeout: 45}); + }); + + it("addItem defaults", () => { + const text = addItem(ref, "b3", "text"); + expect(text.id).toBe("i6"); + expect(text.layout.blocks[2].items?.at(-1)).toEqual({id: "i6", kind: "text", text: "Text", font_size: null}); + expect(addItem(ref, "b3", "emoji").layout.blocks[2].items?.at(-1)) + .toEqual({id: "i6", kind: "emoji", emoji: "💡", font_size: null}); + expect(addItem(ref, "b3", "entity").layout.blocks[2].items?.at(-1)) + .toEqual({id: "i6", kind: "entity", entity_id: "", attribute: null, font_size: null}); + expect(addItem(ref, "b3", "battery").layout.blocks[2].items?.at(-1)) + .toEqual({id: "i6", kind: "battery", font_size: null}); + }); + + it("updateItem and removeItem", () => { + expect(updateItem(ref, "b3", "i1", {text: "Hi"}).blocks[2].items?.[0]).toMatchObject({id: "i1", text: "Hi"}); + expect(itemIds(removeItem(ref, "b3", "i2"), "b3")).toEqual(["i1", "i3", "i4", "i5"]); + }); + + it("moveItem", () => { + expect(itemIds(moveItem(ref, "b3", "i1", 1), "b3")).toEqual(["i2", "i1", "i3", "i4", "i5"]); + expect(itemIds(moveItem(ref, "b3", "i1", -1), "b3")).toEqual(["i1", "i2", "i3", "i4", "i5"]); + expect(itemIds(moveItem(ref, "b3", "i5", 1), "b3")).toEqual(["i1", "i2", "i3", "i4", "i5"]); + expect(itemIds(moveItem(ref, "b3", "i3", -1), "b3")).toEqual(["i1", "i3", "i2", "i4", "i5"]); + }); + + it("never mutates its input", () => { + const copy = structuredClone(ref); + addBlock(copy, {x: 1, y: 0}); + deleteBlock(copy, "b4"); + setStart(copy, "b2"); + updateBlock(copy, "b2", {name: "X"}); + setSleepTimeout(copy, 45); + addItem(copy, "b3", "text"); + updateItem(copy, "b3", "i1", {text: "Hi"}); + removeItem(copy, "b3", "i2"); + moveItem(copy, "b3", "i1", 1); + expect(copy).toEqual(ref); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/emoji.test.ts b/custom_components/ha_controller/frontend/test/emoji.test.ts new file mode 100644 index 0000000..a4e9f31 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/emoji.test.ts @@ -0,0 +1,13 @@ +import {describe, expect, it} from "vitest"; +import {EMOJI_SET, SUPPORTED_EMOJI, normalizeEmoji} from "../src/model/emoji"; + +describe("emoji", () => { + it("has 64 supported emoji", () => { + expect(SUPPORTED_EMOJI).toHaveLength(64); + expect(EMOJI_SET.size).toBe(64); + }); + it("strips the variation selector", () => { + expect(normalizeEmoji("❄️")).toBe("❄"); + expect(normalizeEmoji("💡")).toBe("💡"); + }); +}); From 03f60e01d2232fbdbf52811977f7e0075eea48b2 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:44:30 +0100 Subject: [PATCH 22/49] feat(panel): render the block map Co-Authored-By: Claude Sonnet 5.5 --- .../frontend/src/components/hc-grid.ts | 119 ++++++++++++++++++ .../ha_controller/frontend/test/dom.ts | 23 ++++ .../frontend/test/hc-grid.test.ts | 58 +++++++++ 3 files changed, 200 insertions(+) create mode 100644 custom_components/ha_controller/frontend/src/components/hc-grid.ts create mode 100644 custom_components/ha_controller/frontend/test/dom.ts create mode 100644 custom_components/ha_controller/frontend/test/hc-grid.test.ts diff --git a/custom_components/ha_controller/frontend/src/components/hc-grid.ts b/custom_components/ha_controller/frontend/src/components/hc-grid.ts new file mode 100644 index 0000000..6a39956 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-grid.ts @@ -0,0 +1,119 @@ +import {LitElement, css, html, nothing} from "lit"; +import {customElement, property} from "lit/decorators.js"; +import {gridBounds, placeholders} from "../model/grid"; +import {textColorFor} from "../model/color"; +import type {Layout} from "../types"; + +/** Block map: x grows to the right, y grows downwards, like navigation on the screen. */ +@customElement("hc-grid") +export class HcGrid extends LitElement { + @property({attribute: false}) layout: Layout = {version: 1, start: null, settings: {sleep_timeout: 0}, blocks: []}; + @property({attribute: false}) selectedId: string | null = null; + @property({attribute: false}) errorRefs: ReadonlySet = new Set(); + + static styles = css` + :host { + display: block; + overflow: auto; + } + .grid { + display: grid; + grid-auto-columns: 96px; + grid-auto-rows: 96px; + gap: 12px; + padding: 12px; + width: max-content; + } + button { + all: unset; + box-sizing: border-box; + cursor: pointer; + border-radius: 16px; + display: flex; + align-items: center; + justify-content: center; + text-align: center; + position: relative; + font: inherit; + font-weight: 500; + padding: 8px; + overflow: hidden; + overflow-wrap: anywhere; + } + button:focus-visible { + box-shadow: 0 0 0 3px var(--primary-color, #03a9f4); + } + .block.start { + outline: 3px solid var(--primary-text-color, #212121); + outline-offset: -3px; + } + .block.selected { + box-shadow: 0 0 0 3px var(--card-background-color, #fff), 0 0 0 6px var(--primary-color, #03a9f4); + overflow: visible; + } + .block.has-error { + box-shadow: 0 0 0 3px var(--card-background-color, #fff), 0 0 0 6px var(--error-color, #db4437); + overflow: visible; + } + .start-badge { + position: absolute; + top: 6px; + left: 8px; + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.05em; + opacity: 0.8; + } + .placeholder { + border: 2px dashed var(--divider-color, rgba(0, 0, 0, 0.12)); + color: var(--secondary-text-color, #727272); + font-size: 28px; + font-weight: 300; + } + .placeholder:hover { + border-color: var(--primary-color, #03a9f4); + color: var(--primary-color, #03a9f4); + } + `; + + render() { + const {blocks, start} = this.layout; + const empty = placeholders(this.layout); + const cells = [...blocks, ...empty]; + if (cells.length === 0) return nothing; + const {minX, minY} = gridBounds(cells); + const place = (x: number, y: number) => `grid-column: ${x - minX + 1}; grid-row: ${y - minY + 1}`; + return html`
    + ${blocks.map( + (b) => html``, + )} + ${empty.map( + (c) => html``, + )} +
    `; + } + + private emit(name: string, detail: unknown): void { + this.dispatchEvent(new CustomEvent(name, {detail, bubbles: true, composed: true})); + } +} + +declare global { + interface HTMLElementTagNameMap { + "hc-grid": HcGrid; + } +} diff --git a/custom_components/ha_controller/frontend/test/dom.ts b/custom_components/ha_controller/frontend/test/dom.ts new file mode 100644 index 0000000..4e7d782 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/dom.ts @@ -0,0 +1,23 @@ +import {render, type TemplateResult} from "lit"; + +/** Render a Lit template into document.body and wait for the first element to settle. */ +export async function mount(template: TemplateResult): Promise { + const host = document.createElement("div"); + document.body.append(host); + render(template, host); + const el = host.firstElementChild as T & {updateComplete?: Promise}; + await el.updateComplete; + return el; +} + +export function all(el: Element, selector: string): E[] { + return [...(el.shadowRoot as ShadowRoot).querySelectorAll(selector)]; +} + +export function one(el: Element, selector: string): E | null { + return (el.shadowRoot as ShadowRoot).querySelector(selector); +} + +export function nextEvent(el: EventTarget, name: string): Promise> { + return new Promise((resolve) => el.addEventListener(name, (e) => resolve(e as CustomEvent), {once: true})); +} diff --git a/custom_components/ha_controller/frontend/test/hc-grid.test.ts b/custom_components/ha_controller/frontend/test/hc-grid.test.ts new file mode 100644 index 0000000..61318b5 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hc-grid.test.ts @@ -0,0 +1,58 @@ +import {html} from "lit"; +import {afterEach, describe, expect, it} from "vitest"; +import "../src/components/hc-grid"; +import {all, mount, nextEvent, one} from "./dom"; +import {validLayouts} from "./fixtures"; + +afterEach(() => { + document.body.innerHTML = ""; +}); + +const reference = () => + mount(html``); + +describe("hc-grid", () => { + it("renders blocks, placeholders, start badge and error state", async () => { + const el = await reference(); + expect(all(el, ".block")).toHaveLength(4); + expect(all(el, ".placeholder")).toHaveLength(8); + expect(one(el, '.block[data-id="b1"] .start-badge')?.textContent).toBe("start"); + expect(one(el, '.block[data-id="b4"]')!.classList.contains("has-error")).toBe(true); + expect(one(el, '.block[data-id="b1"]')!.classList.contains("has-error")).toBe(false); + }); + + it("places cells on the grid with x right and y down", async () => { + const el = await reference(); + expect(one(el, '.block[data-id="b3"]')!.style.gridColumn).toBe("2"); + expect(one(el, '.block[data-id="b3"]')!.style.gridRow).toBe("3"); + }); + + it("marks the selected block and colours its text", async () => { + const layout = validLayouts.reference; + const el = await mount(html`()}>`); + expect(one(el, '.block[data-id="b2"]')!.classList.contains("selected")).toBe(true); + expect(all(el, ".block.selected")).toHaveLength(1); + const block = layout.blocks[0]; + const node = one(el, `.block[data-id="${block.id}"]`)!; + expect(node.style.background).not.toBe(""); + expect(["#000000", "#ffffff", "rgb(0, 0, 0)", "rgb(255, 255, 255)"]).toContain(node.style.color.toLowerCase()); + }); + + it("emits hc-add-block from a placeholder", async () => { + const el = await reference(); + const added = nextEvent<{x: number; y: number}>(el, "hc-add-block"); + one(el, '.placeholder[data-x="1"][data-y="0"]')!.click(); + const event = await added; + expect(event.detail).toEqual({x: 1, y: 0}); + expect(event.bubbles && event.composed).toBe(true); + }); + + it("emits hc-select-block from a block", async () => { + const el = await reference(); + const selected = nextEvent<{id: string}>(el, "hc-select-block"); + one(el, '.block[data-id="b3"]')!.click(); + const event = await selected; + expect(event.detail).toEqual({id: "b3"}); + expect(event.bubbles && event.composed).toBe(true); + }); +}); From 0fa933de1a0414d06f89c8d2381f60a30eefa0ca Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:45:55 +0100 Subject: [PATCH 23/49] fix(panel): guard element definition and keep grid states visible Co-Authored-By: Claude Sonnet 5.5 --- .../frontend/src/components/hc-grid.ts | 38 +++++++++++++------ .../ha_controller/frontend/src/define.ts | 4 ++ .../ha_controller/frontend/test/dom.ts | 4 ++ .../frontend/test/hc-grid.test.ts | 36 ++++++++++++++++-- 4 files changed, 67 insertions(+), 15 deletions(-) create mode 100644 custom_components/ha_controller/frontend/src/define.ts diff --git a/custom_components/ha_controller/frontend/src/components/hc-grid.ts b/custom_components/ha_controller/frontend/src/components/hc-grid.ts index 6a39956..39c4516 100644 --- a/custom_components/ha_controller/frontend/src/components/hc-grid.ts +++ b/custom_components/ha_controller/frontend/src/components/hc-grid.ts @@ -1,11 +1,11 @@ import {LitElement, css, html, nothing} from "lit"; -import {customElement, property} from "lit/decorators.js"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; import {gridBounds, placeholders} from "../model/grid"; import {textColorFor} from "../model/color"; import type {Layout} from "../types"; /** Block map: x grows to the right, y grows downwards, like navigation on the screen. */ -@customElement("hc-grid") export class HcGrid extends LitElement { @property({attribute: false}) layout: Layout = {version: 1, start: null, settings: {sleep_timeout: 0}, blocks: []}; @property({attribute: false}) selectedId: string | null = null; @@ -40,20 +40,34 @@ export class HcGrid extends LitElement { overflow: hidden; overflow-wrap: anywhere; } - button:focus-visible { - box-shadow: 0 0 0 3px var(--primary-color, #03a9f4); + /* Cues are layered box-shadows (start inset, selection, error), so they combine. Focus uses + outline, which no state touches, and sits outside the rings. */ + .block { + --ring-start: 0 0 0 0 transparent; + --ring-select: 0 0 0 0 transparent; + --ring-error: 0 0 0 0 transparent; + box-shadow: var(--ring-select), var(--ring-error), var(--ring-start); } .block.start { - outline: 3px solid var(--primary-text-color, #212121); - outline-offset: -3px; + --ring-start: inset 0 0 0 3px var(--primary-text-color, #212121); + } + .block.has-error { + --ring-error: 0 0 0 3px var(--error-color, #db4437); } .block.selected { - box-shadow: 0 0 0 3px var(--card-background-color, #fff), 0 0 0 6px var(--primary-color, #03a9f4); - overflow: visible; + --ring-select: 0 0 0 3px var(--primary-color, #03a9f4); } - .block.has-error { - box-shadow: 0 0 0 3px var(--card-background-color, #fff), 0 0 0 6px var(--error-color, #db4437); - overflow: visible; + .block.selected.has-error { + --ring-select: 0 0 0 3px var(--primary-color, #03a9f4); + --ring-error: 0 0 0 6px var(--error-color, #db4437); + } + button:focus-visible { + outline: 2px solid var(--primary-text-color, #212121); + outline-offset: 3px; + } + .block.selected:focus-visible, + .block.has-error:focus-visible { + outline-offset: 8px; } .start-badge { position: absolute; @@ -112,6 +126,8 @@ export class HcGrid extends LitElement { } } +defineElement("hc-grid", HcGrid); + declare global { interface HTMLElementTagNameMap { "hc-grid": HcGrid; diff --git a/custom_components/ha_controller/frontend/src/define.ts b/custom_components/ha_controller/frontend/src/define.ts new file mode 100644 index 0000000..a754845 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/define.ts @@ -0,0 +1,4 @@ +/** Register a custom element once; safe when a module is evaluated twice (HMR, duplicate bundle). */ +export function defineElement(name: string, ctor: CustomElementConstructor): void { + if (customElements.get(name) === undefined) customElements.define(name, ctor); +} diff --git a/custom_components/ha_controller/frontend/test/dom.ts b/custom_components/ha_controller/frontend/test/dom.ts index 4e7d782..91516b3 100644 --- a/custom_components/ha_controller/frontend/test/dom.ts +++ b/custom_components/ha_controller/frontend/test/dom.ts @@ -21,3 +21,7 @@ export function one(el: Element, selector: stri export function nextEvent(el: EventTarget, name: string): Promise> { return new Promise((resolve) => el.addEventListener(name, (e) => resolve(e as CustomEvent), {once: true})); } + +export function cleanup(): void { + document.body.innerHTML = ""; +} diff --git a/custom_components/ha_controller/frontend/test/hc-grid.test.ts b/custom_components/ha_controller/frontend/test/hc-grid.test.ts index 61318b5..db8d454 100644 --- a/custom_components/ha_controller/frontend/test/hc-grid.test.ts +++ b/custom_components/ha_controller/frontend/test/hc-grid.test.ts @@ -1,12 +1,11 @@ import {html} from "lit"; import {afterEach, describe, expect, it} from "vitest"; import "../src/components/hc-grid"; -import {all, mount, nextEvent, one} from "./dom"; +import {all, cleanup, mount, nextEvent, one} from "./dom"; +import {defineElement} from "../src/define"; import {validLayouts} from "./fixtures"; -afterEach(() => { - document.body.innerHTML = ""; -}); +afterEach(cleanup); const reference = () => mount(html``); @@ -17,6 +16,10 @@ describe("hc-grid", () => { expect(all(el, ".block")).toHaveLength(4); expect(all(el, ".placeholder")).toHaveLength(8); expect(one(el, '.block[data-id="b1"] .start-badge')?.textContent).toBe("start"); + expect(all(el, ".start-badge")).toHaveLength(1); + expect(one(el, '.block[data-id="b1"]')!.classList.contains("start")).toBe(true); + expect(one(el, '.block[data-id="b1"] .start-badge')).not.toBeNull(); + expect(all(el, ".block.start")).toHaveLength(1); expect(one(el, '.block[data-id="b4"]')!.classList.contains("has-error")).toBe(true); expect(one(el, '.block[data-id="b1"]')!.classList.contains("has-error")).toBe(false); }); @@ -55,4 +58,29 @@ describe("hc-grid", () => { expect(event.detail).toEqual({id: "b3"}); expect(event.bubbles && event.composed).toBe(true); }); + + it("can show selected and has-error on the same block", async () => { + const el = await mount(html``); + const node = one(el, '.block[data-id="b4"]')!; + expect(node.classList.contains("selected") && node.classList.contains("has-error")).toBe(true); + }); + + it("renders a single origin placeholder for an empty layout", async () => { + const empty = {version: 1 as const, start: null, settings: {sleep_timeout: 0}, blocks: []}; + const el = await mount(html``); + const ph = all(el, ".placeholder"); + expect(ph).toHaveLength(1); + expect(ph[0].dataset.x).toBe("0"); + expect(ph[0].dataset.y).toBe("0"); + }); +}); + +describe("defineElement", () => { + it("does not throw when the same name is defined twice", () => { + class Dummy extends HTMLElement {} + expect(() => { + defineElement("hc-define-test", Dummy); + defineElement("hc-define-test", Dummy); + }).not.toThrow(); + }); }); From 239428dd49fc4f4421a822aabee80efcc4447329 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:48:46 +0100 Subject: [PATCH 24/49] feat(panel): add block and item editors Co-Authored-By: Claude Sonnet 5.5 --- .../src/components/hc-block-editor.ts | 265 ++++++++++++++++++ .../src/components/hc-emoji-picker.ts | 61 ++++ .../src/components/hc-entity-input.ts | 63 +++++ .../frontend/src/components/hc-item-editor.ts | 155 ++++++++++ .../frontend/src/components/hc-preview.ts | 80 ++++++ .../ha_controller/frontend/src/messages.ts | 31 ++ .../ha_controller/frontend/test/hass.ts | 20 ++ .../frontend/test/hc-block-editor.test.ts | 143 ++++++++++ .../frontend/test/hc-item-editor.test.ts | 96 +++++++ 9 files changed, 914 insertions(+) create mode 100644 custom_components/ha_controller/frontend/src/components/hc-block-editor.ts create mode 100644 custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts create mode 100644 custom_components/ha_controller/frontend/src/components/hc-entity-input.ts create mode 100644 custom_components/ha_controller/frontend/src/components/hc-item-editor.ts create mode 100644 custom_components/ha_controller/frontend/src/components/hc-preview.ts create mode 100644 custom_components/ha_controller/frontend/src/messages.ts create mode 100644 custom_components/ha_controller/frontend/test/hass.ts create mode 100644 custom_components/ha_controller/frontend/test/hc-block-editor.test.ts create mode 100644 custom_components/ha_controller/frontend/test/hc-item-editor.test.ts diff --git a/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts new file mode 100644 index 0000000..ee1a4d5 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts @@ -0,0 +1,265 @@ +import {LitElement, css, html, nothing} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import "./hc-entity-input"; +import "./hc-item-editor"; +import "./hc-preview"; +import {deleteReason} from "../messages"; +import {canDelete} from "../model/grid"; +import { + PALETTE, addItem, deleteBlock, moveItem, removeItem, setStart, updateBlock, updateItem, +} from "../model/edit"; +import {MAX_ITEMS} from "../model/limits"; +import type {Block, FontSize, Hass, Item, ItemKind, Layout} from "../types"; + +const FONT_SIZES: [FontSize, string][] = [["s", "S"], ["m", "M"], ["l", "L"], ["xl", "XL"]]; +const ITEM_KINDS: [ItemKind, string][] = [ + ["text", "Text"], + ["emoji", "Emoji"], + ["entity", "Entity state"], + ["battery", "Battery"], + ["brightness", "Screen brightness"], +]; + +/** Editor for the selected block. Emits `hc-layout-change` with the complete new layout. */ +export class HcBlockEditor extends LitElement { + @property({attribute: false}) hass?: Hass; + @property({attribute: false}) layout!: Layout; + @property() blockId = ""; + + static styles = css` + :host { + display: block; + color: var(--primary-text-color, #212121); + } + .form { + display: grid; + gap: 12px; + } + label, + .label { + display: block; + font-size: 12px; + color: var(--secondary-text-color, #727272); + margin-bottom: 4px; + } + input[type="text"], + select { + box-sizing: border-box; + width: 100%; + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + .row { + display: flex; + gap: 6px; + align-items: center; + flex-wrap: wrap; + } + button.swatch { + width: 28px; + height: 28px; + border-radius: 50%; + border: 2px solid transparent; + cursor: pointer; + padding: 0; + } + button.swatch[aria-pressed="true"] { + border-color: var(--primary-text-color, #212121); + } + button.font-size { + min-width: 36px; + padding: 4px 8px; + cursor: pointer; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + button.font-size[aria-pressed="true"] { + border-color: var(--primary-color, #03a9f4); + box-shadow: 0 0 0 1px var(--primary-color, #03a9f4); + } + input[type="color"] { + width: 36px; + height: 28px; + padding: 0; + } + .items { + display: grid; + gap: 8px; + } + .reason { + font-size: 12px; + color: var(--error-color, #db4437); + } + button.delete:not([disabled]) { + color: var(--error-color, #db4437); + } + `; + + private get block(): Block | undefined { + return this.layout?.blocks.find((b) => b.id === this.blockId); + } + + render() { + const block = this.block; + if (!block) return nothing; + const check = canDelete(this.layout, block.id); + const isStart = this.layout.start === block.id; + return html`
    +
    + + +
    +
    + Background +
    + ${PALETTE.map( + (colour) => html``, + )} + + this.change(updateBlock(this.layout, block.id, {background: (e.target as HTMLInputElement).value.toUpperCase()}))} + /> +
    +
    +
    + Font size +
    + ${FONT_SIZES.map( + ([size, label]) => html``, + )} +
    +
    +
    + + +
    + ${block.type === "entity" ? this.entityFields(block) : this.customFields(block)} +
    + + +
    + ${check.ok ? nothing : html`
    ${deleteReason[check.reason]}
    `} + +
    `; + } + + protected updated(): void { + const select = this.renderRoot.querySelector("select[name=type]"); + if (select && this.block) select.value = this.block.type; + } + + private entityFields(block: Block) { + return html`
    + Entity + ) => { + e.stopPropagation(); + this.change(updateBlock(this.layout, block.id, {entity_id: e.detail.value})); + }} + > +
    `; + } + + private customFields(block: Block) { + const items = block.items ?? []; + return html`
    + ${items.map( + (item, index) => html`}>) => { + e.stopPropagation(); + this.change(updateItem(this.layout, block.id, item.id, e.detail.patch)); + }} + @hc-item-move=${(e: CustomEvent<{delta: -1 | 1}>) => { + e.stopPropagation(); + this.change(moveItem(this.layout, block.id, item.id, e.detail.delta)); + }} + @hc-item-remove=${(e: Event) => { + e.stopPropagation(); + this.change(removeItem(this.layout, block.id, item.id)); + }} + >`, + )} +
    + + +
    +
    `; + } + + private onName = (e: Event): void => { + const block = this.block; + if (block) this.change(updateBlock(this.layout, block.id, {name: (e.target as HTMLInputElement).value})); + }; + + private onType = (e: Event): void => { + const block = this.block; + if (!block) return; + const type = (e.target as HTMLSelectElement).value as Block["type"]; + if (type === block.type) return; + this.change(updateBlock(this.layout, block.id, type === "custom" ? {type, items: block.items ?? []} : {type})); + }; + + private onAddItem = (e: Event): void => { + const select = e.target as HTMLSelectElement; + const block = this.block; + if (!block || select.value === "") return; + const kind = select.value as ItemKind; + select.value = ""; + this.change(addItem(this.layout, block.id, kind).layout); + }; + + private change(layout: Layout): void { + this.dispatchEvent(new CustomEvent("hc-layout-change", {detail: {layout}, bubbles: true, composed: true})); + } +} + +defineElement("hc-block-editor", HcBlockEditor); + +declare global { + interface HTMLElementTagNameMap { + "hc-block-editor": HcBlockEditor; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts b/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts new file mode 100644 index 0000000..b14cbfa --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts @@ -0,0 +1,61 @@ +import {LitElement, css, html} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import {SUPPORTED_EMOJI, normalizeEmoji} from "../model/emoji"; + +/** Grid of the emoji the screen can render. */ +export class HcEmojiPicker extends LitElement { + @property() value = ""; + + static styles = css` + :host { + display: block; + } + .grid { + display: grid; + grid-template-columns: repeat(8, 1fr); + gap: 4px; + } + button { + font-size: 20px; + padding: 4px; + cursor: pointer; + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + button[aria-pressed="true"] { + border-color: var(--primary-color, #03a9f4); + box-shadow: 0 0 0 2px var(--primary-color, #03a9f4); + } + `; + + render() { + const current = normalizeEmoji(this.value ?? ""); + return html`
    + ${SUPPORTED_EMOJI.map( + (e) => html``, + )} +
    `; + } + + private emit(value: string): void { + this.dispatchEvent( + new CustomEvent("hc-value-change", {detail: {value: normalizeEmoji(value)}, bubbles: true, composed: true}), + ); + } +} + +defineElement("hc-emoji-picker", HcEmojiPicker); + +declare global { + interface HTMLElementTagNameMap { + "hc-emoji-picker": HcEmojiPicker; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-entity-input.ts b/custom_components/ha_controller/frontend/src/components/hc-entity-input.ts new file mode 100644 index 0000000..8d5d3d5 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-entity-input.ts @@ -0,0 +1,63 @@ +import {LitElement, css, html} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import type {Hass} from "../types"; + +let counter = 0; + +/** Entity picker built from `hass.states`: a text input with a datalist of matching ids. */ +export class HcEntityInput extends LitElement { + @property({attribute: false}) hass?: Hass; + @property() value = ""; + @property({attribute: false}) domains?: string[]; + + private readonly listId = `entities-${counter++}`; + + static styles = css` + :host { + display: block; + } + input { + box-sizing: border-box; + width: 100%; + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + `; + + render() { + const ids = Object.keys(this.hass?.states ?? {}) + .filter((id) => !this.domains || this.domains.includes(id.split(".")[0])) + .sort(); + return html` this.emit((e.target as HTMLInputElement).value.trim())} + /> + + ${ids.map((id) => { + const name = this.hass?.states[id]?.attributes.friendly_name; + return html``; + })} + `; + } + + private emit(value: string): void { + this.dispatchEvent(new CustomEvent("hc-value-change", {detail: {value}, bubbles: true, composed: true})); + } +} + +defineElement("hc-entity-input", HcEntityInput); + +declare global { + interface HTMLElementTagNameMap { + "hc-entity-input": HcEntityInput; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-item-editor.ts b/custom_components/ha_controller/frontend/src/components/hc-item-editor.ts new file mode 100644 index 0000000..bf35e5d --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-item-editor.ts @@ -0,0 +1,155 @@ +import {LitElement, css, html, nothing} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import "./hc-entity-input"; +import "./hc-emoji-picker"; +import type {FontSize, Hass, Item} from "../types"; + +const KIND_LABEL: Record = { + text: "Text", + emoji: "Emoji", + entity: "Entity state", + battery: "Battery", + brightness: "Screen brightness", +}; + +/** Editor for one item of a custom block. */ +export class HcItemEditor extends LitElement { + @property({attribute: false}) hass?: Hass; + @property({attribute: false}) item!: Item; + @property({type: Number}) index = 0; + @property({type: Number}) count = 0; + + static styles = css` + :host { + display: block; + } + .item { + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 8px; + padding: 8px; + display: grid; + gap: 8px; + background: var(--card-background-color, #fff); + color: var(--primary-text-color, #212121); + } + .head, + .actions { + display: flex; + gap: 6px; + align-items: center; + } + .head strong { + flex: 1; + } + input[type="text"] { + box-sizing: border-box; + width: 100%; + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + label { + font-size: 12px; + color: var(--secondary-text-color, #727272); + } + button.remove { + color: var(--error-color, #db4437); + } + `; + + render() { + const item = this.item; + return html`
    +
    + ${KIND_LABEL[item.kind]} + + + +
    + ${this.fields(item)} +
    + + +
    +
    `; + } + + protected updated(): void { + const select = this.renderRoot.querySelector("select[name=font-size]"); + if (select) select.value = this.item.font_size ?? ""; + } + + private fields(item: Item) { + switch (item.kind) { + case "text": + return html` this.patch({text: (e.target as HTMLInputElement).value})} + />`; + case "emoji": + return html`) => { + e.stopPropagation(); + this.patch({emoji: e.detail.value}); + }} + >`; + case "entity": + return html`) => { + e.stopPropagation(); + this.patch({entity_id: e.detail.value}); + }} + > + this.patch({attribute: (e.target as HTMLInputElement).value || null})} + />`; + default: + return nothing; + } + } + + private onFontSize = (e: Event): void => { + const value = (e.target as HTMLSelectElement).value; + this.patch({font_size: value === "" ? null : (value as FontSize)}); + }; + + private patch(patch: Partial): void { + this.emit("hc-item-change", {patch}); + } + + private move(delta: -1 | 1): void { + this.emit("hc-item-move", {delta}); + } + + private emit(name: string, detail?: unknown): void { + this.dispatchEvent(new CustomEvent(name, {detail, bubbles: true, composed: true})); + } +} + +defineElement("hc-item-editor", HcItemEditor); + +declare global { + interface HTMLElementTagNameMap { + "hc-item-editor": HcItemEditor; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-preview.ts b/custom_components/ha_controller/frontend/src/components/hc-preview.ts new file mode 100644 index 0000000..4eecd16 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-preview.ts @@ -0,0 +1,80 @@ +import {LitElement, css, html} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import {textColorFor} from "../model/color"; +import type {Block, Hass, Item} from "../types"; + +const SIZES: Record = {s: "11px", m: "14px", l: "18px", xl: "24px"}; + +/** Round preview of a block, approximating the screen. */ +export class HcPreview extends LitElement { + @property({attribute: false}) block?: Block; + @property({attribute: false}) hass?: Hass; + + static styles = css` + :host { + display: block; + } + .circle { + box-sizing: border-box; + width: 220px; + height: 220px; + border-radius: 50%; + margin: 0 auto; + padding: 32px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + overflow: hidden; + overflow-wrap: anywhere; + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + } + .name { + font-weight: 600; + } + `; + + private stateOf(entityId: string | undefined, attribute?: string | null): string { + const entity = entityId ? this.hass?.states[entityId] : undefined; + if (!entity) return "unavailable"; + if (attribute) return String(entity.attributes[attribute] ?? ""); + const unit = entity.attributes.unit_of_measurement; + return typeof unit === "string" ? `${entity.state} ${unit}` : entity.state; + } + + private line(block: Block, item: Item) { + let text = ""; + switch (item.kind) { + case "text": text = item.text ?? ""; break; + case "emoji": text = item.emoji ?? ""; break; + case "entity": text = this.stateOf(item.entity_id, item.attribute); break; + case "battery": text = "Battery"; break; + case "brightness": text = "Brightness"; break; + } + return html`
    ${text}
    `; + } + + render() { + const block = this.block; + if (!block) return html``; + return html`
    +
    ${block.name}
    + ${block.type === "entity" + ? html`
    ${this.stateOf(block.entity_id)}
    ` + : (block.items ?? []).map((item) => this.line(block, item))} +
    `; + } +} + +defineElement("hc-preview", HcPreview); + +declare global { + interface HTMLElementTagNameMap { + "hc-preview": HcPreview; + } +} diff --git a/custom_components/ha_controller/frontend/src/messages.ts b/custom_components/ha_controller/frontend/src/messages.ts new file mode 100644 index 0000000..26d8c98 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/messages.ts @@ -0,0 +1,31 @@ +/** English UI strings for validation error codes and delete refusals. */ +const ERRORS: Record = { + invalid_structure: "The layout is malformed.", + too_many_blocks: "A screen holds at most 32 blocks.", + invalid_id: "Invalid identifier.", + duplicate_id: "Duplicate identifier.", + coordinate_out_of_range: "This block is too far from the centre of the map.", + duplicate_position: "Two blocks share the same cell.", + invalid_start: "Choose a start block.", + disconnected: "This block can't be reached from the start block.", + invalid_name: "Names need 1 to 32 characters.", + invalid_background: "Pick a background colour.", + invalid_font_size: "Pick a font size.", + invalid_type: "Pick a block type.", + invalid_entity: "Pick a valid entity.", + too_many_items: "A custom block holds at most 6 items.", + invalid_item: "Unknown item type.", + invalid_text: "Text needs 1 to 64 characters.", + unsupported_emoji: "This emoji is not available on the screen.", + payload_too_large: "The layout is too large for the screen. Remove blocks or shorten texts.", + invalid_sleep_timeout: "The sleep delay must be 0 (never) or between 5 and 3600 seconds.", +}; + +export function errorMessage(code: string): string { + return ERRORS[code] ?? "Invalid layout."; +} + +export const deleteReason: Record<"start" | "disconnects", string> = { + start: "Choose another start block first.", + disconnects: "Other blocks would become unreachable.", +}; diff --git a/custom_components/ha_controller/frontend/test/hass.ts b/custom_components/ha_controller/frontend/test/hass.ts new file mode 100644 index 0000000..9cd5fb6 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hass.ts @@ -0,0 +1,20 @@ +import type {Hass, HassEntity} from "../src/types"; + +const entity = (entity_id: string, state: string, friendly_name: string, extra: Record = {}): HassEntity => ({ + entity_id, + state, + attributes: {friendly_name, ...extra}, +}); + +/** Minimal fake `hass` for component tests. */ +export function fakeHass(): Hass { + const states = Object.fromEntries( + [ + entity("light.kitchen", "on", "Kitchen"), + entity("light.living_room", "off", "Living room"), + entity("climate.bedroom", "heat", "Bedroom"), + entity("sensor.outdoor_temperature", "21.5", "Outdoor temperature", {unit_of_measurement: "°C"}), + ].map((e) => [e.entity_id, e]), + ); + return {states, callWS: () => Promise.reject(new Error("not available in tests"))}; +} diff --git a/custom_components/ha_controller/frontend/test/hc-block-editor.test.ts b/custom_components/ha_controller/frontend/test/hc-block-editor.test.ts new file mode 100644 index 0000000..3ab01bf --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hc-block-editor.test.ts @@ -0,0 +1,143 @@ +import {html} from "lit"; +import {afterEach, describe, expect, it} from "vitest"; +import "../src/components/hc-block-editor"; +import {all, cleanup, mount, nextEvent, one} from "./dom"; +import {validLayouts} from "./fixtures"; +import {fakeHass} from "./hass"; +import type {Layout} from "../src/types"; + +afterEach(cleanup); + +const hass = fakeHass(); +const editor = (blockId: string, layout: Layout = validLayouts.reference) => + mount(html``); + +function type(input: HTMLInputElement, value: string): void { + input.value = value; + input.dispatchEvent(new Event("input", {bubbles: true})); + input.dispatchEvent(new Event("change", {bubbles: true})); +} + +describe("hc-block-editor", () => { + it("emits the new layout when the name changes, without mutating the property", async () => { + const el = await editor("b1"); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + type(one(el, "input[name=name]")!, "Kitchen 2"); + expect((await changed).detail.layout.blocks[0].name).toBe("Kitchen 2"); + expect(validLayouts.reference.blocks[0].name).toBe("Kitchen"); + }); + + it("offers matching entities in the entity input", async () => { + const el = await editor("b1"); + const input = one(el, "hc-entity-input")!; + await (input as unknown as {updateComplete: Promise}).updateComplete; + const values = all(input, "datalist option").map((o) => o.value); + expect(values).toEqual(["climate.bedroom", "light.kitchen", "light.living_room"]); + }); + + it("changes the entity", async () => { + const el = await editor("b1"); + const input = one(el, "hc-entity-input")!; + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + type(one(input, "input")!, "light.living_room"); + expect((await changed).detail.layout.blocks[0].entity_id).toBe("light.living_room"); + }); + + it("changes the background from a swatch and the font size", async () => { + const el = await editor("b1"); + expect(all(el, "button.swatch")).toHaveLength(8); + let changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + all(el, "button.swatch")[1].click(); + expect((await changed).detail.layout.blocks[0].background).toBe("#4F86DD"); + changed = nextEvent(el, "hc-layout-change"); + all(el, "button.font-size").find((b) => b.textContent!.trim() === "XL")!.click(); + expect((await changed).detail.layout.blocks[0].font_size).toBe("xl"); + }); + + it("switches to Custom keeping the entity and adding items", async () => { + const el = await editor("b1"); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + const select = one(el, "select[name=type]")!; + select.value = "custom"; + select.dispatchEvent(new Event("change", {bubbles: true})); + const block = (await changed).detail.layout.blocks[0]; + expect(block.type).toBe("custom"); + expect(block.entity_id).toBe("light.kitchen"); + expect(block.items).toEqual([]); + }); + + it("switches back to Entity keeping the items", async () => { + const el = await editor("b3"); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + const select = one(el, "select[name=type]")!; + select.value = "entity"; + select.dispatchEvent(new Event("change", {bubbles: true})); + const block = (await changed).detail.layout.blocks[2]; + expect(block.type).toBe("entity"); + expect(block.items).toHaveLength(5); + }); + + it("lists items of a custom block and adds an item", async () => { + const el = await editor("b3"); + expect(all(el, "hc-item-editor")).toHaveLength(5); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + const select = one(el, "select[name=add-item]")!; + select.value = "battery"; + select.dispatchEvent(new Event("change", {bubbles: true})); + const items = (await changed).detail.layout.blocks[2].items!; + expect(items).toHaveLength(6); + expect(items[5].kind).toBe("battery"); + }); + + it("applies item events to the layout", async () => { + const el = await editor("b3"); + const editors = all(el, "hc-item-editor"); + let changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + editors[0].dispatchEvent(new CustomEvent("hc-item-change", {detail: {patch: {text: "Hi"}}, bubbles: true, composed: true})); + expect((await changed).detail.layout.blocks[2].items![0].text).toBe("Hi"); + changed = nextEvent(el, "hc-layout-change"); + editors[0].dispatchEvent(new CustomEvent("hc-item-move", {detail: {delta: 1}, bubbles: true, composed: true})); + expect((await changed).detail.layout.blocks[2].items![1].id).toBe("i1"); + changed = nextEvent(el, "hc-layout-change"); + editors[1].dispatchEvent(new CustomEvent("hc-item-remove", {bubbles: true, composed: true})); + expect((await changed).detail.layout.blocks[2].items).toHaveLength(4); + }); + + it("disables start and delete for the start block and explains why", async () => { + const el = await editor("b1"); + expect(one(el, "button.start")!.hasAttribute("disabled")).toBe(true); + expect(one(el, "button.delete")!.hasAttribute("disabled")).toBe(true); + expect(el.shadowRoot!.textContent).toContain("Choose another start block first."); + }); + + it("explains a delete that would disconnect blocks", async () => { + const layout: Layout = { + ...validLayouts.reference, + blocks: [ + {id: "b1", x: 0, y: 0, name: "A", background: "#C94F3D", font_size: "m", type: "custom", items: []}, + {id: "b2", x: 1, y: 0, name: "B", background: "#4F86DD", font_size: "m", type: "custom", items: []}, + {id: "b3", x: 2, y: 0, name: "C", background: "#5B9E4D", font_size: "m", type: "custom", items: []}, + ], + }; + const el = await editor("b2", layout); + expect(one(el, "button.delete")!.hasAttribute("disabled")).toBe(true); + expect(el.shadowRoot!.textContent).toContain("Other blocks would become unreachable."); + }); + + it("sets the start block and deletes a leaf block", async () => { + let el = await editor("b2"); + expect(one(el, "button.start")!.hasAttribute("disabled")).toBe(false); + let changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + one(el, "button.start")!.click(); + expect((await changed).detail.layout.start).toBe("b2"); + el = await editor("b2"); + changed = nextEvent(el, "hc-layout-change"); + one(el, "button.delete")!.click(); + expect((await changed).detail.layout.blocks.map((b) => b.id)).toEqual(["b1", "b3", "b4"]); + }); + + it("renders a preview", async () => { + const el = await editor("b1"); + expect(one(el, "hc-preview")).not.toBeNull(); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/hc-item-editor.test.ts b/custom_components/ha_controller/frontend/test/hc-item-editor.test.ts new file mode 100644 index 0000000..f592683 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hc-item-editor.test.ts @@ -0,0 +1,96 @@ +import {html} from "lit"; +import {afterEach, describe, expect, it} from "vitest"; +import "../src/components/hc-item-editor"; +import "../src/components/hc-emoji-picker"; +import "../src/components/hc-preview"; +import {all, cleanup, mount, nextEvent, one} from "./dom"; +import {fakeHass} from "./hass"; +import {validLayouts} from "./fixtures"; +import type {Item} from "../src/types"; + +afterEach(cleanup); + +const hass = fakeHass(); +const items = validLayouts.reference.blocks[2].items as Item[]; +const item = (i: number) => + mount(html``); + +describe("hc-item-editor", () => { + it("emits a text patch", async () => { + const el = await item(0); + const input = one(el, "input[name=text]")!; + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + input.value = "Hi"; + input.dispatchEvent(new Event("input", {bubbles: true})); + expect((await changed).detail.patch).toEqual({text: "Hi"}); + }); + + it("emits font size patches, null for inherit", async () => { + const el = await item(1); + const select = one(el, "select[name=font-size]")!; + expect(select.value).toBe("xl"); + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + select.value = ""; + select.dispatchEvent(new Event("change", {bubbles: true})); + expect((await changed).detail.patch).toEqual({font_size: null}); + }); + + it("emits move and remove, disabling impossible moves", async () => { + const el = await item(0); + expect(one(el, "button.up")!.hasAttribute("disabled")).toBe(true); + expect(one(el, "button.down")!.hasAttribute("disabled")).toBe(false); + const moved = nextEvent<{delta: number}>(el, "hc-item-move"); + one(el, "button.down")!.click(); + expect((await moved).detail.delta).toBe(1); + const removed = nextEvent(el, "hc-item-remove"); + one(el, "button.remove")!.click(); + await removed; + }); + + it("edits an entity item with attribute", async () => { + const el = await item(2); + expect(one(el, "hc-entity-input")).not.toBeNull(); + const input = one(el, "input[name=attribute]")!; + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + input.value = "unit"; + input.dispatchEvent(new Event("input", {bubbles: true})); + expect((await changed).detail.patch).toEqual({attribute: "unit"}); + }); + + it("maps the emoji picker to an emoji patch", async () => { + const el = await item(1); + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + one(el, "hc-emoji-picker")!.dispatchEvent(new CustomEvent("hc-value-change", {detail: {value: "💡"}, bubbles: true, composed: true})); + expect((await changed).detail.patch).toEqual({emoji: "💡"}); + }); + + it("has no extra fields for battery items", async () => { + const el = await item(3); + expect(one(el, "input")).toBeNull(); + }); +}); + +describe("hc-emoji-picker", () => { + it("renders 64 buttons and emits the normalised value", async () => { + const picker = await mount(html``); + const buttons = all(picker, "button.emoji"); + expect(buttons).toHaveLength(64); + const changed = nextEvent<{value: string}>(picker, "hc-value-change"); + buttons[3].click(); + expect((await changed).detail.value).toBe(buttons[3].textContent!.trim().replaceAll("️", "")); + }); +}); + +describe("hc-preview", () => { + it("shows the entity state for entity blocks", async () => { + const el = await mount(html``); + expect(el.shadowRoot!.textContent).toContain("Kitchen"); + expect(el.shadowRoot!.textContent).toContain("on"); + }); + + it("shows one line per item for custom blocks", async () => { + const el = await mount(html``); + expect(all(el, ".line")).toHaveLength(5); + expect(el.shadowRoot!.textContent).toContain("21.5"); + }); +}); From b58f9001bb7c64f16948dccff2b6589dc44b30f6 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Mon, 16 Nov 2026 21:57:47 +0100 Subject: [PATCH 25/49] refactor(panel): move editor strings into messages.ts Co-Authored-By: Claude Sonnet 5.5 --- .../src/components/hc-block-editor.ts | 51 +++++++++---------- .../src/components/hc-emoji-picker.ts | 3 +- .../src/components/hc-entity-input.ts | 5 +- .../frontend/src/components/hc-item-editor.ts | 30 ++++------- .../frontend/src/components/hc-preview.ts | 7 +-- .../ha_controller/frontend/src/messages.ts | 42 +++++++++++++++ 6 files changed, 85 insertions(+), 53 deletions(-) diff --git a/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts index ee1a4d5..3b34ce6 100644 --- a/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts +++ b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts @@ -1,25 +1,18 @@ import {LitElement, css, html, nothing} from "lit"; import {property} from "lit/decorators.js"; +import {repeat} from "lit/directives/repeat.js"; import {defineElement} from "../define"; import "./hc-entity-input"; import "./hc-item-editor"; import "./hc-preview"; -import {deleteReason} from "../messages"; +import {FONT_SIZE_LABEL, FONT_SIZE_ORDER, ITEM_KIND_LABEL, UI, deleteReason} from "../messages"; import {canDelete} from "../model/grid"; import { PALETTE, addItem, deleteBlock, moveItem, removeItem, setStart, updateBlock, updateItem, } from "../model/edit"; import {MAX_ITEMS} from "../model/limits"; -import type {Block, FontSize, Hass, Item, ItemKind, Layout} from "../types"; +import type {Block, Hass, Item, ItemKind, Layout} from "../types"; -const FONT_SIZES: [FontSize, string][] = [["s", "S"], ["m", "M"], ["l", "L"], ["xl", "XL"]]; -const ITEM_KINDS: [ItemKind, string][] = [ - ["text", "Text"], - ["emoji", "Emoji"], - ["entity", "Entity state"], - ["battery", "Battery"], - ["brightness", "Screen brightness"], -]; /** Editor for the selected block. Emits `hc-layout-change` with the complete new layout. */ export class HcBlockEditor extends LitElement { @@ -113,18 +106,18 @@ export class HcBlockEditor extends LitElement { const isStart = this.layout.start === block.id; return html`
    - +
    - Background + ${UI.background}
    ${PALETTE.map( (colour) => html``, @@ -132,7 +125,7 @@ export class HcBlockEditor extends LitElement { this.change(updateBlock(this.layout, block.id, {background: (e.target as HTMLInputElement).value.toUpperCase()}))} @@ -140,36 +133,36 @@ export class HcBlockEditor extends LitElement {
    - Font size + ${UI.fontSize}
    - ${FONT_SIZES.map( - ([size, label]) => html``, + >${FONT_SIZE_LABEL[size]}`, )}
    - +
    ${block.type === "entity" ? this.entityFields(block) : this.customFields(block)}
    + >${UI.deleteBlock}
    ${check.ok ? nothing : html`
    ${deleteReason[check.reason]}
    `} @@ -183,7 +176,7 @@ export class HcBlockEditor extends LitElement { private entityFields(block: Block) { return html`
    - Entity + ${UI.entity} - ${items.map( + ${repeat( + items, + (item) => item.id, (item, index) => html``, )}
    - +
    `; diff --git a/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts b/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts index b14cbfa..c7dc744 100644 --- a/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts +++ b/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts @@ -1,6 +1,7 @@ import {LitElement, css, html} from "lit"; import {property} from "lit/decorators.js"; import {defineElement} from "../define"; +import {UI} from "../messages"; import {SUPPORTED_EMOJI, normalizeEmoji} from "../model/emoji"; /** Grid of the emoji the screen can render. */ @@ -32,7 +33,7 @@ export class HcEmojiPicker extends LitElement { render() { const current = normalizeEmoji(this.value ?? ""); - return html`
    + return html`
    ${SUPPORTED_EMOJI.map( (e) => html` - - + ${ITEM_KIND_LABEL[item.kind]} + + +
    ${this.fields(item)}
    - +
    `; @@ -93,7 +85,7 @@ export class HcItemEditor extends LitElement { return html` this.patch({text: (e.target as HTMLInputElement).value})} @@ -118,8 +110,8 @@ export class HcItemEditor extends LitElement { this.patch({attribute: (e.target as HTMLInputElement).value || null})} />`; diff --git a/custom_components/ha_controller/frontend/src/components/hc-preview.ts b/custom_components/ha_controller/frontend/src/components/hc-preview.ts index 4eecd16..9e9405f 100644 --- a/custom_components/ha_controller/frontend/src/components/hc-preview.ts +++ b/custom_components/ha_controller/frontend/src/components/hc-preview.ts @@ -2,6 +2,7 @@ import {LitElement, css, html} from "lit"; import {property} from "lit/decorators.js"; import {defineElement} from "../define"; import {textColorFor} from "../model/color"; +import {UI} from "../messages"; import type {Block, Hass, Item} from "../types"; const SIZES: Record = {s: "11px", m: "14px", l: "18px", xl: "24px"}; @@ -38,7 +39,7 @@ export class HcPreview extends LitElement { private stateOf(entityId: string | undefined, attribute?: string | null): string { const entity = entityId ? this.hass?.states[entityId] : undefined; - if (!entity) return "unavailable"; + if (!entity) return UI.unavailable; if (attribute) return String(entity.attributes[attribute] ?? ""); const unit = entity.attributes.unit_of_measurement; return typeof unit === "string" ? `${entity.state} ${unit}` : entity.state; @@ -50,8 +51,8 @@ export class HcPreview extends LitElement { case "text": text = item.text ?? ""; break; case "emoji": text = item.emoji ?? ""; break; case "entity": text = this.stateOf(item.entity_id, item.attribute); break; - case "battery": text = "Battery"; break; - case "brightness": text = "Brightness"; break; + case "battery": text = UI.previewBattery; break; + case "brightness": text = UI.previewBrightness; break; } return html`
    ${text}
    `; } diff --git a/custom_components/ha_controller/frontend/src/messages.ts b/custom_components/ha_controller/frontend/src/messages.ts index 26d8c98..fff45ef 100644 --- a/custom_components/ha_controller/frontend/src/messages.ts +++ b/custom_components/ha_controller/frontend/src/messages.ts @@ -1,3 +1,5 @@ +import type {FontSize, ItemKind} from "./types"; + /** English UI strings for validation error codes and delete refusals. */ const ERRORS: Record = { invalid_structure: "The layout is malformed.", @@ -29,3 +31,43 @@ export const deleteReason: Record<"start" | "disconnects", string> = { start: "Choose another start block first.", disconnects: "Other blocks would become unreachable.", }; + +/** Item kind labels, in the order offered by the "add item" menu. */ +export const ITEM_KIND_LABEL: Record = { + text: "Text", + emoji: "Emoji", + entity: "Entity state", + battery: "Battery", + brightness: "Screen brightness", +}; + +export const FONT_SIZE_LABEL: Record = {s: "S", m: "M", l: "L", xl: "XL"}; + +export const FONT_SIZE_ORDER: FontSize[] = ["s", "m", "l", "xl"]; + +export const UI = { + name: "Name", + background: "Background", + backgroundColour: (colour: string) => `Background ${colour}`, + customBackground: "Custom background colour", + fontSize: "Font size", + fontSizeInherit: "Inherit", + type: "Type", + typeEntity: "Entity", + typeCustom: "Custom", + entity: "Entity", + entityPlaceholder: "domain.entity", + setStart: "Set as start block", + deleteBlock: "Delete block", + addItemLabel: "Add item", + addItemPlaceholder: "Add item…", + moveUp: "Move up", + moveDown: "Move down", + removeItem: "Remove item", + text: "Text", + attributeOptional: "Attribute (optional)", + emoji: "Emoji", + unavailable: "unavailable", + previewBattery: "Battery", + previewBrightness: "Brightness", +}; From b0a6b8a73eeb2c2c112471787df34164d645afd8 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Tue, 17 Nov 2026 05:33:22 +0100 Subject: [PATCH 26/49] feat(panel): add panel root with save, status and dev harness Co-Authored-By: Claude Sonnet 5.5 --- .claude/CLAUDE.md | 1 + .../ha_controller/frontend/dev/index.html | 25 ++ .../ha_controller/frontend/dev/mock-hass.ts | 51 +++ .../ha_controller/frontend/src/api.ts | 19 + .../frontend/src/components/hc-grid.ts | 3 +- .../frontend/src/ha-controller-panel.ts | 375 ++++++++++++++++++ .../ha_controller/frontend/src/messages.ts | 20 + .../ha_controller/frontend/src/types.ts | 14 +- .../ha_controller/frontend/test/panel.test.ts | 185 +++++++++ docs/README.md | 1 + docs/configuration.md | 52 +++ docs/development.md | 11 +- 12 files changed, 748 insertions(+), 9 deletions(-) create mode 100644 custom_components/ha_controller/frontend/dev/index.html create mode 100644 custom_components/ha_controller/frontend/dev/mock-hass.ts create mode 100644 custom_components/ha_controller/frontend/src/api.ts create mode 100644 custom_components/ha_controller/frontend/src/ha-controller-panel.ts create mode 100644 custom_components/ha_controller/frontend/test/panel.test.ts create mode 100644 docs/configuration.md diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 1c280e9..07b23db 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -47,6 +47,7 @@ npm --prefix custom_components/ha_controller/frontend ci npm --prefix custom_components/ha_controller/frontend test npm --prefix custom_components/ha_controller/frontend run typecheck npm --prefix custom_components/ha_controller/frontend run build +npm --prefix custom_components/ha_controller/frontend run dev # panel against a mock hass ``` ## Skills and agents diff --git a/custom_components/ha_controller/frontend/dev/index.html b/custom_components/ha_controller/frontend/dev/index.html new file mode 100644 index 0000000..457f262 --- /dev/null +++ b/custom_components/ha_controller/frontend/dev/index.html @@ -0,0 +1,25 @@ + + + + + + HA Controller panel (mock) + + + + + + + diff --git a/custom_components/ha_controller/frontend/dev/mock-hass.ts b/custom_components/ha_controller/frontend/dev/mock-hass.ts new file mode 100644 index 0000000..5e1c907 --- /dev/null +++ b/custom_components/ha_controller/frontend/dev/mock-hass.ts @@ -0,0 +1,51 @@ +import type {Hass, HassEntity, Layout, ScreenInfo} from "../src/types"; +import reference from "../../../../docs/protocol/fixtures/layouts/valid/reference.json"; + +const entity = (entity_id: string, state: string, friendly_name: string, extra: Record = {}): HassEntity => ({ + entity_id, + state, + attributes: {friendly_name, ...extra}, +}); + +/** A `hass` with a few entities and one screen whose layout lives in memory. */ +export function createMockHass(screen: Partial = {}): Hass { + let layout = structuredClone(reference) as Layout; + let revision = 1; + const info = (): ScreenInfo => ({ + entry_id: "mock-entry", + title: "Kitchen screen", + device_id: "mock-device", + online: true, + firmware_version: "0.1.0", + integration_version: "0.1.0", + protocol_ok: true, + revision: `r${revision}`, + device_revision: `r${revision}`, + ...screen, + }); + const states = Object.fromEntries( + [ + entity("light.kitchen", "on", "Kitchen"), + entity("light.living_room", "off", "Living room"), + entity("climate.bedroom", "heat", "Bedroom"), + entity("sensor.outdoor_temperature", "21.5", "Outdoor temperature", {unit_of_measurement: "°C"}), + ].map((e) => [e.entity_id, e]), + ); + return { + states, + async callWS(msg: {type: string; [key: string]: unknown}): Promise { + switch (msg.type) { + case "ha_controller/screens": + return {screens: [info()]} as T; + case "ha_controller/layout/get": + return {layout: structuredClone(layout)} as T; + case "ha_controller/layout/save": + layout = structuredClone(msg.layout as Layout); + revision += 1; + return {revision: `r${revision}`, pushed: true} as T; + default: + throw {code: "unknown_command", message: `Unknown command ${msg.type}`}; + } + }, + }; +} diff --git a/custom_components/ha_controller/frontend/src/api.ts b/custom_components/ha_controller/frontend/src/api.ts new file mode 100644 index 0000000..e86a35b --- /dev/null +++ b/custom_components/ha_controller/frontend/src/api.ts @@ -0,0 +1,19 @@ +import type {Hass, Layout, ScreenInfo} from "./types"; + +export async function listScreens(hass: Hass): Promise { + const result = await hass.callWS<{screens: ScreenInfo[]}>({type: "ha_controller/screens"}); + return result.screens; +} + +export async function getLayout(hass: Hass, entryId: string): Promise { + const result = await hass.callWS<{layout: Layout}>({type: "ha_controller/layout/get", entry_id: entryId}); + return result.layout; +} + +export function saveLayout( + hass: Hass, + entryId: string, + layout: Layout, +): Promise<{revision: string; pushed: boolean}> { + return hass.callWS({type: "ha_controller/layout/save", entry_id: entryId, layout}); +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-grid.ts b/custom_components/ha_controller/frontend/src/components/hc-grid.ts index 39c4516..ec2fb99 100644 --- a/custom_components/ha_controller/frontend/src/components/hc-grid.ts +++ b/custom_components/ha_controller/frontend/src/components/hc-grid.ts @@ -2,6 +2,7 @@ import {LitElement, css, html, nothing} from "lit"; import {property} from "lit/decorators.js"; import {defineElement} from "../define"; import {gridBounds, placeholders} from "../model/grid"; +import {UI} from "../messages"; import {textColorFor} from "../model/color"; import type {Layout} from "../types"; @@ -114,7 +115,7 @@ export class HcGrid extends LitElement { data-x=${c.x} data-y=${c.y} style=${place(c.x, c.y)} - aria-label="Add block" + aria-label=${UI.addBlock} @click=${() => this.emit("hc-add-block", {x: c.x, y: c.y})} >+`, )} diff --git a/custom_components/ha_controller/frontend/src/ha-controller-panel.ts b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts new file mode 100644 index 0000000..784ad5c --- /dev/null +++ b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts @@ -0,0 +1,375 @@ +import {LitElement, css, html, nothing} from "lit"; +import {property, state} from "lit/decorators.js"; +import {defineElement} from "./define"; +import {getLayout, listScreens, saveLayout} from "./api"; +import "./components/hc-grid"; +import "./components/hc-block-editor"; +import {UI, errorMessage} from "./messages"; +import {addBlock, setSleepTimeout} from "./model/edit"; +import {EMOJI_SET} from "./model/emoji"; +import {validateLayout} from "./model/validate"; +import type {Hass, Layout, LayoutError, ScreenInfo} from "./types"; + +const REFRESH_MS = 10_000; + +interface Notice { + kind: "ok" | "error"; + text: string; +} + +/** Root of the sidebar panel: screen picker, status, block map, editor and save. */ +export class HaControllerPanel extends LitElement { + @property({attribute: false}) hass?: Hass; + @property({type: Boolean}) narrow = false; + @property({attribute: false}) panel?: unknown; + @property({attribute: false}) route?: unknown; + + @state() private screens: ScreenInfo[] = []; + @state() private entryId: string | null = null; + @state() private saved: Layout | null = null; + @state() private layout: Layout | null = null; + @state() private selectedId: string | null = null; + @state() private notice: Notice | null = null; + @state() private saving = false; + + private started = false; + private timer?: ReturnType; + private loadToken = 0; + + static styles = css` + :host { + display: block; + min-height: 100%; + box-sizing: border-box; + color: var(--primary-text-color, #212121); + background: var(--primary-background-color, #fafafa); + font-family: var(--paper-font-body1_-_font-family, Roboto, system-ui, sans-serif); + } + header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + padding: 12px 16px; + background: var(--app-header-background-color, var(--card-background-color, #fff)); + color: var(--app-header-text-color, var(--primary-text-color, #212121)); + border-bottom: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + } + h1 { + margin: 0; + font-size: 20px; + font-weight: 500; + } + .status { + font-size: 13px; + color: var(--secondary-text-color, #727272); + } + .actions { + display: flex; + gap: 8px; + margin-left: auto; + } + select, + input[type="number"] { + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + button.action { + font: inherit; + padding: 6px 16px; + border-radius: 6px; + cursor: pointer; + color: var(--primary-color, #03a9f4); + background: transparent; + border: 1px solid var(--primary-color, #03a9f4); + } + button.action.save { + color: var(--text-primary-color, #fff); + background: var(--primary-color, #03a9f4); + } + button.action:disabled { + opacity: 0.4; + cursor: default; + } + button.action:focus-visible { + outline: 2px solid var(--primary-text-color, #212121); + outline-offset: 2px; + } + main { + display: grid; + grid-template-columns: minmax(0, 1fr) 340px; + gap: 24px; + padding: 16px; + align-items: start; + } + main.narrow { + grid-template-columns: minmax(0, 1fr); + } + section { + margin-top: 16px; + } + h2 { + margin: 0 0 8px; + font-size: 14px; + font-weight: 500; + } + .help { + margin-top: 4px; + font-size: 12px; + color: var(--secondary-text-color, #727272); + } + .errors { + margin: 12px 0 0; + padding-left: 20px; + color: var(--error-color, #db4437); + } + .notice { + margin: 12px 16px 0; + padding: 8px 12px; + border-radius: 6px; + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + background: var(--card-background-color, #fff); + } + .notice.error { + color: var(--error-color, #db4437); + border-color: var(--error-color, #db4437); + } + .empty { + padding: 24px 16px; + color: var(--secondary-text-color, #727272); + } + `; + + connectedCallback(): void { + super.connectedCallback(); + this.timer = setInterval(() => void this.refreshScreens(), REFRESH_MS); + } + + disconnectedCallback(): void { + clearInterval(this.timer); + this.timer = undefined; + super.disconnectedCallback(); + } + + protected updated(changed: Map): void { + if (changed.has("hass") && this.hass && !this.started) { + this.started = true; + void this.init(); + } + } + + private async init(): Promise { + const hass = this.hass as Hass; + try { + this.screens = await listScreens(hass); + } catch (err) { + this.notice = {kind: "error", text: this.describe(err, UI.loadFailed)}; + return; + } + if (this.screens.length > 0) await this.selectScreen(this.screens[0].entry_id); + } + + /** Refresh the screen list only; the working layout is never touched. */ + private async refreshScreens(): Promise { + if (!this.hass) return; + try { + this.screens = await listScreens(this.hass); + } catch { + // A failed refresh keeps the previous status; the next tick tries again. + } + } + + private async selectScreen(entryId: string): Promise { + const token = ++this.loadToken; + try { + const layout = await getLayout(this.hass as Hass, entryId); + if (token !== this.loadToken) return; + this.entryId = entryId; + this.saved = layout; + this.layout = layout; + this.selectedId = layout.start ?? layout.blocks[0]?.id ?? null; + this.notice = null; + } catch (err) { + if (token !== this.loadToken) return; + this.notice = {kind: "error", text: this.describe(err, UI.loadFailed)}; + } + } + + private describe(err: unknown, fallback: string): string { + const message = (err as {message?: unknown} | null)?.message; + return typeof message === "string" && message !== "" ? message : fallback; + } + + private get errors(): LayoutError[] { + return this.layout ? validateLayout(this.layout, EMOJI_SET) : []; + } + + private get dirty(): boolean { + return JSON.stringify(this.layout) !== JSON.stringify(this.saved); + } + + private errorText(error: LayoutError): string { + const message = errorMessage(error.code); + const block = this.layout?.blocks.find((b) => b.id === error.ref); + return block ? UI.withBlock(message, block.name) : message; + } + + private setLayout(layout: Layout): void { + this.layout = layout; + this.notice = null; + if (!layout.blocks.some((b) => b.id === this.selectedId)) { + this.selectedId = layout.start ?? layout.blocks[0]?.id ?? null; + } + } + + private onAddBlock = (e: CustomEvent<{x: number; y: number}>): void => { + if (!this.layout) return; + const {layout, id} = addBlock(this.layout, e.detail); + this.setLayout(layout); + this.selectedId = id; + }; + + private onSleep = (e: Event): void => { + const input = e.target as HTMLInputElement; + if (!this.layout || input.value === "") return; + this.setLayout(setSleepTimeout(this.layout, Number(input.value))); + }; + + private onRevert = (): void => { + if (!this.saved) return; + this.setLayout(this.saved); + }; + + private onSave = async (): Promise => { + if (!this.hass || !this.entryId || !this.layout || this.saving) return; + const layout = this.layout; + this.saving = true; + try { + const result = await saveLayout(this.hass, this.entryId, layout); + this.saved = layout; + this.notice = {kind: "ok", text: result.pushed ? UI.savedPushed : UI.savedOffline}; + void this.refreshScreens(); + } catch (err) { + this.notice = {kind: "error", text: this.saveError(err, layout)}; + } finally { + this.saving = false; + } + }; + + private saveError(err: unknown, layout: Layout): string { + const {code, message} = (err ?? {}) as {code?: string; message?: string}; + if (code === "invalid_layout" && typeof message === "string") { + return message + .split(",") + .map((part) => part.trim()) + .filter((part) => part !== "") + .map((part) => { + const [errorCode, ref = ""] = part.split("@"); + const block = layout.blocks.find((b) => b.id === ref); + return block ? UI.withBlock(errorMessage(errorCode), block.name) : errorMessage(errorCode); + }) + .join(" "); + } + return this.describe(err, UI.saveFailed); + } + + private get screen(): ScreenInfo | undefined { + return this.screens.find((s) => s.entry_id === this.entryId); + } + + private statusText(): string { + const s = this.screen; + if (!s) return ""; + if (!s.online) return UI.statusOffline; + const version = s.firmware_version ?? UI.unknownVersion; + if (s.firmware_version !== s.integration_version) return UI.statusUpdateAvailable(version); + return s.revision === s.device_revision ? UI.statusInSync(version) : UI.statusSyncing(version); + } + + protected render() { + const errors = this.errors; + const canSave = this.dirty && errors.length === 0 && !this.saving; + return html` +
    + ${this.narrow ? html`` : nothing} +

    ${UI.title}

    + ${this.screens.length > 1 + ? html`` + : nothing} + ${this.statusText()} +
    + + +
    +
    + ${this.notice + ? html`
    ${this.notice.text}
    ` + : nothing} + ${this.layout ? this.renderBody(this.layout, errors) : this.renderEmpty()} + `; + } + + private renderEmpty() { + return this.started && this.screens.length === 0 && !this.notice ? html`
    ${UI.noScreens}
    ` : nothing; + } + + private renderBody(layout: Layout, errors: LayoutError[]) { + const refs = new Set(errors.map((e) => e.ref).filter((r): r is string => r !== null)); + return html`
    +
    + ) => (this.selectedId = e.detail.id)} + @hc-add-block=${this.onAddBlock} + > + ${errors.length > 0 + ? html`
      ${errors.map((e) => html`
    • ${this.errorText(e)}
    • `)}
    ` + : nothing} +
    +

    ${UI.screenSection}

    + + +
    ${UI.sleepHelp}
    +
    +
    + ) => this.setLayout(e.detail.layout)} + > +
    `; + } +} + +defineElement("ha-controller-panel", HaControllerPanel); + +declare global { + interface HTMLElementTagNameMap { + "ha-controller-panel": HaControllerPanel; + } +} diff --git a/custom_components/ha_controller/frontend/src/messages.ts b/custom_components/ha_controller/frontend/src/messages.ts index fff45ef..ab93c16 100644 --- a/custom_components/ha_controller/frontend/src/messages.ts +++ b/custom_components/ha_controller/frontend/src/messages.ts @@ -70,4 +70,24 @@ export const UI = { unavailable: "unavailable", previewBattery: "Battery", previewBrightness: "Brightness", + addBlock: "Add block", + title: "HA Controller", + screenSelect: "Screen", + revert: "Revert", + save: "Save", + noScreens: "No screens yet. Add the HA Controller integration and connect a screen.", + loadFailed: "Could not load the screens.", + saveFailed: "Could not save the layout.", + mapLabel: "Block map", + screenSection: "Screen", + sleepAfter: "Sleep after (seconds)", + sleepHelp: "0 keeps the screen on.", + statusOffline: "Offline", + statusUpdateAvailable: (version: string) => `Online · firmware ${version} — update available`, + statusInSync: (version: string) => `Online · firmware ${version} · in sync`, + statusSyncing: (version: string) => `Online · firmware ${version} · syncing…`, + unknownVersion: "unknown", + savedPushed: "Saved — sent to the screen.", + savedOffline: "Saved — the screen is offline and will update when it reconnects.", + withBlock: (message: string, blockName: string) => `${message} (${blockName})`, }; diff --git a/custom_components/ha_controller/frontend/src/types.ts b/custom_components/ha_controller/frontend/src/types.ts index 7c01e8a..d3c4c87 100644 --- a/custom_components/ha_controller/frontend/src/types.ts +++ b/custom_components/ha_controller/frontend/src/types.ts @@ -40,17 +40,17 @@ export interface Cell { y: number; } -/** Screen status as sent by the websocket API (spec section 8). */ +/** One screen as listed by `ha_controller/screens` (spec section 8). */ export interface ScreenInfo { + entry_id: string; + title: string; device_id: string; - name: string; online: boolean; firmware_version: string | null; - battery: number | null; - charging: boolean | null; - brightness: number | null; - layout: Layout; - [key: string]: unknown; + integration_version: string; + protocol_ok: boolean | null; + revision: string; + device_revision: string | null; } export interface HassEntity { diff --git a/custom_components/ha_controller/frontend/test/panel.test.ts b/custom_components/ha_controller/frontend/test/panel.test.ts new file mode 100644 index 0000000..cda4c9f --- /dev/null +++ b/custom_components/ha_controller/frontend/test/panel.test.ts @@ -0,0 +1,185 @@ +import {html} from "lit"; +import {afterEach, beforeEach, describe, expect, it, vi} from "vitest"; +import "../src/ha-controller-panel"; +import type {HaControllerPanel} from "../src/ha-controller-panel"; +import {createMockHass} from "../dev/mock-hass"; +import type {Hass, Layout, ScreenInfo} from "../src/types"; +import {all, cleanup, mount, one} from "./dom"; + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +function spied(screen: Partial = {}) { + const hass = createMockHass(screen); + const real = hass.callWS.bind(hass); + const callWS = vi.fn(real); + hass.callWS = callWS as unknown as Hass["callWS"]; + return {hass, callWS, real}; +} + +function saveCall(callWS: {mock: {calls: unknown[][]}}): {entry_id: string; layout: Layout} { + const msgs = callWS.mock.calls.map((c) => c[0] as {type: string; entry_id: string; layout: Layout}); + return msgs.find((m) => m.type === "ha_controller/layout/save")!; +} + +async function settle(el: HaControllerPanel): Promise { + for (let i = 0; i < 5; i++) { + await Promise.resolve(); + await el.updateComplete; + } +} + +async function open(hass: Hass): Promise { + const el = await mount(html``); + await settle(el); + return el; +} + +const blocks = (el: HaControllerPanel) => all(one(el, "hc-grid")!, ".block"); +const saveButton = (el: HaControllerPanel) => one(el, "button.save")!; +const click = async (el: HaControllerPanel, node: Element) => { + (node as HTMLElement).click(); + await settle(el); +}; +const addBlockRight = async (el: HaControllerPanel) => { + await click(el, one(one(el, "hc-grid")!, '.placeholder[data-x="1"][data-y="0"]')!); +}; + +describe("ha-controller-panel", () => { + it("loads the first screen and renders its map", async () => { + const {hass} = spied(); + const el = await open(hass); + expect(blocks(el)).toHaveLength(4); + }); + + it("save is disabled until something changes", async () => { + const {hass} = spied(); + const el = await open(hass); + expect(saveButton(el).disabled).toBe(true); + await addBlockRight(el); + expect(saveButton(el).disabled).toBe(false); + await click(el, one(el, "button.revert")!); + expect(blocks(el)).toHaveLength(4); + expect(saveButton(el).disabled).toBe(true); + }); + + it("adding a block and saving sends the new layout", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + await addBlockRight(el); + await click(el, saveButton(el)); + const call = saveCall(callWS); + expect(call.entry_id).toBe("mock-entry"); + expect(call.layout.blocks).toHaveLength(5); + expect(one(el, ".notice")!.textContent).toContain("Saved — sent to the screen."); + expect(saveButton(el).disabled).toBe(true); + }); + + it("save error keeps changes", async () => { + const {hass, callWS, real} = spied(); + const el = await open(hass); + await addBlockRight(el); + callWS.mockImplementation((msg: {type: string}) => + msg.type === "ha_controller/layout/save" + ? Promise.reject({code: "invalid_layout", message: "invalid_name@b2"}) + : real(msg), + ); + await click(el, saveButton(el)); + expect(one(el, ".notice")!.textContent).toContain("Names need 1 to 32 characters."); + expect(blocks(el)).toHaveLength(5); + expect(saveButton(el).disabled).toBe(false); + }); + + it("shows the message of other save errors", async () => { + const {hass, callWS, real} = spied(); + const el = await open(hass); + await addBlockRight(el); + callWS.mockImplementation((msg: {type: string}) => + msg.type === "ha_controller/layout/save" ? Promise.reject({code: "not_found", message: "Screen not found"}) : real(msg), + ); + await click(el, saveButton(el)); + expect(one(el, ".notice")!.textContent).toContain("Screen not found"); + }); + + describe("with fake timers", () => { + beforeEach(() => vi.useFakeTimers()); + + it("refresh does not reset working copy", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + await addBlockRight(el); + callWS.mockClear(); + await vi.advanceTimersByTimeAsync(10_000); + await settle(el); + expect(callWS.mock.calls.map((c) => c[0].type)).toEqual(["ha_controller/screens"]); + el.hass = {...hass}; + await settle(el); + expect(blocks(el)).toHaveLength(5); + expect(callWS.mock.calls.map((c) => c[0].type)).toEqual(["ha_controller/screens"]); + }); + + it("stops refreshing when removed", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + el.remove(); + callWS.mockClear(); + await vi.advanceTimersByTimeAsync(30_000); + expect(callWS).not.toHaveBeenCalled(); + }); + }); + + it("changing the sleep delay enables Save and sends it", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + const input = one(el, 'input[name="sleep_timeout"]')!; + expect(input.value).toBe("20"); + input.value = "45"; + input.dispatchEvent(new Event("input")); + await settle(el); + expect(saveButton(el).disabled).toBe(false); + await click(el, saveButton(el)); + const call = saveCall(callWS); + expect(call.layout.settings.sleep_timeout).toBe(45); + }); + + it("disables Save and lists local errors for an invalid sleep delay", async () => { + const {hass} = spied(); + const el = await open(hass); + const input = one(el, 'input[name="sleep_timeout"]')!; + input.value = "2"; + input.dispatchEvent(new Event("input")); + await settle(el); + expect(saveButton(el).disabled).toBe(true); + expect(one(el, ".errors")!.textContent).toContain("The sleep delay must be 0"); + }); + + describe("status line", () => { + it("reports update available", async () => { + const el = await open(spied({firmware_version: "0.0.9"}).hass); + expect(one(el, ".status")!.textContent).toContain("Online · firmware 0.0.9 — update available"); + }); + it("reports in sync", async () => { + const el = await open(spied().hass); + expect(one(el, ".status")!.textContent).toContain("Online · firmware 0.1.0 · in sync"); + }); + it("reports syncing", async () => { + const el = await open(spied({device_revision: "old"}).hass); + expect(one(el, ".status")!.textContent).toContain("Online · firmware 0.1.0 · syncing…"); + }); + it("reports offline", async () => { + const el = await open(spied({online: false}).hass); + expect(one(el, ".status")!.textContent?.trim()).toBe("Offline"); + }); + }); + + it("shows the menu button only when narrow", async () => { + const {hass} = spied(); + const el = await open(hass); + expect(one(el, "ha-menu-button")).toBeNull(); + el.narrow = true; + await settle(el); + expect(one(el, "ha-menu-button")).not.toBeNull(); + }); +}); diff --git a/docs/README.md b/docs/README.md index 8b6700c..8eb402a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,3 +4,4 @@ - [Design specification](superpowers/specs/2026-11-16-ha-controller-design.md): the approved design for version 1, with the plans in `superpowers/plans/`. - [Device protocol v1](protocol/README.md): the normative layout model and device protocol, pinned by `docs/protocol/fixtures/`. - [Development](development.md): environments, tests and running a development Home Assistant. +- [Configuration](configuration.md): how to edit the screens in the HA Controller panel. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..12dcfe1 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,52 @@ +# Configuring HA Controller + +The HA Controller panel edits what each screen shows. Changes only reach the screen when you press Save. + +## Opening the panel + +Open **HA Controller** in the Home Assistant sidebar. The panel is only available to administrators. If you have several screens, pick one in the header. + +The status line next to the title tells you whether the screen is online and whether it is up to date: + +- `Offline`: the screen is not connected. Saved changes are delivered when it reconnects. +- `Online · firmware · syncing…`: the screen is receiving the latest layout. +- `Online · firmware · in sync`: the screen shows the saved layout. +- `Online · firmware — update available`: the screen firmware differs from the integration version. Update the firmware. + +## The block map + +The map shows every block of the screen as a tile. Each block is a full-screen page on the device. The block marked **start** is the one shown when the screen wakes up. + +- Select a block to edit it on the right (below the map on narrow windows). +- Click a **+** next to a block to add a neighbouring block there. New blocks are named "Block 5", "Block 6" and so on. +- Set another start block with "Set as start block". You cannot delete the start block, nor a block that would leave other blocks unreachable from the start. + +## How swiping follows the map + +The map is the layout of the pages on the screen. Put a finger on the right edge and slide left to open the block on the right. The same works for every edge: slide right from the left edge to open the block on the left, slide up from the bottom edge to open the block below, and slide down from the top edge to open the block above. + +## Block types + +- **Light**: controls a light entity (tap to toggle, slide to change brightness). +- **Thermostat**: controls a climate entity. +- **Custom**: a free page of up to 6 items, shown in order. Items are a text, an emoji, an entity state (optionally an attribute), the screen battery or the screen brightness. Use the arrows to reorder items and the remove button to delete one. + +## Fonts and backgrounds + +Each block has a font size (S, M, L or XL) and a background colour, chosen from the palette or with a custom colour. The text colour is chosen automatically so it stays readable. Custom items can inherit the font size of their block or override it. + +## Screen settings + +Under the map, **Sleep after (seconds)** sets how long the screen stays on without interaction. The default is 20 seconds. `0` keeps the screen on. Otherwise use a value between 5 and 3600. + +## Saving + +Save and Revert are enabled once you change something. Save is disabled while the layout has errors, which are listed under the map. Revert discards your changes. After saving, the panel tells you whether the new layout was sent to the screen or will be delivered when it reconnects. The panel never overwrites your unsaved changes when the status refreshes. + +## Limits + +- 32 blocks per screen +- 6 items per custom block +- 32 characters per block name +- 64 characters per text +- 64 emoji per layout, from the supported emoji set diff --git a/docs/development.md b/docs/development.md index 3737ce3..99726c5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -40,7 +40,16 @@ The screen reports itself with ESPHome events. Open Developer tools › Events, ## Panel -Filled in by plan 3. +The panel is TypeScript with Lit and Vite, in `custom_components/ha_controller/frontend/` (Node 24). Run these from the repository root: + +```bash +npm --prefix custom_components/ha_controller/frontend ci # install +npm --prefix custom_components/ha_controller/frontend test # unit and component tests +npm --prefix custom_components/ha_controller/frontend run dev # mock harness (dev/index.html) in the browser +npm --prefix custom_components/ha_controller/frontend run build -- --watch # rebuild dist/ while testing in Home Assistant +``` + +`npm run dev` serves the panel against `dev/mock-hass.ts`, an in-memory fake of the websocket API seeded with the reference layout. The production bundle is `frontend/dist/ha-controller-panel.js` (git-ignored); the integration serves it to the sidebar panel. ## Firmware From 58cdd1c675df84900270bcaf54fe10a3690fe05d Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Tue, 17 Nov 2026 06:19:53 +0100 Subject: [PATCH 27/49] fix(panel): keep screen state consistent across saves, switches and failed loads Co-Authored-By: Claude Sonnet 5.5 --- .../frontend/src/ha-controller-panel.ts | 28 ++++- .../ha_controller/frontend/src/messages.ts | 1 + .../ha_controller/frontend/test/panel.test.ts | 106 ++++++++++++++++++ 3 files changed, 129 insertions(+), 6 deletions(-) diff --git a/custom_components/ha_controller/frontend/src/ha-controller-panel.ts b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts index 784ad5c..56acd08 100644 --- a/custom_components/ha_controller/frontend/src/ha-controller-panel.ts +++ b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts @@ -180,25 +180,36 @@ export class HaControllerPanel extends LitElement { this.screens = await listScreens(this.hass); } catch { // A failed refresh keeps the previous status; the next tick tries again. + return; } + // A failed or empty first load leaves no screen selected: pick one now. + if (this.entryId === null && this.screens.length > 0) await this.selectScreen(this.screens[0].entry_id); } - private async selectScreen(entryId: string): Promise { + /** Load a screen; resolves true when it is now the loaded one. */ + private async selectScreen(entryId: string): Promise { const token = ++this.loadToken; try { const layout = await getLayout(this.hass as Hass, entryId); - if (token !== this.loadToken) return; + if (token !== this.loadToken) return false; this.entryId = entryId; this.saved = layout; this.layout = layout; this.selectedId = layout.start ?? layout.blocks[0]?.id ?? null; this.notice = null; + return true; } catch (err) { - if (token !== this.loadToken) return; + if (token !== this.loadToken) return false; this.notice = {kind: "error", text: this.describe(err, UI.loadFailed)}; + return false; } } + private onScreenChange = async (e: Event): Promise => { + const select = e.target as HTMLSelectElement; + if (!(await this.selectScreen(select.value))) select.value = this.entryId ?? ""; + }; + private describe(err: unknown, fallback: string): string { const message = (err as {message?: unknown} | null)?.message; return typeof message === "string" && message !== "" ? message : fallback; @@ -247,14 +258,16 @@ export class HaControllerPanel extends LitElement { private onSave = async (): Promise => { if (!this.hass || !this.entryId || !this.layout || this.saving) return; const layout = this.layout; + const entryId = this.entryId; this.saving = true; try { - const result = await saveLayout(this.hass, this.entryId, layout); + const result = await saveLayout(this.hass, entryId, layout); + if (entryId !== this.entryId) return; this.saved = layout; this.notice = {kind: "ok", text: result.pushed ? UI.savedPushed : UI.savedOffline}; void this.refreshScreens(); } catch (err) { - this.notice = {kind: "error", text: this.saveError(err, layout)}; + if (entryId === this.entryId) this.notice = {kind: "error", text: this.saveError(err, layout)}; } finally { this.saving = false; } @@ -292,6 +305,7 @@ export class HaControllerPanel extends LitElement { protected render() { const errors = this.errors; + const locked = this.dirty || this.saving; const canSave = this.dirty && errors.length === 0 && !this.saving; return html`
    @@ -301,7 +315,9 @@ export class HaControllerPanel extends LitElement { ? html`