diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md
new file mode 100644
index 0000000..809ddb0
--- /dev/null
+++ b/.claude/CLAUDE.md
@@ -0,0 +1,75 @@
+# 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 `.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z`; `.github/scripts/.venv/bin/python .github/scripts/versioning.py check [--tag vX.Y.Z]` verifies it (CI job `versions`).
+- The protocol is defined in `docs/protocol/README.md` and pinned by `docs/protocol/fixtures/`.
+- The repository root holds no files except README.md, LICENSE, 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
+.github/scripts/.venv/bin/python .github/scripts/make_brand_icon.py # regenerate brand icons
+.github/scripts/.venv/bin/python .github/scripts/versioning.py check # verify the single repository version
+.github/scripts/.venv/bin/python .github/scripts/versioning.py check --tag vX.Y.Z # also verify a release tag
+.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z # set the version in every source
+
+# 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
+
+# Firmware (own venv, run from the repository root)
+python3.13 -m venv esphome/.venv
+esphome/.venv/bin/pip install -r esphome/requirements.txt
+cmake -S esphome/tests -B esphome/tests/build && cmake --build esphome/tests/build
+ctest --test-dir esphome/tests/build --output-on-failure
+
+# Firmware (needs SDL2 for the simulator: brew install sdl2 / apt install libsdl2-dev)
+esphome/.venv/bin/esphome compile esphome/ha-controller.yaml
+esphome/.venv/bin/esphome compile esphome/simulator.yaml
+esphome/.venv/bin/esphome run esphome/simulator.yaml # desktop simulator, API on port 6053
+
+# 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
+npm --prefix custom_components/ha_controller/frontend run dev # panel against a mock hass
+```
+
+## Skills and agents
+
+- Skill `protocol-change` (`.claude/skills/protocol-change/`): checklist for any change that crosses the Home Assistant ↔ screen boundary.
+- Skill `firmware-dev` (`.claude/skills/firmware-dev/`): commands, simulator loop and rules for the ESPHome firmware and LVGL code.
+- Skill `add-widget` (`.claude/skills/add-widget/`): end-to-end checklist for a new block widget or custom item kind.
+- Skill `release` (`.claude/skills/release/`): cutting a release and changing the release pipeline (versions, workflow, Pages installer, HACS packaging, OTA URLs).
+- Agent `firmware-reviewer` (`.claude/agents/firmware-reviewer.md`): reviews changes under `esphome/` for ESPHome/LVGL correctness, memory and hardware safety.
+- 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/firmware-reviewer.md b/.claude/agents/firmware-reviewer.md
new file mode 100644
index 0000000..e5cb94a
--- /dev/null
+++ b/.claude/agents/firmware-reviewer.md
@@ -0,0 +1,17 @@
+---
+name: firmware-reviewer
+description: Reviews changes under esphome/ for ESPHome/LVGL correctness, memory and hardware safety. Use before merging firmware changes.
+tools: Read, Grep, Glob, Bash
+---
+
+You review firmware changes. Read the diff (`git diff main...HEAD -- esphome`), then check:
+
+- No blocking calls in `loop`, except the OTA action.
+- LVGL objects are deleted with their views, with animations cancelled first.
+- No ESPHome callbacks are registered per view.
+- JSON is parsed defensively (missing keys, wrong types, oversized input).
+- Pins and I²C addresses match `docs/hardware.md`.
+- New pure logic has host tests in `esphome/tests/`.
+- Both configs compile: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml` and `esphome/simulator.yaml`.
+
+Report each finding as `file:line — issue — fix`. Say so when there is none.
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/.claude/agents/protocol-guardian.md b/.claude/agents/protocol-guardian.md
new file mode 100644
index 0000000..b51edb3
--- /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/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/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/README.md` describes the new behaviour.
+
+Output a list of `file:line — inconsistency — fix`, or "Protocol consistent".
diff --git a/.claude/skills/add-widget/SKILL.md b/.claude/skills/add-widget/SKILL.md
new file mode 100644
index 0000000..e387128
--- /dev/null
+++ b/.claude/skills/add-widget/SKILL.md
@@ -0,0 +1,23 @@
+---
+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.
+---
+
+# Add a widget
+
+A widget crosses the Home Assistant ↔ screen boundary, so start with the `protocol-change` skill and keep its checklist open. Then:
+
+1. Protocol doc and fixtures: `docs/protocol/README.md` and `docs/protocol/fixtures/` (recompute golden `rev` values).
+2. `ENTITY_BLOCK_DOMAINS` / `ITEM_KINDS` in `custom_components/ha_controller/const.py`, and the panel model in `custom_components/ha_controller/frontend/`.
+3. The state builder and the control mapping in the integration.
+4. The panel editor options and the preview.
+5. The C++ parser enum and the view under `esphome/components/ha_controller/` (with host tests; see the `firmware-dev` skill).
+6. `docs/configuration.md`.
+7. Run all suites and both firmware compiles:
+ - `custom_components/.venv/bin/pytest custom_components/ha_controller/tests`
+ - `.github/scripts/.venv/bin/pytest .github/scripts/tests`
+ - `npm --prefix custom_components/ha_controller/frontend test`
+ - `ctest --test-dir esphome/tests/build --output-on-failure`
+ - `esphome compile` for `esphome/ha-controller.yaml` and `esphome/simulator.yaml`
+
+Finish with the `protocol-guardian` and `firmware-reviewer` agents.
diff --git a/.claude/skills/firmware-dev/SKILL.md b/.claude/skills/firmware-dev/SKILL.md
new file mode 100644
index 0000000..da87b56
--- /dev/null
+++ b/.claude/skills/firmware-dev/SKILL.md
@@ -0,0 +1,47 @@
+---
+name: firmware-dev
+description: Use when building, flashing, simulating or changing the ESPHome firmware (esphome/), including LVGL UI code.
+---
+
+# Firmware development
+
+The firmware is ESPHome with LVGL in `esphome/`. Hardware facts are in `docs/hardware.md`; the manual hardware checklist is in `docs/development.md`.
+
+## Commands
+
+Run from the repository root:
+
+```bash
+# Host tests (pure C++ logic)
+cmake -S esphome/tests -B esphome/tests/build && cmake --build esphome/tests/build
+ctest --test-dir esphome/tests/build --output-on-failure
+
+# Compile both configs (long; run in the background)
+esphome/.venv/bin/esphome compile esphome/ha-controller.yaml
+esphome/.venv/bin/esphome compile esphome/simulator.yaml
+
+# Flash over USB-C, or run the SDL simulator
+esphome/.venv/bin/esphome run esphome/ha-controller.yaml
+esphome/.venv/bin/esphome run esphome/simulator.yaml
+```
+
+The venv is Python 3.13 with `esphome/requirements.txt`. Never commit `esphome/secrets.yaml`.
+
+## Simulator loop
+
+1. Change the code and run the host tests.
+2. `esphome run esphome/simulator.yaml` (an SDL window; mouse drags act as finger swipes).
+3. Connect it to a development Home Assistant (see `docs/development.md`) and edit the layout in the panel.
+4. Before finishing, compile both configs. `install_firmware` exists only in `ha-controller.yaml` (the simulator has no HTTP OTA).
+
+## Rules
+
+- Pure logic goes in host-tested headers or modules under `esphome/components/ha_controller/` with a test in `esphome/tests/`.
+- LVGL is called on the main loop only.
+- Views never register ESPHome callbacks; the component registers them once.
+- Call `lv_refr_now` before blocking work (such as OTA), so the message is on the panel.
+- LVGL is paused while the screen sleeps. Call `wake()` before showing anything the user must see (`show_message` already does).
+- Fonts are declared in `esphome/packages/ui.yaml` and mapped in the `ha_controller:` block.
+- A new LVGL widget type needs a hidden instance on `boot_page`, so ESPHome compiles it in.
+- Controls stay inside radius 185 of the 466 px circle.
+- Keep the `cst9217` external component pinned to its commit SHA.
diff --git a/.claude/skills/protocol-change/SKILL.md b/.claude/skills/protocol-change/SKILL.md
new file mode 100644
index 0000000..53645df
--- /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/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/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md
new file mode 100644
index 0000000..83ebd7e
--- /dev/null
+++ b/.claude/skills/release/SKILL.md
@@ -0,0 +1,32 @@
+---
+name: release
+description: "Use when cutting a release or changing the release pipeline: versions, release workflow, GitHub Pages installer, HACS packaging, firmware OTA URLs."
+---
+
+# Releasing HA Controller
+
+- Never edit versions by hand. Use `.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z`.
+
+## Steps (from `docs/releasing.md`)
+
+1. `.github/scripts/.venv/bin/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.
+5. Check that the Pages page shows X.Y.Z and that HACS offers X.Y.Z.
+
+Dry runs use `workflow_dispatch` (only the `build` job runs).
+
+## What each job produces
+
+- `build`: `dist/ha_controller.zip` (integration with the built panel, for HACS) and `dist/ha-controller-X.Y.Z.*` (factory image, OTA image and OTA md5), uploaded as the `dist` artifact.
+- `pages`: the installer site, built from `esphome/web`, the firmware of this version (from `dist`) and the firmware of every earlier release (releases without firmware assets are skipped). Tag runs only, after `build`.
+- `release`: the GitHub release with every file of `dist`. Tag runs only, after `pages`.
+
+The order is `build` → `pages` → `release`. Pages is deployed before the release so the OTA URLs exist when HACS offers the new version.
+
+## Rules
+
+- The `github-pages` environment must allow tags `v*` (see the one-time setup in `docs/releasing.md`), or the `pages` job fails on tag runs.
+- OTA URLs must stay stable (`firmware//ha-controller.ota.bin`), because integrations already installed depend on them.
+- After any script change, run `.github/scripts/.venv/bin/pytest .github/scripts/tests`.
diff --git a/.github/scripts/build_pages.py b/.github/scripts/build_pages.py
new file mode 100644
index 0000000..1b612a4
--- /dev/null
+++ b/.github/scripts/build_pages.py
@@ -0,0 +1,72 @@
+"""Build the GitHub Pages site: web installer, ESP Web Tools manifest and every OTA image."""
+
+import argparse
+import json
+import shutil
+from pathlib import Path
+
+RELEASE_URL = "https://github.com/pyxel-dev/HA-controller/releases/tag/v{version}"
+
+
+def build_site(web_dir: Path, releases_dir: Path, latest: str, out_dir: Path) -> None:
+ """Write the site to out_dir from web_dir and releases_dir// asset folders."""
+ latest_dir = releases_dir / latest
+ latest_factory = latest_dir / f"ha-controller-{latest}.factory.bin"
+ latest_ota = latest_dir / f"ha-controller-{latest}.ota.bin"
+ for required in (latest_factory, latest_ota):
+ if not required.is_file():
+ raise FileNotFoundError(f"Missing release asset: {required}")
+
+ firmware = out_dir / "firmware"
+ firmware.mkdir(parents=True, exist_ok=True)
+
+ page = (web_dir / "index.html").read_text(encoding="utf-8")
+ (out_dir / "index.html").write_text(page.replace("{{VERSION}}", latest), encoding="utf-8")
+ (out_dir / ".nojekyll").write_text("", encoding="utf-8")
+
+ for folder in sorted(p for p in releases_dir.iterdir() if p.is_dir()):
+ version = folder.name
+ ota = folder / f"ha-controller-{version}.ota.bin"
+ md5 = folder / f"ha-controller-{version}.ota.bin.md5"
+ if not (ota.is_file() and md5.is_file()):
+ continue
+ target = firmware / version
+ target.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(ota, target / "ha-controller.ota.bin")
+ shutil.copyfile(md5, target / "ha-controller.ota.bin.md5")
+
+ shutil.copyfile(latest_factory, firmware / "ha-controller.factory.bin")
+ md5_latest = (latest_dir / f"ha-controller-{latest}.ota.bin.md5").read_text().strip()
+ manifest = {
+ "name": "HA Controller",
+ "version": latest,
+ "home_assistant_domain": "esphome",
+ "new_install_prompt_erase": True,
+ "builds": [
+ {
+ "chipFamily": "ESP32-S3",
+ "parts": [{"path": "ha-controller.factory.bin", "offset": 0}],
+ "ota": {
+ "path": f"{latest}/ha-controller.ota.bin",
+ "md5": md5_latest,
+ "release_url": RELEASE_URL.format(version=latest),
+ },
+ }
+ ],
+ }
+ (firmware / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--web", type=Path, required=True)
+ parser.add_argument("--releases", type=Path, required=True)
+ parser.add_argument("--latest", required=True)
+ parser.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args(argv)
+ build_site(args.web, args.releases, args.latest, args.out)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/scripts/collect_firmware.py b/.github/scripts/collect_firmware.py
new file mode 100644
index 0000000..87740bf
--- /dev/null
+++ b/.github/scripts/collect_firmware.py
@@ -0,0 +1,43 @@
+"""Collect the ESPHome factory and OTA images into versioned release assets."""
+
+import argparse
+import hashlib
+import shutil
+from pathlib import Path
+
+
+def _only(build_dir: Path, pattern: str) -> Path:
+ matches = sorted(build_dir.rglob(pattern))
+ if len(matches) != 1:
+ raise ValueError(f"Expected exactly one {pattern} under {build_dir}, found {len(matches)}")
+ return matches[0]
+
+
+def collect(build_dir: Path, version: str, out_dir: Path) -> list[Path]:
+ """Copy the images to out_dir as ha-controller-.* and write the OTA md5."""
+ factory = _only(build_dir, "*.factory.bin")
+ ota = _only(build_dir, "*.ota.bin")
+ out_dir.mkdir(parents=True, exist_ok=True)
+
+ factory_out = out_dir / f"ha-controller-{version}.factory.bin"
+ ota_out = out_dir / f"ha-controller-{version}.ota.bin"
+ md5_out = out_dir / f"ha-controller-{version}.ota.bin.md5"
+ shutil.copyfile(factory, factory_out)
+ shutil.copyfile(ota, ota_out)
+ md5_out.write_text(hashlib.md5(ota.read_bytes()).hexdigest(), encoding="ascii")
+ return [factory_out, ota_out, md5_out]
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--build-dir", type=Path, required=True)
+ parser.add_argument("--version", required=True)
+ parser.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args(argv)
+ for path in collect(args.build_dir, args.version, args.out):
+ print(path)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
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/package_integration.py b/.github/scripts/package_integration.py
new file mode 100644
index 0000000..66e28a7
--- /dev/null
+++ b/.github/scripts/package_integration.py
@@ -0,0 +1,49 @@
+"""Zip the integration for HACS, with the built panel and without development files."""
+
+import argparse
+import zipfile
+from pathlib import Path
+
+INTEGRATION = Path("custom_components") / "ha_controller"
+PANEL = Path("frontend") / "dist" / "ha-controller-panel.js"
+BUILD_HINT = (
+ "Build the panel first: npm --prefix custom_components/ha_controller/frontend run build"
+)
+
+
+def _included(relative: Path) -> bool:
+ parts = relative.parts
+ if "__pycache__" in parts or "tests" == parts[0]:
+ return False
+ if relative.name.startswith(".") or relative.suffix == ".pyc":
+ return False
+ if parts[0] == "frontend":
+ return relative == PANEL
+ return True
+
+
+def package(root: Path, out_file: Path) -> Path:
+ """Write the zip with the integration contents at the zip root."""
+ source = root / INTEGRATION
+ if not (source / PANEL).is_file():
+ raise FileNotFoundError(BUILD_HINT)
+ out_file.parent.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(out_file, "w", zipfile.ZIP_DEFLATED) as zf:
+ for path in sorted(source.rglob("*")):
+ relative = path.relative_to(source)
+ if path.is_file() and _included(relative):
+ zf.write(path, relative.as_posix())
+ return out_file
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", type=Path, default=Path.cwd())
+ parser.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args(argv)
+ print(package(args.root, args.out))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/scripts/pyproject.toml b/.github/scripts/pyproject.toml
new file mode 100644
index 0000000..9fe26ce
--- /dev/null
+++ b/.github/scripts/pyproject.toml
@@ -0,0 +1,9 @@
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+
+[tool.ruff]
+target-version = "py314"
+line-length = 100
+
+[tool.ruff.lint]
+select = ["E", "F", "I", "UP", "B"]
diff --git a/.github/scripts/requirements.txt b/.github/scripts/requirements.txt
new file mode 100644
index 0000000..e811611
--- /dev/null
+++ b/.github/scripts/requirements.txt
@@ -0,0 +1,3 @@
+pytest
+ruff
+pillow
diff --git a/.github/scripts/tests/__init__.py b/.github/scripts/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/.github/scripts/tests/test_docs_links.py b/.github/scripts/tests/test_docs_links.py
new file mode 100644
index 0000000..3e7aa12
--- /dev/null
+++ b/.github/scripts/tests/test_docs_links.py
@@ -0,0 +1,51 @@
+"""Documentation checks: relative links resolve and the docs index is complete."""
+
+import re
+from pathlib import Path
+
+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:", "#")
+
+
+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)
+ }
+ docs = ROOT / "docs"
+ candidates = [*docs.glob("*.md"), *docs.glob("*/README.md")]
+ missing = [
+ 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/.github/scripts/tests/test_protocol_fixtures.py b/.github/scripts/tests/test_protocol_fixtures.py
new file mode 100644
index 0000000..c85cd13
--- /dev/null
+++ b/.github/scripts/tests/test_protocol_fixtures.py
@@ -0,0 +1,117 @@
+"""Executable protocol contract: shape and golden values of docs/protocol/fixtures."""
+
+import hashlib
+import json
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+FIXTURES = ROOT / "docs" / "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
diff --git a/.github/scripts/tests/test_release_scripts.py b/.github/scripts/tests/test_release_scripts.py
new file mode 100644
index 0000000..6ddfffb
--- /dev/null
+++ b/.github/scripts/tests/test_release_scripts.py
@@ -0,0 +1,183 @@
+"""Release tooling: firmware collection, integration zip and GitHub Pages site."""
+
+import hashlib
+import json
+import zipfile
+from pathlib import Path
+
+import pytest
+
+from build_pages import build_site
+from collect_firmware import collect
+from package_integration import package
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+INTEGRATION = "custom_components/ha_controller"
+PANEL = f"{INTEGRATION}/frontend/dist/ha-controller-panel.js"
+
+
+def _write(path: Path, content: bytes | str = b"x") -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if isinstance(content, str):
+ path.write_text(content, encoding="utf-8")
+ else:
+ path.write_bytes(content)
+ return path
+
+
+def test_collect_writes_versioned_files_and_md5(tmp_path):
+ build = tmp_path / "build" / "ha-controller" / "build"
+ _write(build / "firmware.factory.bin", b"factory")
+ _write(build / "firmware.ota.bin", b"ota-image")
+ _write(build / "ha-controller.bin", b"other")
+ _write(build / "bootloader" / "bootloader.bin", b"boot")
+ out = tmp_path / "out"
+
+ written = collect(tmp_path / "build", "0.2.0", out)
+
+ assert sorted(p.name for p in written) == [
+ "ha-controller-0.2.0.factory.bin",
+ "ha-controller-0.2.0.ota.bin",
+ "ha-controller-0.2.0.ota.bin.md5",
+ ]
+ assert (out / "ha-controller-0.2.0.factory.bin").read_bytes() == b"factory"
+ md5 = (out / "ha-controller-0.2.0.ota.bin.md5").read_bytes()
+ assert md5 == hashlib.md5(b"ota-image").hexdigest().encode()
+ assert len(md5) == 32
+
+
+def test_collect_requires_exactly_one_of_each(tmp_path):
+ build = tmp_path / "build"
+ build.mkdir()
+ with pytest.raises(ValueError):
+ collect(build, "0.2.0", tmp_path / "out")
+
+ _write(build / "a" / "firmware.factory.bin")
+ _write(build / "b" / "firmware.factory.bin")
+ _write(build / "a" / "firmware.ota.bin")
+ with pytest.raises(ValueError):
+ collect(build, "0.2.0", tmp_path / "out")
+
+
+def _fake_repo(root: Path, with_panel: bool = True) -> None:
+ _write(root / INTEGRATION / "manifest.json", "{}")
+ _write(root / INTEGRATION / "__init__.py", "")
+ _write(root / INTEGRATION / "emoji.json", "[]")
+ _write(root / INTEGRATION / "brand" / "icon.png")
+ _write(root / INTEGRATION / "__pycache__" / "x.cpython-314.pyc")
+ _write(root / INTEGRATION / "tests" / "test_x.py", "")
+ _write(root / INTEGRATION / "frontend" / "src" / "a.ts", "")
+ _write(root / INTEGRATION / "frontend" / "package.json", "{}")
+ _write(root / INTEGRATION / "frontend" / "node_modules" / "m" / "i.js", "")
+ _write(root / INTEGRATION / "frontend" / "dist" / "other.js", "")
+ _write(root / INTEGRATION / "frontend" / "dist" / ".gitkeep", "")
+ if with_panel:
+ _write(root / PANEL, "panel")
+
+
+def test_package_zips_integration_with_panel(tmp_path):
+ _fake_repo(tmp_path)
+ out = package(tmp_path, tmp_path / "dist" / "ha_controller.zip")
+
+ with zipfile.ZipFile(out) as zf:
+ names = set(zf.namelist())
+ assert names == {
+ "manifest.json",
+ "__init__.py",
+ "emoji.json",
+ "brand/icon.png",
+ "frontend/dist/ha-controller-panel.js",
+ }
+
+
+def test_package_requires_built_panel(tmp_path):
+ _fake_repo(tmp_path, with_panel=False)
+ with pytest.raises(FileNotFoundError, match="Build the panel first"):
+ package(tmp_path, tmp_path / "ha_controller.zip")
+
+
+def _release(releases: Path, version: str) -> None:
+ _write(releases / version / f"ha-controller-{version}.factory.bin", f"f{version}".encode())
+ ota = f"o{version}".encode()
+ _write(releases / version / f"ha-controller-{version}.ota.bin", ota)
+ _write(
+ releases / version / f"ha-controller-{version}.ota.bin.md5",
+ hashlib.md5(ota).hexdigest(),
+ )
+
+
+def _web(tmp_path: Path) -> Path:
+ return _write(
+ tmp_path / "web" / "index.html", "Firmware {{VERSION}}
"
+ ).parent
+
+
+def test_build_site_manifest(tmp_path):
+ releases = tmp_path / "releases"
+ _release(releases, "0.2.0")
+ out = tmp_path / "site"
+
+ build_site(_web(tmp_path), releases, "0.2.0", out)
+
+ manifest = json.loads((out / "firmware" / "manifest.json").read_text())
+ assert manifest == {
+ "name": "HA Controller",
+ "version": "0.2.0",
+ "home_assistant_domain": "esphome",
+ "new_install_prompt_erase": True,
+ "builds": [
+ {
+ "chipFamily": "ESP32-S3",
+ "parts": [{"path": "ha-controller.factory.bin", "offset": 0}],
+ "ota": {
+ "path": "0.2.0/ha-controller.ota.bin",
+ "md5": hashlib.md5(b"o0.2.0").hexdigest(),
+ "release_url": "https://github.com/pyxel-dev/HA-controller/releases/tag/v0.2.0",
+ },
+ }
+ ],
+ }
+ assert (out / "firmware" / "ha-controller.factory.bin").read_bytes() == b"f0.2.0"
+
+
+def test_build_site_keeps_every_release(tmp_path):
+ releases = tmp_path / "releases"
+ _release(releases, "0.1.0")
+ _release(releases, "0.2.0")
+ out = tmp_path / "site"
+
+ build_site(_web(tmp_path), releases, "0.2.0", out)
+
+ for version in ("0.1.0", "0.2.0"):
+ folder = out / "firmware" / version
+ assert (folder / "ha-controller.ota.bin").read_bytes() == f"o{version}".encode()
+ assert (folder / "ha-controller.ota.bin.md5").read_text() == hashlib.md5(
+ f"o{version}".encode()
+ ).hexdigest()
+ assert (out / "firmware" / "ha-controller.factory.bin").read_bytes() == b"f0.2.0"
+
+
+def test_build_site_renders_version(tmp_path):
+ releases = tmp_path / "releases"
+ _release(releases, "0.2.0")
+ out = tmp_path / "site"
+
+ build_site(_web(tmp_path), releases, "0.2.0", out)
+
+ html = (out / "index.html").read_text()
+ assert "Firmware 0.2.0" in html
+ assert "{{VERSION}}" not in html
+ assert (out / ".nojekyll").exists()
+
+
+def test_build_site_requires_latest_assets(tmp_path):
+ releases = tmp_path / "releases"
+ _release(releases, "0.1.0")
+ with pytest.raises(FileNotFoundError):
+ build_site(_web(tmp_path), releases, "0.2.0", tmp_path / "site")
+
+
+def test_web_page_template():
+ html = (REPO_ROOT / "esphome" / "web" / "index.html").read_text(encoding="utf-8")
+ assert html.count("{{VERSION}}") >= 2
+ assert "esp-web-tools@10.5.2" in html
diff --git a/.github/scripts/tests/test_versioning.py b/.github/scripts/tests/test_versioning.py
new file mode 100644
index 0000000..63d8c38
--- /dev/null
+++ b/.github/scripts/tests/test_versioning.py
@@ -0,0 +1,206 @@
+"""Single-version check and bump across manifest, ESPHome, panel and panel lock."""
+
+import json
+from pathlib import Path
+
+import pytest
+
+import versioning
+from versioning import bump_version, check_versions, main, read_versions
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+MANIFEST = "custom_components/ha_controller/manifest.json"
+ESPHOME = "esphome/version.yaml"
+FRONTEND = "custom_components/ha_controller/frontend/package.json"
+FRONTEND_LOCK = "custom_components/ha_controller/frontend/package-lock.json"
+
+
+def _json(data: dict) -> str:
+ return json.dumps(data, indent=2) + "\n"
+
+
+def _manifest(version: str) -> str:
+ # Same shape as the real manifest: inline arrays that json.dumps would reflow.
+ return (
+ "{\n"
+ ' "domain": "ha_controller",\n'
+ ' "name": "HA Controller",\n'
+ ' "after_dependencies": ["esphome"],\n'
+ ' "codeowners": ["@pyxel-dev"],\n'
+ ' "config_flow": true,\n'
+ ' "dependencies": ["frontend", "http", "panel_custom", "websocket_api"],\n'
+ ' "requirements": [],\n'
+ f' "version": "{version}"\n'
+ "}\n"
+ )
+
+
+def _yaml(version: str) -> str:
+ return (
+ "substitutions:\n"
+ ' device_name: "ha-controller"\n'
+ f' project_version: "{version}"\n'
+ "esphome:\n"
+ " name: ha-controller\n"
+ )
+
+
+@pytest.fixture
+def repo(tmp_path: Path) -> Path:
+ files = {
+ MANIFEST: _manifest("0.1.0"),
+ ESPHOME: _yaml("0.1.0"),
+ FRONTEND: _json({"name": "ha-controller-panel", "version": "0.1.0", "private": True}),
+ FRONTEND_LOCK: _json(
+ {
+ "name": "ha-controller-panel",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "packages": {"": {"name": "ha-controller-panel", "version": "0.1.0"}},
+ }
+ ),
+ }
+ for relative, text in files.items():
+ path = tmp_path / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ return tmp_path
+
+
+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):
+ path = repo / MANIFEST
+ data = json.loads(path.read_text(encoding="utf-8"))
+ data["version"] = "0.2.0"
+ path.write_text(_json(data), encoding="utf-8")
+
+ errors = check_versions(repo)
+
+ assert len(errors) == 1
+ assert "manifest" in errors[0]
+ assert MANIFEST in errors[0]
+ assert "0.2.0" in errors[0]
+ assert "0.1.0" in errors[0]
+
+
+def test_check_errors_name_file_path_for_unreadable_source(repo):
+ (repo / ESPHOME).unlink()
+
+ errors = check_versions(repo)
+
+ assert any("esphome" in error and ESPHOME in error for error in errors)
+
+
+def test_check_tag_must_match(repo):
+ assert check_versions(repo, "v0.1.0") == []
+ assert check_versions(repo, "v0.1.1")
+ assert check_versions(repo, "0.1.0")
+
+
+def test_check_rejects_non_semver(repo):
+ (repo / ESPHOME).write_text(_yaml("0.1"), encoding="utf-8")
+ for relative in (MANIFEST, FRONTEND, FRONTEND_LOCK):
+ path = repo / relative
+ text = path.read_text(encoding="utf-8").replace('"0.1.0"', '"0.1"')
+ path.write_text(text, encoding="utf-8")
+
+ assert check_versions(repo)
+
+
+def test_bump_rewrites_all(repo):
+ before_yaml = (repo / ESPHOME).read_text(encoding="utf-8")
+
+ bump_version(repo, "1.2.3")
+
+ assert set(read_versions(repo).values()) == {"1.2.3"}
+ assert check_versions(repo) == []
+
+ manifest = json.loads((repo / MANIFEST).read_text(encoding="utf-8"))
+ assert manifest["version"] == "1.2.3"
+ assert manifest["dependencies"] == ["frontend", "http", "panel_custom", "websocket_api"]
+
+ frontend = json.loads((repo / FRONTEND).read_text(encoding="utf-8"))
+ assert frontend == {"name": "ha-controller-panel", "version": "1.2.3", "private": True}
+
+ lock = json.loads((repo / FRONTEND_LOCK).read_text(encoding="utf-8"))
+ assert lock["lockfileVersion"] == 3
+ assert lock["packages"][""]["name"] == "ha-controller-panel"
+
+ yaml_after = (repo / ESPHOME).read_text(encoding="utf-8")
+ assert yaml_after == before_yaml.replace('project_version: "0.1.0"', 'project_version: "1.2.3"')
+ assert ' device_name: "ha-controller"' in yaml_after
+
+ for relative in (FRONTEND, FRONTEND_LOCK):
+ assert (repo / relative).read_text(encoding="utf-8").endswith("}\n")
+
+
+def test_bump_changes_only_manifest_version_text(repo):
+ before = (repo / MANIFEST).read_text(encoding="utf-8")
+
+ bump_version(repo, "1.2.3")
+
+ after = (repo / MANIFEST).read_text(encoding="utf-8")
+ assert after == before.replace('"version": "0.1.0"', '"version": "1.2.3"')
+
+
+@pytest.mark.parametrize("bad", ["1.2", "v1.2.3", "1.2.3-rc1"])
+def test_bump_rejects_invalid(repo, bad):
+ with pytest.raises(ValueError):
+ bump_version(repo, bad)
+ assert set(read_versions(repo).values()) == {"0.1.0"}
+
+
+def test_repository_versions_are_consistent():
+ assert check_versions(REPO_ROOT) == []
+
+
+def test_main_exit_codes(repo, monkeypatch):
+ monkeypatch.setattr(versioning, "REPO_ROOT", repo)
+
+ assert main(["check"]) == 0
+ assert main(["check", "--tag", "v0.1.0"]) == 0
+ assert main(["check", "--tag", "v0.1.1"]) == 1
+ assert main(["bump", "0.3.0"]) == 0
+ assert set(read_versions(repo).values()) == {"0.3.0"}
+ assert main(["check"]) == 0
+ assert main(["bump", "0.3"]) == 1
+
+
+@pytest.mark.parametrize(
+ ("relative", "content"),
+ [
+ (MANIFEST, "{ not json"),
+ (MANIFEST, "[]"),
+ (MANIFEST, '{"domain": "ha_controller"}'),
+ (FRONTEND_LOCK, "[]"),
+ (FRONTEND_LOCK, '{"version": "0.1.0"}'),
+ (ESPHOME, "substitutions: {}\n"),
+ ],
+)
+@pytest.mark.parametrize("argv", [["check"], ["bump", "1.2.3"]])
+def test_main_reports_malformed_files_without_traceback(
+ repo, monkeypatch, capsys, relative, content, argv
+):
+ monkeypatch.setattr(versioning, "REPO_ROOT", repo)
+ (repo / relative).write_text(content, encoding="utf-8")
+
+ assert main(argv) == 1
+
+ assert capsys.readouterr().err.strip()
+
+
+def test_main_reports_missing_file_without_traceback(repo, monkeypatch, capsys):
+ monkeypatch.setattr(versioning, "REPO_ROOT", repo)
+ (repo / FRONTEND).unlink()
+
+ assert main(["check"]) == 1
+ assert main(["bump", "1.2.3"]) == 1
+ assert FRONTEND in capsys.readouterr().err
diff --git a/.github/scripts/versioning.py b/.github/scripts/versioning.py
new file mode 100644
index 0000000..8161bc7
--- /dev/null
+++ b/.github/scripts/versioning.py
@@ -0,0 +1,192 @@
+"""Check and bump the single SemVer version shared by the whole repository.
+
+The version lives in four files:
+- custom_components/ha_controller/manifest.json ("version")
+- esphome/version.yaml (substitutions.project_version)
+- custom_components/ha_controller/frontend/package.json ("version")
+- custom_components/ha_controller/frontend/package-lock.json (root and packages[""] "version")
+
+Usage:
+ python .github/scripts/versioning.py check [--tag vX.Y.Z]
+ python .github/scripts/versioning.py bump X.Y.Z
+"""
+
+import argparse
+import json
+import re
+import sys
+from collections import Counter
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")
+
+MANIFEST = Path("custom_components/ha_controller/manifest.json")
+ESPHOME = Path("esphome/version.yaml")
+FRONTEND = Path("custom_components/ha_controller/frontend/package.json")
+FRONTEND_LOCK = Path("custom_components/ha_controller/frontend/package-lock.json")
+
+SOURCE_PATHS = {
+ "manifest": MANIFEST,
+ "esphome": ESPHOME,
+ "frontend": FRONTEND,
+ "frontend-lock": FRONTEND_LOCK,
+}
+
+ESPHOME_LINE_RE = re.compile(r'^(\s*project_version:\s*")([^"]*)(")', re.MULTILINE)
+MANIFEST_VERSION_RE = re.compile(r'^(\s*"version"\s*:\s*")([^"]*)(")', re.MULTILINE)
+
+
+def _read_json(path: Path) -> dict:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _write_json(path: Path, data: dict) -> None:
+ path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+
+def _read_esphome(root: Path) -> str:
+ match = ESPHOME_LINE_RE.search((root / ESPHOME).read_text(encoding="utf-8"))
+ if match is None:
+ raise ValueError("project_version not found")
+ return match.group(2)
+
+
+def _read_lock(root: Path) -> str:
+ lock = _read_json(root / FRONTEND_LOCK)
+ root_version = lock["version"]
+ package_version = lock["packages"][""]["version"]
+ if root_version != package_version:
+ raise ValueError(
+ f'version {root_version} differs from packages[""] version {package_version}'
+ )
+ return root_version
+
+
+READERS = {
+ "manifest": lambda root: _read_json(root / MANIFEST)["version"],
+ "esphome": _read_esphome,
+ "frontend": lambda root: _read_json(root / FRONTEND)["version"],
+ "frontend-lock": _read_lock,
+}
+
+
+def _collect(root: Path) -> tuple[dict[str, str], list[str]]:
+ values: dict[str, str] = {}
+ errors: list[str] = []
+ for key, reader in READERS.items():
+ try:
+ values[key] = reader(root)
+ except (OSError, ValueError, KeyError, TypeError) as exc:
+ errors.append(f"{key} ({SOURCE_PATHS[key]}): cannot read version ({exc})")
+ return values, errors
+
+
+def read_versions(root: Path) -> dict[str, str]:
+ """Return the version found in each source, keyed by source name."""
+ values, errors = _collect(root)
+ if errors:
+ raise ValueError("; ".join(errors))
+ return values
+
+
+def check_versions(root: Path, tag: str | None = None) -> list[str]:
+ """Return human-readable errors; an empty list means the repository is consistent."""
+ values, errors = _collect(root)
+
+ for key, value in values.items():
+ if not VERSION_RE.fullmatch(value):
+ errors.append(f"{key} ({SOURCE_PATHS[key]}) version {value!r} is not SemVer X.Y.Z")
+
+ if values:
+ # The first source (manifest) wins a tie, so the reference is stable.
+ expected, _ = Counter(values.values()).most_common(1)[0]
+ for key, value in values.items():
+ if value != expected:
+ errors.append(f"{key} ({SOURCE_PATHS[key]}) is {value}, expected {expected}")
+
+ if tag is not None and tag != f"v{expected}":
+ errors.append(f"tag {tag} does not match version v{expected}")
+ elif tag is not None:
+ errors.append(f"tag {tag} cannot be checked without a readable version")
+
+ return errors
+
+
+def _bump_manifest_text(text: str, version: str) -> str:
+ """Replace only the top-level version value, leaving every other byte unchanged."""
+ old = json.loads(text)
+ if not isinstance(old, dict) or "version" not in old:
+ raise ValueError(f"{MANIFEST}: top-level version not found")
+
+ match = MANIFEST_VERSION_RE.search(text)
+ if match is None:
+ raise ValueError(f"{MANIFEST}: top-level version not found")
+ new_text = text[: match.start(2)] + version + text[match.end(2) :]
+
+ # Guard against matching a nested "version" key: the only change must be the top-level one.
+ if json.loads(new_text) != {**old, "version": version}:
+ raise ValueError(f"{MANIFEST}: could not locate the top-level version safely")
+ return new_text
+
+
+def bump_version(root: Path, version: str) -> None:
+ """Write version to every source. Nothing is written unless all sources can be updated."""
+ if not VERSION_RE.fullmatch(version):
+ raise ValueError(f"version {version!r} is not SemVer X.Y.Z")
+
+ manifest_text = (root / MANIFEST).read_text(encoding="utf-8", newline="")
+ manifest_new = _bump_manifest_text(manifest_text, version)
+
+ frontend = _read_json(root / FRONTEND)
+ frontend["version"] = version
+
+ lock = _read_json(root / FRONTEND_LOCK)
+ lock["version"] = version
+ lock["packages"][""]["version"] = version
+
+ esphome_text = (root / ESPHOME).read_text(encoding="utf-8")
+ esphome_new, count = ESPHOME_LINE_RE.subn(
+ lambda match: f"{match.group(1)}{version}{match.group(3)}", esphome_text, count=1
+ )
+ if count != 1:
+ raise ValueError(f"{ESPHOME}: project_version not found")
+
+ (root / MANIFEST).write_text(manifest_new, encoding="utf-8", newline="")
+ _write_json(root / FRONTEND, frontend)
+ _write_json(root / FRONTEND_LOCK, lock)
+ (root / ESPHOME).write_text(esphome_new, encoding="utf-8")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(prog="versioning.py", description=__doc__.splitlines()[0])
+ commands = parser.add_subparsers(dest="command", required=True)
+
+ check = commands.add_parser("check", help="verify that every source has the same version")
+ check.add_argument("--tag", help="release tag that must equal v + version")
+
+ bump = commands.add_parser("bump", help="set the version in every source")
+ bump.add_argument("version", help="new SemVer version X.Y.Z")
+
+ args = parser.parse_args(sys.argv[1:] if argv is None else argv)
+
+ try:
+ if args.command == "check":
+ errors = check_versions(REPO_ROOT, args.tag)
+ if errors:
+ for error in errors:
+ print(error, file=sys.stderr)
+ return 1
+ print(f"versions consistent: {next(iter(read_versions(REPO_ROOT).values()))}")
+ return 0
+
+ bump_version(REPO_ROOT, args.version)
+ except (OSError, ValueError, KeyError, TypeError) as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ print(f"version bumped to {args.version}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..5869771
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,54 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+jobs:
+ 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 .github/scripts/requirements.txt
+ - run: ruff check .github/scripts
+ - run: pytest .github/scripts/tests
+
+ versions:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.14"
+ - run: python .github/scripts/versioning.py check
+
+ 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
+
+ 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/.github/workflows/firmware.yml b/.github/workflows/firmware.yml
new file mode 100644
index 0000000..c2e9174
--- /dev/null
+++ b/.github/workflows/firmware.yml
@@ -0,0 +1,43 @@
+name: Firmware
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - "esphome/**"
+ - "docs/protocol/**"
+ - "custom_components/ha_controller/emoji.json"
+ - ".github/workflows/firmware.yml"
+ pull_request:
+ paths:
+ - "esphome/**"
+ - "docs/protocol/**"
+ - "custom_components/ha_controller/emoji.json"
+ - ".github/workflows/firmware.yml"
+
+jobs:
+ host-tests:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: cmake -S esphome/tests -B esphome/tests/build
+ - run: cmake --build esphome/tests/build
+ - run: ctest --test-dir esphome/tests/build --output-on-failure
+
+ compile:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.13"
+ - uses: actions/cache@v4
+ with:
+ path: |
+ ~/.platformio
+ esphome/.esphome
+ key: esphome-${{ hashFiles('esphome/requirements.txt', 'esphome/**/*.yaml') }}
+ - run: sudo apt-get install -y libsdl2-dev
+ - run: pip install -r esphome/requirements.txt
+ - run: esphome compile esphome/ha-controller.yaml
+ - run: esphome compile esphome/simulator.yaml
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..ac32a60
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,126 @@
+name: Release
+
+on:
+ push:
+ tags: ["v*"]
+ workflow_dispatch:
+
+permissions:
+ contents: write
+ pages: write
+ id-token: write
+
+concurrency:
+ group: release
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ outputs:
+ version: ${{ steps.version.outputs.version }}
+ steps:
+ - uses: actions/checkout@v4
+ # Both versions are installed. The last one listed (3.14) is the default `python`
+ # and runs the repository scripts; ESPHome runs in a 3.13 venv.
+ - uses: actions/setup-python@v5
+ with:
+ python-version: |
+ 3.13
+ 3.14
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "24"
+ cache: npm
+ cache-dependency-path: custom_components/ha_controller/frontend/package-lock.json
+ - name: Read the version
+ id: version
+ run: |
+ version=$(python -c "import json; print(json.load(open('custom_components/ha_controller/manifest.json'))['version'])")
+ echo "version=$version" >> "$GITHUB_OUTPUT"
+ - name: Check the repository version
+ run: python .github/scripts/versioning.py check
+ - name: Check the tag matches the version
+ if: github.ref_type == 'tag'
+ run: python .github/scripts/versioning.py check --tag "$GITHUB_REF_NAME"
+ - name: Build the panel
+ run: |
+ npm --prefix custom_components/ha_controller/frontend ci
+ npm --prefix custom_components/ha_controller/frontend run build
+ - name: Package the integration
+ run: python .github/scripts/package_integration.py --out dist/ha_controller.zip
+ - name: Install ESPHome
+ run: |
+ python3.13 -m venv esphome/.venv
+ esphome/.venv/bin/pip install -r esphome/requirements.txt
+ - name: Compile the firmware
+ run: esphome/.venv/bin/esphome compile esphome/ha-controller.yaml
+ - name: Collect the firmware
+ run: >
+ python .github/scripts/collect_firmware.py
+ --build-dir esphome/.esphome/build/ha-controller/build
+ --version "${{ steps.version.outputs.version }}"
+ --out dist
+ - uses: actions/upload-artifact@v4
+ with:
+ name: dist
+ path: dist
+
+ pages:
+ needs: build
+ if: github.ref_type == 'tag'
+ runs-on: ubuntu-latest
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.14"
+ - uses: actions/download-artifact@v4
+ with:
+ name: dist
+ path: dist
+ - name: Add the firmware of this version
+ run: |
+ mkdir -p "releases/${{ needs.build.outputs.version }}"
+ cp dist/ha-controller-* "releases/${{ needs.build.outputs.version }}/"
+ - name: Download the firmware of every earlier release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ run: |
+ for tag in $(gh release list --limit 200 --json tagName -q '.[].tagName'); do
+ if [ "$tag" = "$GITHUB_REF_NAME" ]; then continue; fi
+ if ! gh release download "$tag" -p 'ha-controller-*' -D "releases/${tag#v}"; then
+ echo "No firmware downloaded for $tag, skipping it"
+ rm -rf "releases/${tag#v}"
+ fi
+ done
+ - name: Build the site
+ run: >
+ python .github/scripts/build_pages.py --web esphome/web --releases releases
+ --latest "${{ needs.build.outputs.version }}" --out site
+ - uses: actions/configure-pages@v5
+ - uses: actions/upload-pages-artifact@v3
+ with:
+ path: site
+ - id: deployment
+ uses: actions/deploy-pages@v4
+
+ release:
+ needs: [build, pages]
+ if: github.ref_type == 'tag'
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ name: dist
+ path: dist
+ - name: Create the GitHub release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ run: >
+ gh release create "$GITHUB_REF_NAME" dist/*
+ --title "$GITHUB_REF_NAME" --generate-notes --verify-tag
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/.gitignore b/.gitignore
index 496ee2c..a95a7d0 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/
+esphome/.esphome/
+esphome/secrets.yaml
+build/
+dist/
+site/
+.superpowers/
+esphome/.gitignore
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..96be66d
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,3 @@
+{
+ "cmake.sourceDirectory": "/Users/kevin/Projects/HA-controller/esphome/tests"
+}
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
index 9999a74..6727480 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,29 @@
# 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).
+
+## Install
+
+1. Flash the firmware from the web installer: (Chrome or Edge).
+2. In HACS, add the custom repository `https://github.com/pyxel-dev/HA-controller` (type Integration) and install the same version.
+
+See [Getting started](docs/getting-started.md) for the full steps and 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/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..f988e92
--- /dev/null
+++ b/custom_components/ha_controller/__init__.py
@@ -0,0 +1,64 @@
+"""The HA Controller integration."""
+
+from homeassistant.config_entries import ConfigEntry
+from homeassistant.const import Platform
+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 .panel import async_register_panel, async_unregister_panel
+from .store import LayoutStore
+from .websocket import async_register_websocket
+
+CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
+
+PLATFORMS = [Platform.UPDATE]
+
+type HaControllerConfigEntry = ConfigEntry[ScreenController]
+
+
+async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
+ """Set up the integration."""
+ async_register_websocket(hass)
+ return True
+
+
+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
+ await async_register_panel(hass, controller.integration_version)
+ await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
+ return True
+
+
+async def async_unload_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> bool:
+ """Unload one screen."""
+ if not await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
+ return False
+ 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
+
+
+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/brand/icon.png b/custom_components/ha_controller/brand/icon.png
new file mode 100644
index 0000000..b846736
Binary files /dev/null and b/custom_components/ha_controller/brand/icon.png differ
diff --git a/custom_components/ha_controller/brand/icon@2x.png b/custom_components/ha_controller/brand/icon@2x.png
new file mode 100644
index 0000000..6f63e28
Binary files /dev/null and b/custom_components/ha_controller/brand/icon@2x.png differ
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/config_flow.py b/custom_components/ha_controller/config_flow.py
new file mode 100644
index 0000000..3287682
--- /dev/null
+++ b/custom_components/ha_controller/config_flow.py
@@ -0,0 +1,82 @@
+"""Config flow for HA Controller."""
+
+from typing import Any
+
+import voluptuous as vol
+from homeassistant.config_entries import (
+ ConfigEntry,
+ ConfigFlow,
+ ConfigFlowResult,
+ OptionsFlow,
+)
+from homeassistant.core import callback
+from homeassistant.helpers import device_registry as dr
+from homeassistant.helpers import selector
+
+from .const import CONF_AUTO_UPDATE, 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
+
+ @staticmethod
+ @callback
+ def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlowHandler:
+ return OptionsFlowHandler()
+
+ 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
+ )
+
+
+class OptionsFlowHandler(OptionsFlow):
+ """Options of one screen."""
+
+ async def async_step_init(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
+ if user_input is not None:
+ return self.async_create_entry(data=user_input)
+ current = self.config_entry.options.get(CONF_AUTO_UPDATE, True)
+ return self.async_show_form(
+ step_id="init",
+ data_schema=vol.Schema({vol.Required(CONF_AUTO_UPDATE, default=current): bool}),
+ )
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/controller.py b/custom_components/ha_controller/controller.py
new file mode 100644
index 0000000..9e9191d
--- /dev/null
+++ b/custom_components/ha_controller/controller.py
@@ -0,0 +1,410 @@
+"""Per-screen controller: owns the layout and keeps the screen in sync."""
+
+import asyncio
+import logging
+from collections.abc import Callable, Collection, Mapping
+from dataclasses import dataclass
+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
+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_INSTALL_FIRMWARE,
+ ACTION_SET_LAYOUT,
+ ACTION_SET_STATES,
+ AUTO_UPDATE_RETRY,
+ CONF_AUTO_UPDATE,
+ CONF_DEVICE_ID,
+ EVENT_CONTROL,
+ EVENT_HELLO,
+ INSTALL_TIMEOUT,
+ MAX_PAYLOAD_BYTES,
+ ONLINE_TIMEOUT,
+ PROTOCOL_VERSION,
+ PUSH_RETRY,
+ STATE_COALESCE_SECONDS,
+)
+from .controls import resolve_control
+from .firmware import firmware_urls, is_release_version
+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
+
+
+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__(format_layout_errors(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_control: CALLBACK_TYPE | None = None
+ self._unsub_states: CALLBACK_TYPE | None = None
+ self._cancel_flush: CALLBACK_TYPE | None = None
+ self._pending: set[str] = set()
+ self._first_hello_seen = False
+ self._install_in_progress = False
+ self._install_target: str | None = None
+ self._install_waiter: asyncio.Future[None] | None = None
+ self._auto_attempts: dict[str, datetime] = {}
+ self._auto_tasks: set[asyncio.Task[None]] = 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
+
+ @property
+ def install_in_progress(self) -> bool:
+ return self._install_in_progress
+
+ 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,
+ format_layout_errors(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
+ )
+ 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()
+ self._cancel_flush = None
+ self._pending.clear()
+ for task in list(self._auto_tasks):
+ task.cancel()
+ if self._install_waiter is not None and not self._install_waiter.done():
+ self._install_waiter.set_exception(HomeAssistantError("The integration was unloaded."))
+ 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(),
+ )
+ version = self._device.version
+ if (
+ self._install_waiter is not None
+ and not self._install_waiter.done()
+ and version == self._install_target
+ ):
+ self._install_waiter.set_result(None)
+ self._notify_listeners()
+ self._maybe_auto_update()
+ if self._device.protocol != PROTOCOL_VERSION:
+ return
+ 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()
+ elif connected:
+ await self.async_push_states()
+
+ def _maybe_auto_update(self) -> None:
+ """Start an automatic firmware install when the screen runs another version."""
+ version = self._integration_version
+ if (
+ not self.entry.options.get(CONF_AUTO_UPDATE, True)
+ or not is_release_version(version)
+ or self._device.version is None
+ or self._device.version == version
+ or self._install_in_progress
+ ):
+ return
+ now = dt_util.utcnow()
+ last = self._auto_attempts.get(version)
+ if last is not None and now - last < AUTO_UPDATE_RETRY:
+ return
+ self._auto_attempts[version] = now
+ task = self.hass.async_create_background_task(
+ self._async_auto_install(version), f"ha_controller auto update {self.entry.title}"
+ )
+ self._auto_tasks.add(task)
+ task.add_done_callback(self._auto_tasks.discard)
+
+ async def _async_auto_install(self, version: str) -> None:
+ try:
+ await self.async_install_firmware(version)
+ except HomeAssistantError as err:
+ _LOGGER.warning("Automatic firmware update of %s failed: %s", self.entry.title, err)
+
+ async def async_install_firmware(self, version: str) -> None:
+ """Install a firmware version and wait until the screen reports it."""
+ if not self._device.online():
+ raise HomeAssistantError("The screen is offline.")
+ if self._install_in_progress:
+ raise HomeAssistantError("A firmware update is already running.")
+ self._install_in_progress = True
+ self._install_target = version
+ waiter = self.hass.loop.create_future()
+ self._install_waiter = waiter
+ self._notify_listeners()
+ try:
+ url, md5_url = firmware_urls(version)
+ if not await self.async_call_device(
+ ACTION_INSTALL_FIRMWARE, {"url": url, "md5_url": md5_url}
+ ):
+ raise HomeAssistantError("The screen did not accept the firmware update.")
+ try:
+ async with asyncio.timeout(INSTALL_TIMEOUT):
+ await waiter
+ except TimeoutError:
+ raise HomeAssistantError(
+ f"Firmware update to {version} did not complete."
+ ) from None
+ finally:
+ self._install_in_progress = False
+ self._install_target = None
+ self._install_waiter = None
+ self._notify_listeners()
+
+ def _notify_listeners(self) -> None:
+ for cb in list(self._listeners):
+ cb()
+
+ 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
+ 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, vol.Invalid) 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/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/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/custom_components/ha_controller/firmware.py b/custom_components/ha_controller/firmware.py
new file mode 100644
index 0000000..0c560b8
--- /dev/null
+++ b/custom_components/ha_controller/firmware.py
@@ -0,0 +1,18 @@
+"""Firmware locations and version rules."""
+
+import re
+
+from .const import FIRMWARE_BASE_URL
+
+_RELEASE = re.compile(r"^\d+\.\d+\.\d+$")
+
+
+def firmware_urls(version: str) -> tuple[str, str]:
+ """Return the OTA image URL and its MD5 URL for a version."""
+ url = f"{FIRMWARE_BASE_URL}/{version}/ha-controller.ota.bin"
+ return url, f"{url}.md5"
+
+
+def is_release_version(version: str) -> bool:
+ """Return True for a plain release version such as 1.2.3."""
+ return _RELEASE.match(version) is not None
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/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/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-block-editor.ts b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts
new file mode 100644
index 0000000..3b34ce6
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts
@@ -0,0 +1,260 @@
+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 {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, Hass, Item, ItemKind, Layout} from "../types";
+
+
+/** 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``;
+ }
+
+ 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`
+ ${UI.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`
+ ${repeat(
+ items,
+ (item) => item.id,
+ (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..c7dc744
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts
@@ -0,0 +1,62 @@
+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. */
+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..6a53f77
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/components/hc-entity-input.ts
@@ -0,0 +1,64 @@
+import {LitElement, css, html} from "lit";
+import {property} from "lit/decorators.js";
+import {defineElement} from "../define";
+import {UI} from "../messages";
+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())}
+ />
+ `;
+ }
+
+ 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-grid.ts b/custom_components/ha_controller/frontend/src/components/hc-grid.ts
new file mode 100644
index 0000000..ec2fb99
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/components/hc-grid.ts
@@ -0,0 +1,136 @@
+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";
+
+/** Block map: x grows to the right, y grows downwards, like navigation on the screen. */
+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;
+ }
+ /* 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 {
+ --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 {
+ --ring-select: 0 0 0 3px var(--primary-color, #03a9f4);
+ }
+ .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;
+ 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}));
+ }
+}
+
+defineElement("hc-grid", HcGrid);
+
+declare global {
+ interface HTMLElementTagNameMap {
+ "hc-grid": HcGrid;
+ }
+}
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..a78dfaa
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/components/hc-item-editor.ts
@@ -0,0 +1,147 @@
+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 {FONT_SIZE_LABEL, FONT_SIZE_ORDER, ITEM_KIND_LABEL, UI} from "../messages";
+import type {FontSize, Hass, Item} from "../types";
+
+/** 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`
+
+ ${ITEM_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..9e9405f
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/components/hc-preview.ts
@@ -0,0 +1,81 @@
+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"};
+
+/** 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 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;
+ }
+
+ 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 = UI.previewBattery; break;
+ case "brightness": text = UI.previewBrightness; 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/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/src/ha-controller-panel.ts b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts
new file mode 100644
index 0000000..56acd08
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts
@@ -0,0 +1,391 @@
+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.
+ 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);
+ }
+
+ /** 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 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 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;
+ }
+
+ 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;
+ const entryId = this.entryId;
+ this.saving = true;
+ try {
+ 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) {
+ if (entryId === this.entryId) 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 locked = this.dirty || this.saving;
+ const canSave = this.dirty && errors.length === 0 && !this.saving;
+ return html`
+
+ ${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}
+
+
+ ) => 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
new file mode 100644
index 0000000..20af4fe
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/messages.ts
@@ -0,0 +1,94 @@
+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.",
+ 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.",
+};
+
+/** 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",
+ addBlock: "Add block",
+ title: "HA Controller",
+ screenSelect: "Screen",
+ revert: "Revert",
+ save: "Save",
+ switchBlocked: "Save or revert your changes first.",
+ 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/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
new file mode 100644
index 0000000..6bce298
--- /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("\uFE0F", "");
+}
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..0baf3e7
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/model/grid.ts
@@ -0,0 +1,66 @@
+import type {Block, Cell, Layout} from "../types";
+import {COORD_LIMIT, MAX_BLOCKS} from "./limits";
+
+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 >= 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) > COORD_LIMIT || Math.abs(y) > COORD_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/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
new file mode 100644
index 0000000..e1113c6
--- /dev/null
+++ b/custom_components/ha_controller/frontend/src/model/validate.ts
@@ -0,0 +1,153 @@
+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_NAME_LEN = 32;
+const MAX_TEXT_LEN = 64;
+const MAX_ATTRIBUTE_LEN = 64;
+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..d3c4c87
--- /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;
+}
+
+/** One screen as listed by `ha_controller/screens` (spec section 8). */
+export interface ScreenInfo {
+ entry_id: string;
+ title: string;
+ device_id: string;
+ online: boolean;
+ firmware_version: string | null;
+ integration_version: string;
+ protocol_ok: boolean | null;
+ revision: string;
+ device_revision: string | null;
+}
+
+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/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/dom.ts b/custom_components/ha_controller/frontend/test/dom.ts
new file mode 100644
index 0000000..91516b3
--- /dev/null
+++ b/custom_components/ha_controller/frontend/test/dom.ts
@@ -0,0 +1,27 @@
+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}));
+}
+
+export function cleanup(): void {
+ document.body.innerHTML = "";
+}
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("💡");
+ });
+});
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/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-grid.test.ts b/custom_components/ha_controller/frontend/test/hc-grid.test.ts
new file mode 100644
index 0000000..db8d454
--- /dev/null
+++ b/custom_components/ha_controller/frontend/test/hc-grid.test.ts
@@ -0,0 +1,86 @@
+import {html} from "lit";
+import {afterEach, describe, expect, it} from "vitest";
+import "../src/components/hc-grid";
+import {all, cleanup, mount, nextEvent, one} from "./dom";
+import {defineElement} from "../src/define";
+import {validLayouts} from "./fixtures";
+
+afterEach(cleanup);
+
+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(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);
+ });
+
+ 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);
+ });
+
+ 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();
+ });
+});
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");
+ });
+});
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..9e6d52d
--- /dev/null
+++ b/custom_components/ha_controller/frontend/test/panel.test.ts
@@ -0,0 +1,291 @@
+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();
+ });
+
+ describe("screen state", () => {
+ const twoScreens = () => {
+ const {hass, callWS, real} = spied();
+ const info = (id: string, title: string) => ({
+ entry_id: id,
+ title,
+ device_id: `d-${id}`,
+ online: true,
+ firmware_version: "0.1.0",
+ integration_version: "0.1.0",
+ protocol_ok: true,
+ revision: "r1",
+ device_revision: "r1",
+ });
+ return {hass, callWS, real, info};
+ };
+
+ it("drops a save result when the screen changed meanwhile", async () => {
+ const {hass, callWS, real, info} = twoScreens();
+ let resolveSave: (v: unknown) => void = () => undefined;
+ callWS.mockImplementation((msg: {type: string; entry_id?: string}) => {
+ if (msg.type === "ha_controller/screens") return Promise.resolve({screens: [info("a", "A"), info("b", "B")]});
+ if (msg.type === "ha_controller/layout/save") return new Promise((r) => (resolveSave = r));
+ return real({...msg, type: msg.type});
+ });
+ const el = await open(hass);
+ await addBlockRight(el);
+ void (el as unknown as {onSave: () => Promise}).onSave();
+ await settle(el);
+ await (el as unknown as {selectScreen: (id: string) => Promise}).selectScreen("b");
+ await settle(el);
+ resolveSave({revision: "r2", pushed: true});
+ await settle(el);
+ expect(saveButton(el).disabled).toBe(true);
+ expect(one(el, ".notice")).toBeNull();
+ await click(el, one(el, "button.revert")!);
+ expect(blocks(el)).toHaveLength(4);
+ });
+
+ it("loads the layout on a later refresh when the first load failed", async () => {
+ vi.useFakeTimers();
+ const {hass, callWS, real} = spied();
+ let first = true;
+ callWS.mockImplementation((msg: {type: string}) => {
+ if (msg.type === "ha_controller/layout/get" && first) {
+ first = false;
+ return Promise.reject({code: "boom", message: "boom"});
+ }
+ return real(msg);
+ });
+ const el = await open(hass);
+ expect(one(el, "hc-grid")).toBeNull();
+ await vi.advanceTimersByTimeAsync(10_000);
+ await settle(el);
+ expect(blocks(el)).toHaveLength(4);
+ });
+
+ it("selects a screen that appears after an empty first load", async () => {
+ vi.useFakeTimers();
+ const {hass, callWS, real} = spied();
+ let empty = true;
+ callWS.mockImplementation((msg: {type: string}) =>
+ msg.type === "ha_controller/screens" && empty ? Promise.resolve({screens: []}) : real(msg),
+ );
+ const el = await open(hass);
+ expect(one(el, ".empty")).not.toBeNull();
+ empty = false;
+ await vi.advanceTimersByTimeAsync(10_000);
+ await settle(el);
+ expect(blocks(el)).toHaveLength(4);
+ });
+
+ it("disables the screen select while dirty", async () => {
+ const {hass, callWS, real, info} = twoScreens();
+ callWS.mockImplementation((msg: {type: string}) =>
+ msg.type === "ha_controller/screens" ? Promise.resolve({screens: [info("a", "A"), info("b", "B")]}) : real(msg),
+ );
+ const el = await open(hass);
+ const select = () => one(el, "select")!;
+ expect(select().disabled).toBe(false);
+ await addBlockRight(el);
+ expect(select().disabled).toBe(true);
+ expect(select().title).toBe("Save or revert your changes first.");
+ await click(el, one(el, "button.revert")!);
+ expect(select().disabled).toBe(false);
+ });
+
+ it("puts the select back on the loaded screen when a switch fails", async () => {
+ const {hass, callWS, real, info} = twoScreens();
+ callWS.mockImplementation((msg: {type: string; entry_id?: string}) => {
+ if (msg.type === "ha_controller/screens") return Promise.resolve({screens: [info("a", "A"), info("b", "B")]});
+ if (msg.type === "ha_controller/layout/get" && msg.entry_id === "b") return Promise.reject({message: "nope"});
+ return real(msg);
+ });
+ const el = await open(hass);
+ const select = one(el, "select")!;
+ expect(select.value).toBe("a");
+ select.value = "b";
+ select.dispatchEvent(new Event("change"));
+ await settle(el);
+ expect(select.value).toBe("a");
+ expect(one(el, ".notice")!.textContent).toContain("nope");
+ expect(blocks(el)).toHaveLength(4);
+ });
+ });
+});
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"},
+});
diff --git a/custom_components/ha_controller/layout.py b/custom_components/ha_controller/layout.py
new file mode 100644
index 0000000..f7811c2
--- /dev/null
+++ b/custom_components/ha_controller/layout.py
@@ -0,0 +1,257 @@
+"""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 _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 _is_entity_id(entity_id):
+ 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 _is_entity_id(entity_id):
+ 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/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/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/services.yaml b/custom_components/ha_controller/services.yaml
new file mode 100644
index 0000000..a0e86ff
--- /dev/null
+++ b/custom_components/ha_controller/services.yaml
@@ -0,0 +1,2 @@
+# This integration registers no services of its own.
+{}
diff --git a/custom_components/ha_controller/states.py b/custom_components/ha_controller/states.py
new file mode 100644
index 0000000..fc825bf
--- /dev/null
+++ b/custom_components/ha_controller/states.py
@@ -0,0 +1,127 @@
+"""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 MAX_TEXT_LEN, STATE_CHUNK_BYTES
+
+MISSING_TEXT = "—"
+_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_LEN]
+ 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_LEN]
+
+
+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/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/strings.json b/custom_components/ha_controller/strings.json
new file mode 100644
index 0000000..ce4e2a8
--- /dev/null
+++ b/custom_components/ha_controller/strings.json
@@ -0,0 +1,37 @@
+{
+ "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."
+ }
+ },
+ "entity": {
+ "update": {
+ "firmware": {
+ "name": "HA Controller firmware"
+ }
+ }
+ },
+ "options": {
+ "step": {
+ "init": {
+ "title": "HA Controller options",
+ "description": "Installs the firmware that matches this integration's version whenever the screen reports a different one.",
+ "data": {
+ "auto_update": "Update the screen firmware automatically"
+ }
+ }
+ }
+ }
+}
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..c8b487a
--- /dev/null
+++ b/custom_components/ha_controller/tests/helpers.py
@@ -0,0 +1,63 @@
+"""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"
+VERSION = json.loads((Path(__file__).resolve().parents[1] / "manifest.json").read_text())["version"]
+
+
+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": VERSION,
+ "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_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
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/tests/test_controller.py b/custom_components/ha_controller/tests/test_controller.py
new file mode 100644
index 0000000..07f0cea
--- /dev/null
+++ b/custom_components/ha_controller/tests/test_controller.py
@@ -0,0 +1,346 @@
+"""Tests for the layout store and the screen sync engine."""
+
+import json
+from datetime import timedelta
+
+import voluptuous as vol
+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, VERSION, 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") # 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)
+ 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")
+ 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})
+ 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")
+ states.clear()
+ 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": VERSION,
+ "integration_version": VERSION,
+ "protocol_ok": True,
+ "revision": REFERENCE_REV,
+ "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 == []
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
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..2ece638
--- /dev/null
+++ b/custom_components/ha_controller/tests/test_layout.py
@@ -0,0 +1,138 @@
+"""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"))
+
+
+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 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)
+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:
+ with EMOJI_FILE.open(encoding="utf-8") as handle:
+ assert EMOJI == frozenset(json.load(handle))
+ assert "💡" in EMOJI
+
+
+async def test_async_load_emoji(hass) -> None:
+ assert await async_load_emoji(hass) == EMOJI
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..1379b8a
--- /dev/null
+++ b/custom_components/ha_controller/tests/test_panel.py
@@ -0,0 +1,73 @@
+"""Tests for the sidebar panel registration."""
+
+from pathlib import Path
+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."""
+ with patch(
+ "custom_components.ha_controller.panel.BUNDLE", Path("/nonexistent/ha-controller-panel.js")
+ ):
+ entry = await setup_screen(hass, await register_screen(hass))
+
+ assert entry.state.name == "LOADED"
+ assert "bundle" in caplog.text
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..17d6a92
--- /dev/null
+++ b/custom_components/ha_controller/tests/test_states.py
@@ -0,0 +1,101 @@
+"""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, US_CUSTOMARY_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]]
+
+
+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"}]
diff --git a/custom_components/ha_controller/tests/test_update.py b/custom_components/ha_controller/tests/test_update.py
new file mode 100644
index 0000000..76bba05
--- /dev/null
+++ b/custom_components/ha_controller/tests/test_update.py
@@ -0,0 +1,193 @@
+"""Tests for the firmware update entity, automatic updates and the options flow."""
+
+import asyncio
+from datetime import timedelta
+
+import pytest
+from homeassistant.data_entry_flow import FlowResultType
+from homeassistant.exceptions import HomeAssistantError
+from pytest_homeassistant_custom_component.common import (
+ async_fire_time_changed,
+ async_mock_service,
+)
+
+from custom_components.ha_controller.const import CONF_AUTO_UPDATE
+from custom_components.ha_controller.firmware import firmware_urls, is_release_version
+
+from .helpers import VERSION, hello, register_screen, setup_screen
+
+ENTITY = "update.mock_title_ha_controller_firmware"
+URL = f"https://pyxel-dev.github.io/HA-controller/firmware/{VERSION}/ha-controller.ota.bin"
+
+
+def test_firmware_urls():
+ assert firmware_urls(VERSION) == (URL, URL + ".md5")
+
+
+def test_is_release_version():
+ assert is_release_version("1.2.3")
+ assert not is_release_version("0.2.0.dev0")
+ assert not is_release_version("0.2.0-rc1")
+
+
+async def start(hass, *, auto_update=False):
+ installs = async_mock_service(hass, "esphome", "ha_controller_aabbcc_install_firmware")
+ async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_layout")
+ async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_states")
+ device = await register_screen(hass)
+ entry = await setup_screen(hass, device)
+ hass.config_entries.async_update_entry(entry, options={CONF_AUTO_UPDATE: auto_update})
+ await hass.async_block_till_done()
+ return device, entry, installs
+
+
+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 start_install(hass):
+ """Start the install service call and let it reach its wait for the hello."""
+ task = hass.async_create_background_task(
+ hass.services.async_call("update", "install", {"entity_id": ENTITY}, blocking=True),
+ "test install",
+ )
+ for _ in range(20):
+ await asyncio.sleep(0)
+ return task
+
+
+async def test_unknown_before_first_hello(hass):
+ await start(hass)
+ assert hass.states.get(ENTITY).state == "unknown"
+
+
+async def test_update_entity_reports_versions(hass):
+ device, _, _ = await start(hass)
+ await send_hello(hass, device, version="0.0.9")
+ state = hass.states.get(ENTITY)
+ assert state.state == "on"
+ assert state.attributes["installed_version"] == "0.0.9"
+ assert state.attributes["latest_version"] == VERSION
+ assert state.attributes["release_url"].endswith(f"/tag/v{VERSION}")
+
+
+async def test_update_entity_off_when_versions_match(hass):
+ device, _, _ = await start(hass)
+ await send_hello(hass, device, version=VERSION)
+ assert hass.states.get(ENTITY).state == "off"
+
+
+async def test_newer_firmware_is_offered_as_update(hass):
+ device, _, _ = await start(hass)
+ await send_hello(hass, device, version="999.0.0")
+ assert hass.states.get(ENTITY).state == "on"
+
+
+async def test_install_calls_device_and_completes_on_hello(hass):
+ device, _, installs = await start(hass)
+ await send_hello(hass, device, version="0.0.9")
+ task = await start_install(hass)
+ assert len(installs) == 1
+ assert installs[0].data == {"url": URL, "md5_url": URL + ".md5"}
+ assert hass.states.get(ENTITY).attributes["in_progress"] is True
+ await send_hello(hass, device, version=VERSION)
+ await task
+ state = hass.states.get(ENTITY)
+ assert state.state == "off"
+ assert state.attributes["in_progress"] is False
+
+
+async def test_install_times_out(hass, freezer):
+ device, entry, _ = await start(hass)
+ await send_hello(hass, device, version="0.0.9")
+ task = await start_install(hass)
+ assert entry.runtime_data.install_in_progress
+ freezer.tick(timedelta(seconds=301))
+ async_fire_time_changed(hass)
+ await hass.async_block_till_done()
+ with pytest.raises(HomeAssistantError, match="did not complete"):
+ await task
+ assert not entry.runtime_data.install_in_progress
+ assert hass.states.get(ENTITY).attributes["in_progress"] is False
+
+
+async def test_install_when_offline_raises(hass):
+ _, entry, installs = await start(hass)
+ with pytest.raises(HomeAssistantError, match="offline"):
+ await entry.runtime_data.async_install_firmware(VERSION)
+ assert installs == []
+
+
+async def test_install_while_in_progress_raises(hass):
+ device, entry, installs = await start(hass)
+ await send_hello(hass, device, version="0.0.9")
+ task = await start_install(hass)
+ with pytest.raises(HomeAssistantError, match="already running"):
+ await entry.runtime_data.async_install_firmware(VERSION)
+ assert len(installs) == 1
+ await send_hello(hass, device, version=VERSION)
+ await task
+
+
+async def test_auto_update_installs_at_most_once_per_hour(hass, freezer):
+ device, entry, installs = await start(hass, auto_update=True)
+ await send_hello(hass, device, version="0.0.9")
+ assert len(installs) == 1
+ freezer.tick(timedelta(seconds=301))
+ async_fire_time_changed(hass) # the first install gives up waiting
+ await hass.async_block_till_done()
+ assert not entry.runtime_data.install_in_progress
+ freezer.tick(timedelta(seconds=1))
+ await send_hello(hass, device, version="0.0.9") # inside the one hour window
+ assert len(installs) == 1
+ freezer.tick(timedelta(seconds=3601 - 302))
+ await send_hello(hass, device, version="0.0.9") # 3601 s after the first attempt
+ assert len(installs) == 2
+ await send_hello(hass, device, version=VERSION)
+
+
+async def test_auto_update_ignores_protocol_mismatch(hass):
+ device, _, installs = await start(hass, auto_update=True)
+ await send_hello(hass, device, version="0.0.9", protocol="2")
+ assert len(installs) == 1
+ await send_hello(hass, device, version=VERSION, protocol="2")
+
+
+async def test_unload_ends_pending_install(hass):
+ device, entry, installs = await start(hass)
+ await send_hello(hass, device, version="0.0.9")
+ task = await start_install(hass)
+ controller = entry.runtime_data
+ assert controller.install_in_progress
+ assert await hass.config_entries.async_unload(entry.entry_id)
+ await hass.async_block_till_done()
+ assert task.done() # ended without waiting for the 300 s timeout
+ with pytest.raises(HomeAssistantError, match="unloaded"):
+ await task
+ assert not controller.install_in_progress
+ assert controller._install_waiter is None
+
+
+async def test_auto_update_disabled_by_option(hass):
+ device, _, installs = await start(hass, auto_update=False)
+ await send_hello(hass, device, version="0.0.9")
+ assert installs == []
+
+
+async def test_auto_update_skipped_for_dev_versions(hass):
+ device, entry, installs = await start(hass, auto_update=True)
+ entry.runtime_data._integration_version = "0.2.0.dev0"
+ await send_hello(hass, device, version="0.0.9")
+ assert installs == []
+
+
+async def test_options_flow_toggles_auto_update(hass):
+ _, entry, _ = await start(hass, auto_update=True)
+ result = await hass.config_entries.options.async_init(entry.entry_id)
+ assert result["type"] is FlowResultType.FORM and result["step_id"] == "init"
+ result = await hass.config_entries.options.async_configure(
+ result["flow_id"], {CONF_AUTO_UPDATE: False}
+ )
+ assert result["type"] is FlowResultType.CREATE_ENTRY
+ assert entry.options[CONF_AUTO_UPDATE] is False
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..210577d
--- /dev/null
+++ b/custom_components/ha_controller/tests/test_websocket.py
@@ -0,0 +1,145 @@
+"""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/translations/en.json b/custom_components/ha_controller/translations/en.json
new file mode 100644
index 0000000..ce4e2a8
--- /dev/null
+++ b/custom_components/ha_controller/translations/en.json
@@ -0,0 +1,37 @@
+{
+ "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."
+ }
+ },
+ "entity": {
+ "update": {
+ "firmware": {
+ "name": "HA Controller firmware"
+ }
+ }
+ },
+ "options": {
+ "step": {
+ "init": {
+ "title": "HA Controller options",
+ "description": "Installs the firmware that matches this integration's version whenever the screen reports a different one.",
+ "data": {
+ "auto_update": "Update the screen firmware automatically"
+ }
+ }
+ }
+ }
+}
diff --git a/custom_components/ha_controller/update.py b/custom_components/ha_controller/update.py
new file mode 100644
index 0000000..eef1a2c
--- /dev/null
+++ b/custom_components/ha_controller/update.py
@@ -0,0 +1,69 @@
+"""Firmware update entity of a screen."""
+
+from homeassistant.components.update import UpdateEntity, UpdateEntityFeature
+from homeassistant.core import HomeAssistant, callback
+from homeassistant.helpers import device_registry as dr
+from homeassistant.helpers.device_registry import DeviceInfo
+from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
+
+from . import HaControllerConfigEntry
+from .const import RELEASE_URL
+from .controller import ScreenController
+
+
+async def async_setup_entry(
+ hass: HomeAssistant,
+ entry: HaControllerConfigEntry,
+ async_add_entities: AddConfigEntryEntitiesCallback,
+) -> None:
+ """Add the firmware update entity of a screen."""
+ controller = entry.runtime_data
+ device = dr.async_get(hass).async_get(controller.device_id)
+ if device is None:
+ return
+ async_add_entities([FirmwareUpdateEntity(controller, device.connections)])
+
+
+class FirmwareUpdateEntity(UpdateEntity):
+ """Keeps the screen firmware on the integration version."""
+
+ _attr_has_entity_name = True
+ _attr_translation_key = "firmware"
+ _attr_title = "HA Controller"
+ _attr_supported_features = UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS
+ _attr_should_poll = False
+
+ def __init__(self, controller: ScreenController, connections: set[tuple[str, str]]) -> None:
+ self._controller = controller
+ self._attr_unique_id = f"{controller.device_id}-firmware"
+ self._attr_device_info = DeviceInfo(connections=connections)
+
+ @property
+ def installed_version(self) -> str | None:
+ return self._controller.device.version
+
+ @property
+ def latest_version(self) -> str:
+ return self._controller.integration_version
+
+ @property
+ def release_url(self) -> str:
+ return RELEASE_URL.format(version=self.latest_version)
+
+ @property
+ def in_progress(self) -> bool:
+ return self._controller.install_in_progress
+
+ def version_is_newer(self, latest_version: str, installed_version: str) -> bool:
+ """Offer any different version, so a downgrade is shown as an update."""
+ return latest_version != installed_version
+
+ async def async_install(self, version: str | None, backup: bool, **kwargs: object) -> None:
+ await self._controller.async_install_firmware(self.latest_version)
+
+ async def async_added_to_hass(self) -> None:
+ self.async_on_remove(self._controller.async_add_listener(self._handle_update))
+
+ @callback
+ def _handle_update(self) -> None:
+ self.async_write_ha_state()
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})
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/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..cb6af5d
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,11 @@
+# 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/`.
+- [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.
+- [Hardware](hardware.md): the board, pins, power, performance settings and enclosures.
+- [Getting started](getting-started.md): installing the firmware and the integration.
+- [Updates](updates.md): how the integration and the firmware are updated.
+- [Releasing](releasing.md): cutting a release.
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..840f552
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,60 @@
+# 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** (`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** (`.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. 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
+
+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
+
+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) |
diff --git a/docs/configuration.md b/docs/configuration.md
new file mode 100644
index 0000000..3d15837
--- /dev/null
+++ b/docs/configuration.md
@@ -0,0 +1,53 @@
+# 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 supported emoji; only emoji from that set can be used
+- 24 KB (24,576 bytes) for the whole layout once compiled for the screen. A layout above that limit is refused when you save it
diff --git a/docs/development.md b/docs/development.md
new file mode 100644
index 0000000..89e69eb
--- /dev/null
+++ b/docs/development.md
@@ -0,0 +1,159 @@
+# Development
+
+## Prerequisites
+
+- Python 3.14 (integration tests and repository checks).
+- Node 24 (panel build).
+- Firmware: a Python 3.13 venv with ESPHome, CMake and SDL2 (see [Firmware](#firmware)).
+
+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
+
+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
+
+The firmware is ESPHome with LVGL, in `esphome/`. The hardware is described in [hardware.md](hardware.md).
+
+### Prerequisites
+
+- Python 3.13 (CI uses 3.13; ESPHome is pinned in `esphome/requirements.txt`).
+- CMake and a C++ compiler for the host tests.
+- SDL2 (`brew install sdl2` or `sudo apt-get install libsdl2-dev`) for the simulator.
+
+```bash
+python3.13 -m venv esphome/.venv
+esphome/.venv/bin/pip install -r esphome/requirements.txt
+```
+
+### Commands
+
+Run these from the repository root:
+
+```bash
+# Host tests for the pure C++ logic
+cmake -S esphome/tests -B esphome/tests/build
+cmake --build esphome/tests/build
+ctest --test-dir esphome/tests/build --output-on-failure
+
+# Compile the device and the simulator configs
+esphome/.venv/bin/esphome compile esphome/ha-controller.yaml
+esphome/.venv/bin/esphome compile esphome/simulator.yaml
+
+# Flash the screen over USB-C (first flash, or when OTA is not possible)
+esphome/.venv/bin/esphome run esphome/ha-controller.yaml
+
+# Run the simulator (an SDL window on the development machine)
+esphome/.venv/bin/esphome run esphome/simulator.yaml
+```
+
+`esphome/secrets.yaml` must never be committed. ESPHome recreates `esphome/.gitignore` on every compile; it is git-ignored.
+
+### Connecting Home Assistant to the simulator
+
+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`.
+3. Add the HA Controller integration and pick "HA Controller Simulator".
+4. Within 5 s the simulator shows "No blocks yet". Developer tools › Events shows `esphome.ha_controller_hello` with the reasons `connected` and then `applied`.
+
+Edit the layout in the panel and the simulator follows. Mouse drags stand in for finger swipes. The simulator has no HTTP OTA, so `install_firmware` exists only in the device config.
+
+### Manual hardware checklist
+
+Plan 4 could not test these on the board. Run them in one go with the firmware flashed over USB-C and, where marked, the simulator connected to Home Assistant.
+
+**Display, touch and power** (device)
+
+- The round display shows "HA Controller", the version and 💡, centred.
+- Tapping near the top, right, bottom and left edges logs about `(233,5)`, `(460,233)`, `(233,460)` and `(5,233)`. Otherwise 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.
+
+**End to end with Home Assistant** (simulator)
+
+- The simulator shows "No blocks yet" within 5 s of the connection; the hello events show `connected` then `applied`.
+- In the panel, add three blocks and save. The simulator shows the start block's name on its background.
+- Heartbeat hellos arrive every 60 s with a revision equal to the panel's.
+
+**Navigation** (simulator, then device with a finger)
+
+Build the reference map in the panel: Kitchen start, Lights above, Hello World left, Bedroom below Hello World.
+
+- From Kitchen, a drag from the left edge to the right slides to Hello World.
+- From the top edge downwards slides to Lights.
+- From the right edge leftwards 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 edge hints match the neighbours.
+- Saving a layout from the panel while holding a drag shows the new layout cleanly, with no stuck half-page.
+- On the device, the slides look smooth (about 30 fps or better). If not, follow the tuning order in [hardware.md](hardware.md#performance-settings) and record the result there.
+
+**Controls** (simulator with Home Assistant, then device)
+
+- Light: the knob shows Home Assistant's brightness; dragging to about 30 % and releasing sets the light to 30 %; a centre tap toggles it; a brightness change in Home Assistant moves the knob within 1 s; incoming updates do not move the knob while dragging.
+- On/off-only light: a toggle button.
+- Climate: steps of 0.5 °C; release updates the target; `Now …` and the action are shown.
+- Custom block: text, emoji and the outdoor temperature are shown and follow sensor changes; the battery row shows `🔋 76 %`; the brightness slider changes `number.*_screen_brightness`.
+- Renamed entity: renaming a bound entity in Home Assistant shows `—` and `Unavailable` and disables its control.
+- Taps give immediate visual feedback.
+- On the device: repeat the light, climate and custom checks, the battery row shows the real level, the brightness slider dims the panel smoothly, and with the battery unplugged the row shows `🔋 — %` and nothing crashes.
+
+**Sleep** (simulator, then device)
+
+- Simulator: 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; a delay of 5 s in the panel sleeps after 5 s and `0` keeps the screen awake; a Home Assistant state change made while asleep is visible right after waking.
+- Device: the panel goes black after the delay; a tap on the knob area only wakes the screen, which then stays awake for the full delay; changing `Screen brightness` from Home Assistant while asleep keeps the panel dark and the new level shows on wake.
+- Watch for a one-frame flash of stale content on wake.
+
+**Over-the-air update** (device)
+
+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 the checksum 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. In Developer tools › Actions, call `esphome.ha_controller__install_firmware` with the LAN URLs of the `.bin` and the `.md5`. The screen shows "Updating firmware…", reboots, and the next hello carries `0.1.1`.
+4. Run it once while the screen sleeps: the screen must wake first.
+5. Repeat with a wrong `.md5`. The screen shows "Update failed" for 5 s, then the pages return.
+6. Revert `version.yaml`.
+
+Plain `http://` URLs are fine for the LAN test: `verify_ssl` only affects HTTPS.
diff --git a/docs/getting-started.md b/docs/getting-started.md
new file mode 100644
index 0000000..784730e
--- /dev/null
+++ b/docs/getting-started.md
@@ -0,0 +1,14 @@
+# Getting started
+
+1. **Hardware and enclosure.** You need a Waveshare ESP32-S3-Touch-AMOLED-1.75. Print an enclosure from the [3D models](../3D_models/) (see [Hardware](hardware.md)).
+2. **Flash the firmware.** Open in Chrome or Edge, connect the board over USB and click Install. Note the firmware version shown on the page.
+3. **Connect to Wi-Fi.** Use Improv in the installer, or join the `HA Controller` access point and use its captive portal.
+4. **Adopt the device.** In Home Assistant, the ESPHome device is discovered. Adopt it under Settings > Devices & services.
+5. **Install the integration.** 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, then restart Home Assistant.
+6. **Add the integration.** Go to Settings > Devices & services > Add integration > HA Controller, then pick the screen.
+7. **Open the panel.** Open HA Controller in the sidebar and design your screens (see [Configuration](configuration.md)).
+
+## Troubleshooting
+
+- **The screen stays on "Waiting for Home Assistant".** Check that the ESPHome device and the HA Controller entry both 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](updates.md).
diff --git a/docs/hardware.md b/docs/hardware.md
new file mode 100644
index 0000000..e651d78
--- /dev/null
+++ b/docs/hardware.md
@@ -0,0 +1,61 @@
+# Hardware
+
+The firmware targets the Waveshare ESP32-S3-Touch-AMOLED-1.75: an ESP32-S3R8 (8 MB octal PSRAM, 16 MB flash) with a 1.75" round AMOLED (466×466) and a capacitive touch panel, powered over USB-C or a LiPo battery.
+
+## Pins and buses
+
+| Item | Value |
+|---|---|
+| Display | CO5300 over QSPI. CS GPIO12, SCLK GPIO38, D0–D3 GPIO4/5/6/7, RESET GPIO39. TE (GPIO13) is not used. |
+| Touch | CST9217 at I²C 0x5A. INT GPIO11, RESET GPIO40. Transform: `mirror_x` + `mirror_y`. |
+| I²C bus | SDA GPIO15, SCL GPIO14, 400 kHz. |
+
+The I²C bus is shared by these devices:
+
+| Device | Address | Used by the firmware |
+|---|---|---|
+| AXP2101 (PMU) | 0x34 | yes (battery) |
+| TCA9554 (IO expander) | 0x20 | no |
+| QMI8658 (IMU) | 0x6B | no |
+| PCF85063 (RTC) | 0x51 | no |
+| ES8311 (audio codec) | 0x18 | no |
+| ES7210 (audio ADC) | 0x40 | no |
+
+The touch driver is the external component `cst9217` from `shelson/esphome-cst9217`, pinned to a commit SHA in `esphome/packages/board-waveshare-amoled-175.yaml`. Keep it pinned.
+
+## Power and battery
+
+The AXP2101 reports the battery state through the `axp2101_battery` component (`esphome/components/axp2101_battery/`). The display and touch rails are powered by default, so the firmware does not touch the LDO registers.
+
+Registers used (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 percentage: register 0xA4 (0–100).
+- Battery voltage in mV: `((reg 0x34 & 0x1F) << 8) | reg 0x35`.
+
+Without a battery the level and voltage are unknown (NaN) and nothing logs an error. While the screen sleeps the panel brightness is 0 and LVGL is paused; the Wi-Fi and API connections stay up.
+
+## Performance settings
+
+- LVGL draws with `lvgl: buffer_size: 25%` (in `esphome/packages/ui.yaml`). This is the current setting.
+- It has not been tuned on hardware yet. If the page slides stutter (below about 30 fps), try these 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%`.
+- Record the result here once measured.
+- Image size: about 2.0 MB, in an app partition of about 8.1 MB (ESPHome sizes the partitions for 16 MB flash).
+
+## Fonts
+
+Fonts are declared in `esphome/packages/ui.yaml` and reach LVGL through `font::Font::get_lv_font()`. The text font uses `glyphsets: [GF_Latin_Core]` and the Google Fonts source (`gfonts`); both were accepted by ESPHome 2026.10.2, so no explicit-glyph fallback was needed. The emoji fonts take their glyphs from `custom_components/ha_controller/emoji.json`.
+
+## Sleep
+
+Sleep uses `touchscreen::TouchListener::release()` to wake on touch (the touch that wakes the screen is swallowed) and the `lvgl.pause`, `lvgl.resume` and `lvgl.widget.redraw` actions to stop and restart drawing.
+
+## Enclosures
+
+Printable enclosures are in [`3D_models/`](../3D_models/), in two variants: [with a PWR button](../3D_models/with_pwr_button) and [without one](../3D_models/without_pwr_button).
diff --git a/docs/protocol/README.md b/docs/protocol/README.md
new file mode 100644
index 0000000..449dce8
--- /dev/null
+++ b/docs/protocol/README.md
@@ -0,0 +1,170 @@
+# 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 `docs/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. |
+
+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)
+
+`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._`:
+
+| 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`, 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.
+
+**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
+
+`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/docs/protocol/fixtures/colors.json b/docs/protocol/fixtures/colors.json
new file mode 100644
index 0000000..8ed6457
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/climate-clamp.json b/docs/protocol/fixtures/controls/climate-clamp.json
new file mode 100644
index 0000000..4590942
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/climate-set.json b/docs/protocol/fixtures/controls/climate-set.json
new file mode 100644
index 0000000..8794970
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/ignored-bad-value.json b/docs/protocol/fixtures/controls/ignored-bad-value.json
new file mode 100644
index 0000000..290ad87
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/ignored-climate-toggle.json b/docs/protocol/fixtures/controls/ignored-climate-toggle.json
new file mode 100644
index 0000000..dd5e767
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/ignored-custom-block.json b/docs/protocol/fixtures/controls/ignored-custom-block.json
new file mode 100644
index 0000000..8e65c09
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/ignored-unknown-block.json b/docs/protocol/fixtures/controls/ignored-unknown-block.json
new file mode 100644
index 0000000..15c4a1b
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/light-set-over.json b/docs/protocol/fixtures/controls/light-set-over.json
new file mode 100644
index 0000000..50e6a98
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/light-set-zero.json b/docs/protocol/fixtures/controls/light-set-zero.json
new file mode 100644
index 0000000..e79c924
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/light-set.json b/docs/protocol/fixtures/controls/light-set.json
new file mode 100644
index 0000000..5340543
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/controls/light-toggle.json b/docs/protocol/fixtures/controls/light-toggle.json
new file mode 100644
index 0000000..25bfddc
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json b/docs/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json
new file mode 100644
index 0000000..bdfe85b
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/disconnected.json b/docs/protocol/fixtures/layouts/invalid/disconnected.json
new file mode 100644
index 0000000..a6245c4
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/duplicate_id.json b/docs/protocol/fixtures/layouts/invalid/duplicate_id.json
new file mode 100644
index 0000000..c976924
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/duplicate_position.json b/docs/protocol/fixtures/layouts/invalid/duplicate_position.json
new file mode 100644
index 0000000..2275e77
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_background.json b/docs/protocol/fixtures/layouts/invalid/invalid_background.json
new file mode 100644
index 0000000..abc7b13
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_entity-item.json b/docs/protocol/fixtures/layouts/invalid/invalid_entity-item.json
new file mode 100644
index 0000000..07a5134
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_entity.json b/docs/protocol/fixtures/layouts/invalid/invalid_entity.json
new file mode 100644
index 0000000..1a9c855
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_font_size-item.json b/docs/protocol/fixtures/layouts/invalid/invalid_font_size-item.json
new file mode 100644
index 0000000..49f6b79
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_font_size.json b/docs/protocol/fixtures/layouts/invalid/invalid_font_size.json
new file mode 100644
index 0000000..c5ea2a8
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_id.json b/docs/protocol/fixtures/layouts/invalid/invalid_id.json
new file mode 100644
index 0000000..82916a0
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_item.json b/docs/protocol/fixtures/layouts/invalid/invalid_item.json
new file mode 100644
index 0000000..aa38cd8
--- /dev/null
+++ b/docs/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/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/invalid/invalid_name.json b/docs/protocol/fixtures/layouts/invalid/invalid_name.json
new file mode 100644
index 0000000..a3b6402
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json b/docs/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json
new file mode 100644
index 0000000..2576ad1
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_start-empty.json b/docs/protocol/fixtures/layouts/invalid/invalid_start-empty.json
new file mode 100644
index 0000000..01d9e95
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_start.json b/docs/protocol/fixtures/layouts/invalid/invalid_start.json
new file mode 100644
index 0000000..eeeb16d
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_structure-settings.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure-settings.json
new file mode 100644
index 0000000..8cbe925
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_structure-version.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure-version.json
new file mode 100644
index 0000000..4192b9c
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_structure.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure.json
new file mode 100644
index 0000000..f48243b
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_text.json b/docs/protocol/fixtures/layouts/invalid/invalid_text.json
new file mode 100644
index 0000000..a0a169e
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/invalid_type.json b/docs/protocol/fixtures/layouts/invalid/invalid_type.json
new file mode 100644
index 0000000..1201756
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/too_many_blocks.json b/docs/protocol/fixtures/layouts/invalid/too_many_blocks.json
new file mode 100644
index 0000000..04c7dba
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/too_many_items.json b/docs/protocol/fixtures/layouts/invalid/too_many_items.json
new file mode 100644
index 0000000..9e9391a
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/invalid/unsupported_emoji.json b/docs/protocol/fixtures/layouts/invalid/unsupported_emoji.json
new file mode 100644
index 0000000..7a673ce
--- /dev/null
+++ b/docs/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/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/protocol/fixtures/layouts/valid/emoji-variation.json b/docs/protocol/fixtures/layouts/valid/emoji-variation.json
new file mode 100644
index 0000000..7eb8b85
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/valid/empty.json b/docs/protocol/fixtures/layouts/valid/empty.json
new file mode 100644
index 0000000..3cd8f9c
--- /dev/null
+++ b/docs/protocol/fixtures/layouts/valid/empty.json
@@ -0,0 +1,8 @@
+{
+ "version": 1,
+ "start": null,
+ "settings": {
+ "sleep_timeout": 20
+ },
+ "blocks": []
+}
diff --git a/docs/protocol/fixtures/layouts/valid/reference.json b/docs/protocol/fixtures/layouts/valid/reference.json
new file mode 100644
index 0000000..2ebd691
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/layouts/valid/single.json b/docs/protocol/fixtures/layouts/valid/single.json
new file mode 100644
index 0000000..aabeba2
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/payloads/invalid/bad_json-array.json b/docs/protocol/fixtures/payloads/invalid/bad_json-array.json
new file mode 100644
index 0000000..2ae4a97
--- /dev/null
+++ b/docs/protocol/fixtures/payloads/invalid/bad_json-array.json
@@ -0,0 +1,4 @@
+{
+ "expect": "bad_json",
+ "text": "[1,2]"
+}
diff --git a/docs/protocol/fixtures/payloads/invalid/bad_json.json b/docs/protocol/fixtures/payloads/invalid/bad_json.json
new file mode 100644
index 0000000..02556ae
--- /dev/null
+++ b/docs/protocol/fixtures/payloads/invalid/bad_json.json
@@ -0,0 +1,4 @@
+{
+ "expect": "bad_json",
+ "text": "{\"v\":1,"
+}
diff --git a/docs/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json
new file mode 100644
index 0000000..37b3dee
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/payloads/invalid/invalid_payload-widget.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload-widget.json
new file mode 100644
index 0000000..a8c6e7c
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/payloads/invalid/invalid_payload.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload.json
new file mode 100644
index 0000000..d94e132
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/payloads/invalid/unsupported_version.json b/docs/protocol/fixtures/payloads/invalid/unsupported_version.json
new file mode 100644
index 0000000..ba34385
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/payloads/valid/emoji-variation.json b/docs/protocol/fixtures/payloads/valid/emoji-variation.json
new file mode 100644
index 0000000..953dec4
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/payloads/valid/empty.json b/docs/protocol/fixtures/payloads/valid/empty.json
new file mode 100644
index 0000000..3a4e6b8
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/payloads/valid/reference.json b/docs/protocol/fixtures/payloads/valid/reference.json
new file mode 100644
index 0000000..a9f0752
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/all-missing.json b/docs/protocol/fixtures/states/all-missing.json
new file mode 100644
index 0000000..df191af
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/climate-defaults.json b/docs/protocol/fixtures/states/climate-defaults.json
new file mode 100644
index 0000000..e0941ce
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/climate-heating.json b/docs/protocol/fixtures/states/climate-heating.json
new file mode 100644
index 0000000..c4fa0ce
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/entity-missing.json b/docs/protocol/fixtures/states/entity-missing.json
new file mode 100644
index 0000000..3d3ec18
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/entity-precision.json b/docs/protocol/fixtures/states/entity-precision.json
new file mode 100644
index 0000000..c89b542
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/light-dimmable-off.json b/docs/protocol/fixtures/states/light-dimmable-off.json
new file mode 100644
index 0000000..ee2aa57
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/light-dimmable-on.json b/docs/protocol/fixtures/states/light-dimmable-on.json
new file mode 100644
index 0000000..9a99452
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/light-onoff.json b/docs/protocol/fixtures/states/light-onoff.json
new file mode 100644
index 0000000..24d35da
--- /dev/null
+++ b/docs/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/docs/protocol/fixtures/states/light-unavailable.json b/docs/protocol/fixtures/states/light-unavailable.json
new file mode 100644
index 0000000..a24b34d
--- /dev/null
+++ b/docs/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/docs/releasing.md b/docs/releasing.md
new file mode 100644
index 0000000..476a16a
--- /dev/null
+++ b/docs/releasing.md
@@ -0,0 +1,25 @@
+# Releasing
+
+## One-time setup
+
+- Settings > Pages > Source: "GitHub Actions".
+- Settings > Environments > `github-pages` > Deployment branches and tags: add a tag rule `v*`. By default the environment only accepts the default branch, so the `pages` job of a tag run would be rejected.
+- Set the repository description and topics, which HACS requires.
+
+## Steps
+
+1. Set the version everywhere: `.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z`.
+2. Commit it: `git commit -am "chore: release X.Y.Z"`.
+3. Tag and push: `git tag vX.Y.Z && git push origin main vX.Y.Z`.
+4. Watch the "Release" workflow.
+5. Check that the Pages installer shows X.Y.Z and that HACS offers X.Y.Z.
+
+The workflow builds the panel, packages `ha_controller.zip`, compiles the firmware, rebuilds and deploys the GitHub Pages site with the new firmware and every earlier released firmware, and only then creates the GitHub release with the zip and the firmware files. Pages is deployed before the release so that the `firmware//ha-controller.ota.bin` URLs already exist when HACS offers the new version; otherwise the first automatic update would get a 404.
+
+## Dry runs
+
+Run the "Release" workflow with `workflow_dispatch`. Only the `build` job runs, and it uploads a `dist` artifact without creating a release.
+
+## Stable OTA URLs
+
+Installed integrations download `firmware//ha-controller.ota.bin` from the Pages site. Never change this layout.
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..015086d
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md
@@ -0,0 +1,337 @@
+# 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. 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.
+
+## 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/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:
+ - `.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/CLAUDE.md` with a `## Commands` table and a `## Skills and agents` section. Later plans append rows.
+
+- [ ] **Step 1: Write the failing tests** in `.github/scripts/tests/test_docs_links.py`.
+
+```python
+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
+ # 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 .github/scripts/tests -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/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 .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 .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/`, `custom_components/ha_controller/frontend/coverage/`, `.superpowers/`, `esphome/.esphome/`, `esphome/secrets.yaml`, `build/`, `dist/`, `site/`.
+
+- [ ] **Step 4: Run the tests and lint**
+
+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 `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/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"
+```
+
+---
+
+### Task 2: Protocol contract — protocol doc, emoji list, fixtures and Claude guidance
+
+**Files:**
+- Create:
+ - `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/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:
+ `💡 🔥 ❄ 🌡 💧 🌬 ☀ 🌙 ⭐ ☁ ⛅ 🌧 ⚡ 🔋 🔌 🏠 🛋 🛏 🛁 🚿 🍳 🍽 ☕ 🍷 🧺 🪴 🚪 🪟 🔒 🔓 🔑 🔔 🔕 🔊 🔇 🎵 📺 🎮 💻 📱 ⏰ 📅 🚗 🚲 🐶 🐱 👶 👋 👍 ❤ 😀 😴 🎉 🎄 ✅ ❌ ⚠ ℹ ▶ ⏸ ♻ 🌀 🧊 🏡`
+ - `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
+ {
+ "layout": "reference",
+ "unit": "°C",
+ "entity_ids": ["…"] | null,
+ "hass_states": {"": {"state": "…", "attributes": {}}},
+ "registry_options": {"": {}},
+ "updates": []
+ }
+ ```
+
+ `registry_options` is optional; `updates` lists the expected update objects.
+ - `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 `.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():
+ 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 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
+ # 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 .github/scripts/tests -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 .github/scripts/tests -v`
+Expected: PASS.
+
+- [ ] **Step 5: Write the protocol doc and guidance**
+ - **`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:
+
+ ```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/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/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/CLAUDE.md`:** list the skill and the agent under `## Skills and agents`.
+
+- [ ] **Step 6: Run the whole suite**
+
+Run: `pytest .github/scripts/tests -v && ruff check .github/scripts`
+Expected: PASS.
+
+- [ ] **Step 7: Commit**
+
+```bash
+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
new file mode 100644
index 0000000..9ddbedb
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md
@@ -0,0 +1,596 @@
+# 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 `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.
+
+**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.
+- **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`.
+- 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`
+ - `.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`
+ - `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:
+ - **`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}"`.
+ - **`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 `docs/protocol/fixtures/...`.
+
+- [ ] **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 {}
+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 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.**
+ - **`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
+ {
+ "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"}`.
+ - **`.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;
+ - 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 custom_components/ha_controller/tests/test_config_flow.py -v && ruff check custom_components`
+Expected: PASS.
+
+- [ ] **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/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 .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"
+```
+
+---
+
+### Task 2: Layout validation
+
+**Files:**
+- Create: `custom_components/ha_controller/layout.py`, `custom_components/ha_controller/tests/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 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.
+ - **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 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 custom_components/ha_controller/tests/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`, `custom_components/ha_controller/tests/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 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 custom_components/ha_controller/tests/test_compiler.py -v`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 4: State builders
+
+**Files:**
+- Create: `custom_components/ha_controller/states.py`, `custom_components/ha_controller/tests/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 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 custom_components/ha_controller/tests/test_states.py -v`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 5: Layout store and ScreenController sync engine
+
+**Files:**
+- 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:**
+- 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 custom_components/ha_controller/tests/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 custom_components/ha_controller/tests -v`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 6: Control events
+
+**Files:**
+- Create: `custom_components/ha_controller/controls.py`, `custom_components/ha_controller/tests/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 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 custom_components/ha_controller/tests -v`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 7: Websocket API
+
+**Files:**
+- 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:**
+- 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 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 custom_components/ha_controller/tests -v`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 8: Sidebar panel registration, developer docs and reviewer agent
+
+**Files:**
+- Create:
+ - `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/CLAUDE.md`
+
+**Interfaces:**
+- 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(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(
+ 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 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 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 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 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;
+ - 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/CLAUDE.md`:** list the agent.
+
+- [ ] **Step 6: Commit**
+
+```bash
+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
new file mode 100644
index 0000000..e929817
--- /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/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`.
+
+**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:** `custom_components/ha_controller/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:
+ - `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:
+ - **`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. 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"})`.
+
+- [ ] **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: "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`.
+
+- [ ] **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 custom_components/ha_controller/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 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: 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 custom_components/ha_controller/frontend …` commands to `.claude/CLAUDE.md`.
+
+- [ ] **Step 7: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 2: Edit operations, colours and emoji
+
+**Files:**
+- 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).
+- 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 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 custom_components/ha_controller/frontend test`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 3: Block map component (`hc-grid`)
+
+**Files:**
+- 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`.
+- 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 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 custom_components/ha_controller/frontend test`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+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"
+```
+
+---
+
+### Task 4: Block editor components
+
+**Files:**
+- Create:
+ - `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`.
+- 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 `