agentleFS
adrienbraultadrienbrault/geekmagic-hacs/CLAUDE.md

geekmagic-hacs

CLAUDE.md510 starsChanged 15 days agoMITView on GitHub

Home Assistant custom integration for GeekMagic displays (SmallTV Pro and similar ESP8266-based devices). Use uv for all Python operations: scripts/dev-ha (Docker) starts a throwaway HA with this checkout's integration mounted read-only, a fake device (dev/fake_device.py, an emulated SmallTV Ultra) and eleven seeded views. No onboarding or login. scripts/dev-ha restart picks up Python changes. To verify a change end to end: - Render every view through the real pipeline with the websocket API (geekmagic/views/list, then geekmagic/preview/render), authenticated with the token in…

  • Reads credentials
  • Installs packages
  • Commits and pushes

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

45 rules. About 0 are common, 13 are distinctive, and 32 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈13

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 32

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use uv for all Python operations:

    line 7
  2. Distinctive:

    Follow Conventional Commits and create atomic commits as you work:

    line 48
  3. Distinctive:

    Create small, focused commits that each represent a single logical change:

    line 60
  4. Distinctive:

    Commit and push on main:

    line 91
  5. Very specific:

    Wait for CI, HACS and Hassfest to pass on the bump commit (gh run list --branch main, gh run watch <id>).

    line 95
  6. Very specific:

    Add the Highlights section below the generated notes with the release-highlights skill (.claude/skills/release-highlights/), and run its …

    line 105
  7. Distinctive:

    Only release when the user asked for one: a release reaches every HACS user, and a published tag is never moved or reused (fix forward with …

    line 115
  8. Very specific:

    All drawing happens in the Blitz HTML/CSS engine via the blitz-py package (Stylo CSS + Taffy layout + Parley text + Vello raster — no …

    line 171
  9. Very specific:

    Animated path (opt-in): when the device's Animations switch is on and a placed widget returns `is_animated() == True, the coordinator calls …

    line 241
  10. Very specific:

    Every engine call goes through engine.get_engine() (or engine_available() for "usable and above the floor").

    line 279
  11. Very specific:

    All Python-side fitting is open-loop (predict, then draw) and funnels through _textfit._ref_width, which sanitizes degenerate engine …

    line 320
  12. Very specific:

    No container queries. filter does blur() and drop-shadow() only: the colour filters (grayscale(), brightness()...) are ignored, and only …

    line 352
  13. Distinctive:

    Use high contrast colors (light on dark)

    line 400
  14. Distinctive:

    The value is the widget: Every cell spends its height on the hero.

    line 424
  15. Very specific:

    Default: no explicit color (body text is var(--text-primary)).

    line 514
  16. Distinctive:

    Use a role tint only when one of these narrow exceptions applies:

    line 517
  17. Very specific:

    Don't hardcode SYSTEM_* colors or hex literals in widget code — the regression test tests/test_watchos_design_system.py guards this.

    line 532
  18. Very specific:

    Don't import from widgets/theme.py for colour values in widgets.

    line 535
  19. Distinctive:

    Don't tint a hero value just because it "looks nice" — follow the rule above.

    line 536
  20. Very specific:

    Don't put style="display: flex" inline on an element that carries a .hide-* class — inline styles defeat the media-query hide.

    line 538
  21. Very specific:

    Don't rely on text-overflow: ellipsis or overflow: hidden for widget text — overflow: hidden crops glyph ascenders/descenders on tight …

    line 540
  22. Very specific:

    Don't spread two bands with space-evenly — a header and a hero are one block, centred with a scaled gap (card_html(stack_gap_px=…)).

    line 544
  23. Very specific:

    Read tests/test_watchos_design_system.py before adding a widget — it documents the contract.

    line 551
  24. Very specific:

    Use card_html() from widgets/_card.py for the standard caption/hero/chips card — consistency for free.

    line 553
  25. Very specific:

    Use kit classes; add inline style only for widget-specific layout.

    line 594
  26. Distinctive:

    All pytest tests use mocks and don't require a real device or Home Assistant instance.

    line 611
  27. Very specific:

    Use core interfaces (hass.states, hass.services) instead of integration details

    line 650
  28. Distinctive:

    Add regression tests when fixing bugs

    line 652
  29. Very specific:

    Run pytest and pre-commit before commits

    line 653
  30. Distinctive:

    When that happens the fix belongs on main, not in the contributor's branch.

    line 681
  31. Very specific:

    Add tests in tests/widgets/

    line 697
  32. Very specific:

    Document it: add a factory to generate_widget_sizes() in scripts/generate_samples.py (renders every cell size), a section in …

    line 698
  33. Very specific:

    Use helper functions from widgets/helpers.py for common operations:

    line 708
  34. Distinctive:

    When adding a new layout, update these files:

    line 734
  35. Very specific:

    Run uv run python scripts/update_samples.py to generate images (CI also regenerates them on PRs — see "Samples (README images)")

    line 753
  36. Very specific:

    When embedding sample/screenshot images of device renders (240x240 PNGs from samples/) in README.md or docs/:

    line 822
  37. Very specific:

    Outside tables: always use width="200" for consistency across dashboard samples, binary sensor states, domain icons, layouts, etc.

    line 825
  38. Very specific:

    Create implementation in entities/<platform>.py

    line 846
  39. Very specific:

    Create stub at custom_components/geekmagic/<platform>.py that re-exports async_setup_entry

    line 847
  40. Very specific:

    Add Platform.<PLATFORM> to PLATFORMS list in __init__.py

    line 848
  41. Very specific:

    Sleep: Use asyncio.sleep() instead of time.sleep()

    line 867
  42. Very specific:

    Use HA elements whose API is simple and stable (ha-card, ha-button, ha-icon-button, ha-switch, ha-slider, ha-select via select-compat.ts, …

    line 905
  43. Very specific:

    After making changes to the frontend source in custom_components/geekmagic/frontend/:

    line 915
  44. Very specific:

    Run npm run build to regenerate dist/

    line 932
  45. Distinctive:

    Commit both source and dist changes

    line 933

≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

GeekMagic HACS Integration

Home Assistant custom integration for GeekMagic displays (SmallTV Pro and similar ESP8266-based devices).

Development

Use uv for all Python operations:

uv sync                       # Install dependencies (blitz-py comes as a
                              # prebuilt wheel from PyPI)
uv run pytest                 # Run tests
uv run pytest -v              # Run tests with verbose output
uv run ruff check .           # Lint code
uv run ruff format .          # Format code
uv run ty check               # Type check
uv run pre-commit run --all   # Run all pre-commit hooks

Running it in a real Home Assistant

scripts/dev-ha (Docker) starts a throwaway HA with this checkout's integration mounted read-only, a fake device (dev/fake_device.py, an emulated SmallTV Ultra) and eleven seeded views. No onboarding or login. scripts/dev-ha restart picks up Python changes. To verify a change end to end:

  • Render every view through the real pipeline with the websocket API (geekmagic/views/list, then geekmagic/preview/render), authenticated with the token in dev/.state/token.
  • GET http://127.0.0.1:<FAKE_PORT>/_fake/state returns the displayed file, theme, brightness and the integration's recent requests (status

    = 400 means the fake lacks an endpoint the integration now calls).

  • The PNG of the frame the device was last sent is GET /api/image_proxy/image.fake_display_display_preview. Show "11 Camera" (select.fake_display_display; nothing in it moves) and its geekmagic/preview/render output must be byte-identical to it.
  • Ports live in dev/.state/ports.env. Use 127.0.0.1, not localhost: the project venv's aiodns breaks on localhost lookups.

dev/bootstrap.py only uses public HA and integration APIs (onboarding, config flow, geekmagic/views/*), so changes to the integration's storage format don't break it. When a new endpoint or firmware behaviour matters, extend the fake from the captures in docs/devices/.

Git Workflow

Follow Conventional Commits and create atomic commits as you work:

Commit Types

  • feat: New feature
  • fix: Bug fix
  • refactor: Code refactoring (no functional change)
  • docs: Documentation only
  • test: Adding/updating tests
  • chore: Maintenance (deps, config, tooling)
  • style: Formatting, whitespace (no code change)

Atomic Commits

Create small, focused commits that each represent a single logical change:

  1. After implementing a feature → commit the feature
  2. After fixing a bug → commit the fix
  3. After adding tests → commit the tests
  4. After refactoring → commit the refactor

Always run pre-commit before committing: uv run pre-commit run --all

This validates tests, linting, formatting, and type checking in one command.

Examples

git commit -m "feat: add clock widget with timezone support"
git commit -m "fix: handle missing entity gracefully in EntityWidget"
git commit -m "test: add unit tests for sparkline rendering"
git commit -m "refactor: extract color parsing into helper function"
git commit -m "chore: add ty type checker and pre-commit hooks"

Release Process

HACS detects new versions via GitHub releases. When the user asks for a release, Claude does all of it: bump, wait for CI, tag, push, publish the release with GitHub's generated notes. The user doesn't need to touch the GitHub UI.

When the user asks for a release (e.g. "release 1.0.1", "bump and release a patch")

  1. Determine the new version using semver:
    • Patch (1.0.0 → 1.0.1): bug fixes only
    • Minor (1.0.0 → 1.1.0): new features, backward-compatible
    • Major (1.0.0 → 2.0.0): breaking changes
  2. On an up-to-date main (git pull --ff-only), update version in custom_components/geekmagic/manifest.json
  3. Commit and push on main:
    chore: bump version to X.Y.Z
  4. Wait for CI, HACS and Hassfest to pass on the bump commit (gh run list --branch main, gh run watch <id>). If one fails, stop and report: never tag a red commit.
  5. Tag the bump commit and push the tag:
    git tag -s X.Y.Z <bump-sha> -m "X.Y.Z"   # annotated tag without -s if signing fails
    git push origin X.Y.Z
  6. Publish the release from that tag:
    gh release create X.Y.Z --verify-tag --generate-notes --title X.Y.Z
  7. Add the Highlights section below the generated notes with the release-highlights skill (.claude/skills/release-highlights/), and run its verifier.
  8. Report the release URL and what it contains (the generated notes' PR list and the highlights).

Critical rules

  • Tag must match manifest.json version exactly (HA core reads manifest.json and a mismatch breaks update detection): check git show <bump-sha>:custom_components/geekmagic/manifest.json before tagging
  • Tag the bump commit, not an earlier one — otherwise the tagged tree still has the old version
  • Tag format: X.Y.Z (no leading v — every existing tag is plain, e.g. 1.5.1)
  • Only release when the user asked for one: a release reaches every HACS user, and a published tag is never moved or reused (fix forward with a new patch version)

Project Structure

custom_components/geekmagic/
├── __init__.py       # Integration entry, services
├── config_flow.py    # Device setup + options flow
├── coordinator.py    # Data update coordinator
├── frame.py          # Frame inputs fetched from HA, shared by device and preview
├── view.py           # HA-free half: build_layout, widget states, render_still
├── history.py        # Recorder history for chart/candlestick widgets
├── image_decode.py   # HA-free bounded picture decode (decode_image)
├── device.py         # HTTP API client for GeekMagic
├── htmldoc.py        # Blitz document assembly, fluid kit, SVG helpers
├── engine.py         # The one door to blitz_py (lazy import + self-test gate)
├── engine_probe.py   # Subprocess engine self-test, cache, repair issue
├── engine_selftest.py # The frame the self-test child renders (HA-free)
├── renderer.py       # Canvas compositing + JPEG/PNG encoding
├── const.py          # Constants and config keys
├── fonts/            # Embedded fonts (Nunito, DejaVu, Noto script subsets, MDI)
├── widgets/          # Widget components (HTML fragments)
│   ├── base.py       # Widget base class (render_html contract)
│   ├── _card.py      # card_html/chip_html three-band primitives
│   ├── theme.py      # Themes: palette + CSS (chrome/backdrop/overlay)
│   ├── clock.py      # Clock widget
│   ├── entity.py     # HA entity display
│   ├── media.py      # Media player widget
│   ├── chart.py      # Sparkline chart (SVG)
│   ├── helpers.py    # Widget helper functions
│   └── text.py       # Static/dynamic text
├── layouts/          # Layout systems
│   ├── base.py       # Layout base class
│   ├── grid.py       # 2x2, 2x3, 3x3 grids
│   ├── hero.py       # Hero + footer layout
│   └── split.py      # Split panel layouts
├── entities/         # Entity platform implementations
│   ├── base.py       # Base GeekMagicEntity class
│   ├── number.py     # Number entities (brightness, etc.)
│   ├── select.py     # Select entities (display, rotation)
│   ├── switch.py     # Switch entities (boolean options)
│   ├── button.py     # Button entities (refresh, nav)
│   └── sensor.py     # Sensor entities (status, dividers)
├── number.py         # Re-export for HA platform discovery
├── select.py         # Re-export for HA platform discovery
├── switch.py         # Re-export for HA platform discovery
├── button.py         # Re-export for HA platform discovery
├── sensor.py         # Re-export for HA platform discovery
├── manifest.json     # HACS metadata
└── strings.json      # UI translations

Key Concepts

Rendering Pipeline (Blitz engine)

All drawing happens in the Blitz HTML/CSS engine via the blitz-py package (Stylo CSS + Taffy layout + Parley text + Vello raster — no browser). Pillow only composites passes and encodes JPEG/PNG.

  1. Coordinator triggers update on interval
  2. Layout calculates widget rectangles (slots) — pure geometry
  3. One render_layers call composites the whole screen engine-side: the theme backdrop layer (theme.backdrop_css), one layer per widget cell (each widget's render_html fragment wrapped by htmldoc.build_cell_document — theme CSS variables + fluid kit + theme.chrome_css), and the optional theme.overlay_css layer (scanlines, vignettes) on top. Each cell layer keeps its own CSS viewport (vmin/vw and @media respond to the CELL size) and is CLIPPED to its rect by the engine. Themes with glow_effect (neon) paint each cell once blurred beneath its sharp pass (per-layer blur/opacity).
  4. Image converted to JPEG and uploaded to device — unless it is byte-identical to the last successful push (renders are deterministic; each upload is a flash write, issue #96). The skip lives in coordinator._async_push_frame: it needs a state read that succeeded this cycle (so an offline device is still caught), a push younger than FORCED_REPUSH_INTERVAL, and no _invalidate_push() since — call that from any new path that can change what the device shows behind the frame's back. Fonts are registered process-wide once, under a lock (register_fonts, htmldoc's font_param()) — no per-call font bytes. If registration ever fails, the same embedded font bytes ride every measurement call AND every render layer, so measurement and rendering can never resolve different fonts (that divergence is how fitted text overflows the panel).

The panel preview is the device frame. geekmagic/preview/render renders a draft view through the same pipeline as the coordinator: view.build_layout, FrameInputs.async_gather (camera snapshots, album art, Image widget pictures, chart/candlestick history, weather forecasts, then templates last in the event loop), FrameInputs.widget_states and view.render_still. A new kind of widget input goes into FrameInputs (fetching) and view.FrameData / view.assemble_widget_states (handing it to the widget), never into the coordinator or the preview alone. view.py stays HA-free (tools render views without Home Assistant through it); tests/test_preview_parity.py asserts the two produce byte-identical PNGs. What legitimately differs: the preview is never rotated, is animated only on request (animate: the editor asks for it on its own once an animated draft settles, and re-asks on the minute tick so a clock in a playing GIF stays current), has no notification overlay, and starts from fresh inputs (no stale-on-error snapshot) with shorter fetch timeouts. The animated preview is an unrotated device's GIF byte for byte: both go through view.render_animated (frames on animation.frame_timing, then the encoding).

manifest.json pins blitz-py exactly (==0.7.0). 0.6.0 fixed a native leak of ~16 KB per render call (a new render thread per call; ~5.8 MB/hour per display at the 10 s refresh, issue #209). 0.7.0 builds Blitz from the blitz-py branch of adrienbrault/blitz (upstream main plus the fork's fix branches; Stylo 0.24, Parley 0.13, vello_cpu 0.4): text moves by about 1px, and the engine now paints text-shadow, text-overflow: ellipsis, outline-offset, background-clip: text and CSS filter: blur()/drop-shadow(); no Python API change. Keep it an exact pin, and keep pyproject.toml on the same == so CI tests what users run: with >=, HA installs the newest blitz-py on every fresh install, so an engine release would reach users under integration versions that were never tested with it. Moving to a new blitz-py is an integration change: bump both pins, run the suite, regenerate the samples (scripts/update_samples.py) and diff them, then release. The pipeline's functional floor stays 0.4.2 (engine.ENGINE_FLOOR) — a working older install keeps rendering rather than getting the install-hint screen, which only an engine below the floor (or missing) paints. The pre-0.4.2 fallback paths (per-document renders + Pillow premultiplied compositing) were removed — do not reintroduce version-gated pipelines.

Animated path (opt-in): when the device's Animations switch is on and a placed widget returns is_animated() == True, the coordinator calls layout.render_animation instead: each frame is ONE render_layers call with the frame's clock on animated layers (and their glow underlays). Frames are encoded with Renderer.to_gif (1.6s @ 10fps, palette quantized without dithering) and dashboard.gif is uploaded in place of the JPEG. Frames and encoding live in view.render_animated (timing: animation.frame_timing), shared with the editor's autoplaying preview (geekmagic/preview/render with animate) and the HTML sample generator.

blitz-py capabilities adopted so far: measure_text (0.3.0) and ellipsize (0.4.0) drive widgets/_textfit.py — engine-native shaping over the embedded fonts (the same stacks the documents draw with, _textfit._FAMILY_CSS); register_fonts (0.4.0) makes fonts process-wide; render_layers (0.4.0) composites the screen engine-side. Still available but not yet adopted: fit_font_size / line_clamp / wrap_balanced (the Python fitters in _cardfit/media carry extra semantics — suffix reserve, identity rules — that need mapping first), Template.get_box/boxes() (could replace the CSS-math mirrors like label_px), the Template mutate-and-re-render fast path, and native render_layers_jpeg encode (encoding stays in renderer.py while supersample-then-Lanczos remains the quality baseline). Since 0.7.0 the engine paints text-overflow: ellipsis (single-line, nowrap + overflow: hidden), but widgets keep truncating in Python: their measured fitting decides what to drop, and overflow: hidden still crops glyphs.

blitz-py is REQUIRED for rendering — it's in manifest.json requirements (PyPI wheels for Linux glibc/musl x86_64 + aarch64, macOS, Windows), so HA installs it automatically. Without it the display shows an install-hint error screen.

The engine is never imported at module level, and never loaded into Home Assistant before a subprocess self-test passed (issue #262: a native crash in blitz-py — SIGILL on one HAOS VM — killed Core on every boot, with no traceback, until the integration was deleted). Rules:

  • Every engine call goes through engine.get_engine() (or engine_available() for "usable and above the floor"). Never import blitz_py, and no module-level engine state (HAS_* constants, try: import) — tests/test_engine_probe.py checks in a fresh interpreter that importing the integration and its platforms leaves blitz_py out of sys.modules. Never memoize an engine-less answer either (_FontRegistry, _textfit._ref_width): the gate can open after a first call.
  • async_setup holds the gate and starts ONE self-test per HA process (engine_probe, task under a HassKey). Any new render path in HA awaits async_engine_ready(hass) first (entry setup before its first refresh, geekmagic/preview/render); while held or blocked, get_engine() answers None.
  • The child (engine_selftest.main, started with -s -P -X faulthandler, Core's environment and Core's sys.path) imports the package's submodules WITHOUT its __init__, so everything it reaches must stay HA-free: htmldoc, engine, layouts/, widgets/, renderer, const, icons. It renders one neon 2x2 frame through Layout.render; a new engine capability adopted in production belongs in that frame too.
  • A pass is cached in Store under blitz-py version + Python + machine
    • CPU flags hash + integration version; failures are never cached. A failure blocks the engine for the process, logs one error (signal, versions, the child's stderr tail), raises the engine_crashed repair issue, and displays paint "Rendering engine disabled" (Layout._render_missing_blitz). Scripts and plain tests never touch the gate: it starts open. HA tests get a passing self-test from the autouse probe_spawns fixture (tests/conftest.py).

Blitz engine gotchas (verified on 0.4.2, re-verified on 0.5.0 — the engine bump fixed none of these, keep every workaround; 0.7.0 added the "…" for text-overflow: ellipsis, text-shadow, background-clip: text and blur/drop-shadow filter, the rest is not re-verified):

  • var(--x) does NOT resolve inside SVG paint attributes — pass concrete colors (css_rgb(theme.x)) to the SVG helpers.
  • text-overflow: ellipsis paints "…" only since blitz-py 0.7.0, and only on a single nowrap line; overflow: hidden cuts glyphs mid-stroke — on tight line-heights (.t-hero's 0.85) it also crops ascenders/descenders, and overflow-x clips BOTH axes. So CSS can contain overflow but never resolve it nicely: keep truncating long strings in Python (helpers.truncate_text, or the measured _textfit metrics for design-critical text).
  • All Python-side fitting is open-loop (predict, then draw) and funnels through _textfit._ref_width, which sanitizes degenerate engine measurements (NaN/<= 0 fall back to a conservative estimate). A NaN that leaks into fit_hero disables the width bound AND truncation (every comparison is False) and paints the value at the height cap across the bezel — the "massive text" field bug. Keep that choke point intact.
  • Inline style="display: flex" beats the kit's .hide-* media rules — put hide classes on a wrapper div without inline display.
  • Inline <svg> is sized from its viewBox ASPECT RATIO, not from height:100% against a flex parent — measure the plot box in Python and pass a matching aspect/viewBox.
  • Percentage padding resolves against the cell WIDTH on both axes — use px padding when vertical space is tight.
  • <style> blocks inside a widget fragment work, including media queries — a clean lever for widget-scoped responsive rules. But an element carrying both .hide-* and your own breakpoint loses to the kit's display:none !important; drop the .hide-* class when self-managing visibility.
  • Blitz paints non-positioned subtrees BEFORE absolutely-positioned siblings. A .hide-* wrapper around overlay text puts it under the scrim unless the wrapper itself is position:absolute; inset:0 (and it must fill the cell — absolute boxes resolve against the parent, so a zero-height wrapper collapses the overlay).
  • Fixed-height flex children shrink when the column overflows — give bars/tracks flex: none or they collapse to hairlines.
  • white-space: normal wrapping is not clipped by .cell's percentage padding — engine-wrapped text bleeds into the margin. Emit one block div per line (see _cardfit).
  • Text measured for fitting must use the theme's real face and case — widgets/_textfit.py (metrics_for(theme)) is the canonical measurer; _cardfit.py builds card geometry on top of it.
  • No container queries. filter does blur() and drop-shadow() only: the colour filters (grayscale(), brightness()...) are ignored, and only the first function of a list applies. text-shadow and background-clip: text work since 0.7.0. Gradients (linear/radial/conic), box-shadow, borders, object-fit, SVG (incl. linearGradient, bezier paths, stroke-dasharray), and CSS math (clamp/min/nested) all work.

Widget Interface

class Widget(ABC):
    def render_html(self, ctx: CellContext, state: WidgetState) -> str:
        """Return an HTML fragment rasterized at the cell size."""

    def get_entities(self) -> list[str]:
        """Return entity IDs this widget depends on."""

CellContext (from htmldoc.py) carries width, height, slot_index, theme, plus accent() (slot-cycled theme accent as a CSS color) and is_compact.

Layout Interface

class Layout(ABC):
    def _calculate_slots(self) -> None:
        """Calculate slot rectangles (pure geometry)."""

    def render(self, renderer, draw, widget_states) -> None:
        """Composite backdrop + widget cells + overlay onto the canvas."""

Device API

GeekMagic devices use a simple HTTP API:

POST /doUpload?dir=/image/   # Upload image (multipart form)
GET  /set?img=/image/{file}  # Display image
GET  /set?theme=3            # Set custom image mode
GET  /set?brt={0-100}        # Set brightness
GET  /app.json               # Get device state

Display Constraints

  • Resolution: 240x240 pixels
  • Physical size: ~4cm diagonal
  • Minimum font size: 10-12px for readability
  • Use high contrast colors (light on dark)
  • JPEG upload is faster than PNG (~2.5s vs ~5.8s)

Design System (watchOS-inspired) — rules for widget authors

The default theme (watchos) is modelled on Apple's watchOS HIG: true-black background, system colours, opacity-based text hierarchy, tinted Activity-ring gauges, no card chrome. standby is the same system on translucent white cards (iOS StandBy / Smart Stack); night is StandBy's bedside mode, one warm red ramp on black — a monochrome theme (Theme.monochrome), so the layout strips per-widget colours (config.color, on_color/off_color, thresholds, item colours) before rendering. Every widget should follow these rules so themes stay consistent. When in doubt, look at how Entity / Clock / BarGauge handle the same thing — they're the canonical references.

The viewing distance rule (read this first)

The panel is ~27mm wide and is read from 0.6 to 1 m away — a nightstand, a desk edge, a shelf. At 1 m a 12px caption subtends about 3 arcminutes, well under comfortable reading; a 40px value, a 20px tinted icon, and a colour fill are what actually register. So the design is modelled on Apple's StandBy and Smart Stack widgets, not on a dashboard:

  • The value is the widget. Every cell spends its height on the hero.
  • The icon carries identity and state. A tinted glyph reads from a metre away where a word does not; an entity that is off/closed/away renders its icon in var(--muted) (entity._MUTED_STATES).
  • Captions are support, not structure. Secondary tone, 10-18px, one line, shrink-then-truncate (_cardfit.fit_caption_sized).
  • Colour is restrained. One accent per cell, the theme's rotation across cells, semantic tints only where colour IS the meaning.
  • Edge to edge. Themes keep a 2-3px outer margin and an 8px gap between widgets; the gap does the separating.

Card anatomy (entity / gauge / progress / clock / text)

One shared header (_card.header_html) and one hero:

┌──────────────┐   ┌──────────────┐
│  ◉ CAPTION   │   │      ◉       │   header: tinted icon + caps caption,
│              │   │   CAPTION    │   inline — or STACKED in narrow, tall
│    23.5°C    │   │    23.5°C    │   cells (`header_stacks(ctx)`)
└──────────────┘   └──────────────┘
  • Inline vs stacked is decided from cell geometry only (_card.header_stacks), never from the content, so every cell of a grid carries the same header shape.
  • The glyph is big. 2.3x the caption inline, 3x stacked (HEADER_ICON_EM / STACK_ICON_EM), floored at a share of the cell's short side and capped at 24% of the cell height so it never costs the hero. When the caption would truncate beside it, the glyph gives up size first (1.5x), then the caption shortens by word.
  • Header and hero are centred as one block with a gap that scales with the cell (card_html(stack_gap_px=…)); three-band cards (with a chip strip) keep the kit's space-evenly.
  • Sibling harmony. Widgets report hero_hint(ctx, state) -> (kind, px); Layout._hero_caps caps equal-sized cells whose heroes are of the same kind ("num" / "word") to the smallest fitted size, floored at half a cell's own size. A grid of readings shares one type size; a row of "On / Off / Heat" shares another. Read the cap from ctx.extra["hero_px_cap"] in any widget that fits a hero.

Goals

  1. Information density first. A 240×240 cell is tiny. Use every pixel — justify="space-evenly" to spread content top-to-bottom (equal gaps before/between/after each band reads more balanced than pinning the first/last items flush to the cell edges). Never leave the bottom half of a cell empty if there's data to show. Three-band layout (caption / hero / supporting strip) is the default for cells ≥100×100.
  2. Hierarchy via size + weight + colour. A glance must surface the primary metric instantly: bold + large for the hero, secondary for supporting data, tertiary for captions. Don't make everything the same size.
  3. Theme consistency. A user moving between widgets in the same theme should never see an unexplained colour shift. Colour comes from the theme, not from the widget.
  4. Adapt to cell shape. Pick layout from (width, height) at render time — a hero ring should spread across a fullscreen cell but stay tight in a 3×3 grid; a vertical bar should stack everything when the cell is very narrow.

Colour rules — pick by intent, not by RGB

Widgets MUST use theme CSS variables in markup, never hardcoded hex colors. The variables resolve to the active theme's palette when the cell document is built.

Available CSS variables (resolve to theme.<role>):

CSS variableUse for
var(--text-primary)Default for hero values (white-ish on dark themes)
var(--text-secondary)Supporting info (dates, units, "Sunny" condition)
var(--text-tertiary)Caps captions, very-low-priority text
var(--primary)Brand accent — fallback for chart / progress
var(--secondary)Night, lightning, less-prominent accents
var(--success)ON / connected / wind
var(--warning)Sunny / hot temp / heating / caution
var(--error)Problems: disconnected / extreme / alarm
var(--info)Cool / cold / water / rain / cooling / humidity
var(--muted)Off / closed / away / idle / fog / disabled

Also: var(--bg), var(--surface), var(--surface-variant), var(--border), var(--accent-0..N), var(--radius). For the slot-cycled accent use ctx.accent(). Inside SVG paint attributes var() does not resolve — pass concrete colors via css_rgb(ctx.theme.success) etc.

Rule of thumb for hero value colour:

  • Default: no explicit color (body text is var(--text-primary)). Use this for entity value, clock time, weather temp, climate temp, multi-progress hero.
  • Use a role tint only when one of these narrow exceptions applies:
    1. Gauge family (Bar/Ring/Arc) where the value matches the gauge's own accent — value + fill read as one visual unit (Apple Activity-ring style). E.g. ring 73% in the ring's tint.
    2. Status state where the colour IS the meaning — ON in success green, OFF in the muted tone (red is for problems the user chose to paint red, never the default off state).
    3. Mode chip where the tint reinforces an explicit mode label (climate HEATING chip in warning).

The icon, ring fill, bar fill, and dot indicators carry the semantic tint. That's where the colour lives.

Don't

  • Don't hardcode SYSTEM_* colors or hex literals in widget code — the regression test tests/test_watchos_design_system.py guards this. (Neutral rgba(255,255,255,0.x) tracks/overlays are the exception.)
  • Don't import from widgets/theme.py for colour values in widgets.
  • Don't tint a hero value just because it "looks nice" — follow the rule above. If you're tempted, the icon should probably be tinted instead.
  • Don't put style="display: flex" inline on an element that carries a .hide-* class — inline styles defeat the media-query hide. Wrap it.
  • Don't rely on text-overflow: ellipsis or overflow: hidden for widget text — overflow: hidden crops glyph ascenders/descenders on tight line-heights, and the "…" only covers one nowrap line. Truncate long strings in Python (helpers.truncate_text).
  • Don't spread two bands with space-evenly — a header and a hero are one block, centred with a scaled gap (card_html(stack_gap_px=…)). Three or more bands keep space-evenly; tall columns group their bands (see progress) rather than fling them to the cell's ends.

Do

  • Read tests/test_watchos_design_system.py before adding a widget — it documents the contract.
  • Use card_html() from widgets/_card.py for the standard caption/hero/chips card — consistency for free.
  • Tint gauge tracks with css_rgba(accent, theme.tint_track_opacity) when theme.tint_track is set (see gauge.py).
  • Attach .hide-short / .hide-small to optional bands so cells degrade gracefully — that's the fluid system.

Typography — the fluid kit

Type is CSS-driven. The fluid kit (injected into every cell document by htmldoc.py) scales text with the CELL via clamp() + vmin/vw (width-capped so ~5-char values never overflow), and sheds optional bands via media queries:

ClassRole
.t-heroPrimary value — as big as the cell allows (weight 700, -0.02em)
.t-valueSecondary emphasized value
.t-unitUnit suffix (secondary color)
.t-labelCaps caption (secondary color, 0.05em tracking)
.t-datePlain secondary line (the clock's date)
.caption-row / .card-headInline / stacked header (see _card.header_html)
.icon + .i-lg/.i-md/.i-smMDI glyphs (embedded font)
.hide-shortHidden when cell < 100px tall
.hide-narrowHidden when cell < 100px wide
.hide-smallHidden when either dimension < 130px
.cell / .cell.rowFlex scaffold, space-evenly
.chips / .chip / .caption-rowSupporting strip (see _card.py)

Fonts embedded in every render: Nunito (400/600/700/800), DejaVu Sans, Material Design Icons, and variable-weight Noto Sans subsets for the scripts those lack: JP, SC, TC, KR, Thai, Arabic, Devanagari (scripts/subset_fonts.py lists what each keeps and rebuilds them). Themes pick families via theme.font_stack. The engine only falls back to a registered font that the stack NAMES (then to the host's fonts, and HAOS has none for these scripts: issue #320), so every stack lists const.SCRIPT_FAMILIES right after its own face (the first family sets the line box; before DejaVu, whose partial Arabic would split Urdu words). HTML widgets get it as var(--script-fonts).

Best practices:

  • Use kit classes; add inline style only for widget-specific layout.
  • TEXT AS BIG AS POSSIBLE — this is a 2" display.
  • One fragment for all sizes: hide bands with .hide-* instead of branching in Python where possible (ctx.is_compact exists for the cases CSS can't express).

Testing

Tests are organized by component:

  • tests/test_device.py - HTTP client tests
  • tests/test_renderer.py - Canvas/encoding tests
  • tests/test_config_flow.py - Config flow and options flow tests
  • tests/test_integration.py - Integration setup/teardown tests
  • tests/widgets/test_widgets.py - Widget tests
  • tests/layouts/test_layouts.py - Layout tests
  • tests/test_panel_contract.py - Panel ↔ widget contract (see below)

All pytest tests use mocks and don't require a real device or Home Assistant instance.

Panel ↔ widget contract

The panel (TypeScript) saves view configs; the widgets (Python) read them. tests/fixtures/panel_option_shapes.json holds one value per option type in exactly the shape the panel saves (array editors end with the blank row the panel inserts on "Add", from frontend/src/panel-defaults.ts). tests/test_panel_contract.py renders every widget with every option set that way, and frontend/src/panel-contract.test.ts type-checks the same file against the panel's types. A new option type needs a fixture entry; changing a stored shape on either side must fail one of these.

A widget that can't be built or rendered costs its own cell (BrokenWidget / WIDGET_ERROR_HTML), never the device's update loop. Keep it that way.

End-to-end (panel in a real Home Assistant)

frontend/e2e/*.e2e.ts (Playwright) drive the real panel against scripts/dev-ha. npm run e2e (in frontend/) starts or reuses the dev HA, then runs them; CI runs the same in the e2e job. Tests share one HA and one fake device, so they run serially; each gets a throwaway view (fixtures.ts) and must restore anything else it changes (device view assignments). Call the HA API through the page's own connection (ws(), callService()): CI's Node has no WebSocket. Assert on effects that can't already be true (count fake-device uploads after an action, not "status is Connected"). HA UI gotchas: dropdown items are menuitems, and the entity picker needs its own search box filled (stray keys open HA's quick bar) and a keyboard Enter (its virtualized list never settles for a click).

Home Assistant Testing Best Practices

Uses pytest-homeassistant-custom-component for HA-specific fixtures. See:

Available fixtures: hass, aioclient_mock, MockConfigEntry, etc.

Testing principles:

  • Use core interfaces (hass.states, hass.services) instead of integration details
  • Mock external dependencies (aiohttp, devices)
  • Add regression tests when fixing bugs
  • Run pytest and pre-commit before commits
  • Never reach into hass.data by string key, and never call a core API the release notes mark deprecated. Both work right up until they don't: HA's hass.data keys are HassKey objects that only happen to subclass str, so a raw lookup returns None and silently drops data instead of raising. dr.async_get(hass) / ar.async_get(hass) / er.async_get(hass), and dr.async_entries_for_config_entry over async_get_device.

The CI matrix is an HA matrix

uv.lock is gitignored on purpose, so CI resolves fresh on every run. Each pytest-homeassistant-custom-component release pins one exact HA version and raises its own requires-python in lockstep, which means the Python version alone decides which core the suite runs against:

JobResolves toAs of 2026-09
Python 3.12oldest ptc that still supports itHA 2025.1.4
Python 3.13a ptc a few months backHA 2026.2.3 (stable)
Python 3.14the newest ptcHA 2026.9.0b6 (beta)

That mapping moves on its own. The Resolved Home Assistant version step in each leg prints what a given run actually got.

The newest leg is deliberately merge-blocking. Resolving unpinned is how the 2026.9 deprecation of device_registry.async_get_device surfaced months before it would have reached users, and a red check is what got it fixed the same day. The accepted cost: an upstream beta can turn an unrelated PR red. When that happens the fix belongs on main, not in the contributor's branch.

Adding New Widgets

  1. Create custom_components/geekmagic/widgets/mywidget.py
  2. Extend Widget base class
  3. Implement render_html() and optionally get_entities()
  4. Register in widgets/__init__.py (_ALL_WIDGETS — WIDGET_CLASSES and schemas derive from it)
  5. Give the SCHEMA the panel's picker metadata: icon (mdi), category (values/home/time/history/pictures/custom), a one-line description, and uses_label: False if the widget ignores the label. An option that only applies to some choices gets visible_when ({"style": ["bar"]}: every key must match one of its values, against the stored value or the option's default). tests/test_panel_metadata.py checks all of it.
  6. Add tests in tests/widgets/
  7. Document it: add a factory to generate_widget_sizes() in scripts/generate_samples.py (renders every cell size), a section in docs/widgets.md (size row + options), and a row in the README's Widgets table (fullscreen / 2×2 / 3×3 only)
  8. Give it a picker preview: map its type to a sample name in frontend/src/widget-previews.json (or add it to WITHOUT_PREVIEW in tests/test_widget_previews.py), then run scripts/update_samples.py

Widget Helper Functions

Use helper functions from widgets/helpers.py for common operations:

from ..widgets.helpers import (
    truncate_text,  # Truncate long text with ellipsis
    estimate_max_chars,  # Estimate max chars that fit in pixel width
    format_number,  # Format with optional 1k/1M abbreviation
    format_value_with_unit,  # Format "23°C" / "1.5k views"
    calculate_percent,  # Clamp value to 0..100 over a min/max range
    parse_color,  # Coerce JSON list/tuple to RGB
    get_binary_sensor_icon,  # MDI icon by binary_sensor device_class
    get_domain_state_icon,  # MDI icon by domain + state
    translate_binary_state,  # Localized "Open"/"Closed" etc.
)

Markup Helpers

Build fragments with card_html/chip_html (widgets/_card.py) for the standard three-band card, and mdi_span / svg_sparkline / svg_ring / svg_arc / image_data_uri from htmldoc.py. The fluid kit classes handle size adaptation; themes restyle everything through chrome_css.

Adding New Layouts

When adding a new layout, update these files:

1. Backend

  • layouts/<name>.py - Create layout class extending Layout
  • layouts/__init__.py - Import and export the new class
  • const.py - Add LAYOUT_<NAME> constant, add it to LAYOUT_SLOT_COUNTS, and give it a display name in LAYOUT_NAMES
  • view.py - Add to LAYOUT_CLASSES dict

2. Frontend

Nothing to do: the panel draws layout tiles from the slot rects geekmagic/config computes from the layout class, and the editor's click-to-select overlay from the rects each preview returns.

3. Documentation & Samples

  • scripts/generate_samples.py - Add layout to generate_layout_samples()
  • Run uv run python scripts/update_samples.py to generate images (CI also regenerates them on PRs — see "Samples (README images)")
  • docs/layouts.md - Add the layout's image and its row (name, ID, slots) to the matching family

4. Tests

  • tests/layouts/test_layouts.py - Add test class for the new layout

Samples (README images)

samples/ holds the rendered device images used by the README and docs/. Regenerate them with one command:

uv run python scripts/update_samples.py

It runs scripts/generate_samples.py and scripts/generate_html_samples.py, then deletes any file under samples/ that no generator produced (so never hand-place images there — add a generator instead). A file is only rewritten when its pixels change by more than NOISE_TOLERANCE (scripts/sample_io.py), so macOS and Linux renders don't fight over rounding noise.

The panel's widget picker previews come from the same run: generate_widget_sizes crops slot 0 of each mapped widget sample, at every size, into custom_components/geekmagic/frontend/previews/ (shipped with the integration, served at /geekmagic_previews; samples/ itself is not installed by HACS). frontend/src/widget-previews.json maps widget types to samples and lists each size class's cell size; the panel picks the class that sheds the same optional bands as the slot.

The HTML widget gallery (docs/html-widget.md) comes from scripts/html_examples/*.html, rendered to samples/html/ (.gif for animated ones, which must fit the device's 400KB upload budget). The doc embeds each template verbatim; tests/test_html_examples.py keeps template, image and doc in sync and renders each template with only the entities the widget would pre-fetch.

CI keeps them (and the previews) current (.github/workflows/samples.yml): on a same-repo PR it regenerates samples on Linux and, if anything changed, pushes a chore: regenerate samples commit to your branch — so after pushing, you may need git pull --rebase before your next push. Fork PRs can't receive that push: the check fails and tells you to run the command above and commit.

The README's UI screenshots (docs/panel-main.png, the main page; docs/panel-editor.png, the View Editor; docs/panel-layout-theme.png, its Layout & theme tab; docs/device-info.png, the device page) are NOT samples: scripts/dev-ha screenshot regenerates them on demand from the dev Home Assistant (scripts/screenshot_panel.py, headless Playwright). They stay out of CI and update_samples.py because the demo data moves.

Docs layout

README.md is the overview that HACS shows in its UI: dashboard samples, features, install, a three-size widget table, a layout teaser, every theme, configuration (panel walkthrough with the generated screenshots), and short summaries linking to docs/. Reference detail lives in docs/ (index: docs/README.md): widgets.md (every widget at every size + options), html-widget.md, layouts.md, automation.md (entities + notify), devices/README.md (compatibility + device reports), development.md.

Link from README.md with ABSOLUTE https://github.com/.../blob/main/... URLs (HACS renders the README outside GitHub, where relative links break); docs/ pages link to each other relatively.

README Image Conventions

When embedding sample/screenshot images of device renders (240x240 PNGs from samples/) in README.md or docs/:

  • In README.md, use absolute https://raw.githubusercontent.com/adrienbrault/geekmagic-hacs/main/samples/... URLs, so images render in HACS too. In docs/, use relative paths (../samples/...): only GitHub renders those pages, and relative paths also work on a PR branch before its samples reach main.
  • Outside tables: always use width="200" for consistency across dashboard samples, binary sensor states, domain icons, layouts, etc.
  • Inside tables: omit the width attribute — let the table column dictate sizing.
  • UI screenshots (panel editor, device info pages) and the hero device photo are not "samples" and keep their own widths.

Home Assistant Platform Discovery

IMPORTANT: Home Assistant discovers entity platforms by looking for modules at custom_components.<domain>.<platform>. For example, Platform.NUMBER looks for custom_components.geekmagic.number.

Entity implementations live in entities/ subfolder for organization, but stub modules must exist at the root level that re-export async_setup_entry:

# custom_components/geekmagic/number.py (stub for HA discovery)
"""Number platform - re-exports from entities submodule."""

from .entities.number import async_setup_entry

__all__ = ["async_setup_entry"]

When Adding New Entity Platforms

  1. Create implementation in entities/<platform>.py
  2. Create stub at custom_components/geekmagic/<platform>.py that re-exports async_setup_entry
  3. Add Platform.<PLATFORM> to PLATFORMS list in __init__.py

Common Mistake to Avoid

Moving entity files to a subfolder without creating re-export stubs will cause:

ModuleNotFoundError: No module named 'custom_components.geekmagic.<platform>'

The fix is to create stub modules that re-export from the subfolder.

Asyncio and Blocking Operations

Home Assistant runs on asyncio. Blocking operations prevent the event loop from executing other tasks and must be handled properly.

Blocking Operations to Avoid in Async Code

  • Disk I/O: open(), glob.glob(), os.walk(), os.listdir(), pathlib read/write
  • Network I/O: urllib operations (use aiohttp instead)
  • Heavy computation: CPU-intensive tasks like image rendering
  • Sleep: Use asyncio.sleep() instead of time.sleep()

How to Offload Blocking Work

# In Home Assistant integration code:
result = await hass.async_add_executor_job(blocking_function, arg1, arg2)

# With keyword arguments:
from functools import partial

result = await hass.async_add_executor_job(partial(blocking_function, kwarg1=value1), arg1)

This Integration's Blocking Operations

  • Image rendering (Pillow): CPU-intensive, runs in executor
  • JPEG/PNG encoding: CPU-intensive, runs in executor
  • HTTP upload to device: Uses aiohttp (async-native)

See: https://developers.home-assistant.io/docs/asyncio_blocking_operations/

Frontend Panel

The integration includes a custom panel for configuring displays via the HA sidebar.

Structure (frontend/src/): geekmagic-panel.ts is the shell (loads config, views, devices, thumbnails; the main page). components/ holds the elements: gm-device-card (live screen, controls, rotation strip), gm-view-editor (draft, preview, inspector, pickers), gm-widget-options (option fields and list editors), gm-screen (the bezel), gm-dialog (native <dialog>), gm-menu (overflow menu). Logic that can be pure is, with vitest tests: view-ops.ts (edits never mutate the stored view), option-visibility.ts, rotation.ts, preview-queue.ts (debounced, latest-only renders), format.ts, widget-previews.ts (which picker preview fits a slot), animation-preview.ts (autoplay: debounced, single-flight animated renders and their cache; which displays would show an animated view as a still), minute-timer.ts (thumbnails and the editor preview re-render each minute while visible). api.ts wraps the websocket calls.

Use HA elements whose API is simple and stable (ha-card, ha-button, ha-icon-button, ha-switch, ha-slider, ha-select via select-compat.ts, ha-input, ha-selector, ha-alert, ha-spinner). Dialogs and menus are our own: ha-dialog/ha-dropdown changed API across 2025-26, and ha-circular-progress no longer exists. The panel drives devices through their entities (ids from devices/list, resolved from the registry) and devices/show_view (by id; names are ambiguous).

Building the Frontend

After making changes to the frontend source in custom_components/geekmagic/frontend/:

cd custom_components/geekmagic/frontend
npm install    # First time only
npm run build  # Build production bundle

Important: The built dist/ directory must be committed to git. Users install via HACS which clones the repo directly - there's no build step during installation.

Cache Busting

The panel uses content-hash based cache busting. A SHA256 hash of the JS file is appended to the URL (via ?h={hash} query parameter). When the file content changes, the hash changes, and browsers automatically fetch the new version.

After Frontend Changes

  1. Make changes in frontend/src/
  2. Run npm run build to regenerate dist/
  3. Commit both source and dist changes

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.