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
In this repository3 other files it gives its agents.
- AGENTS.mdAGENTS.md
- geekmagic-reverse-engineerSkill
- release-highlightsSkill
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
- Very specific: line 7
Use uv for all Python operations:
- Distinctive: line 48
Follow Conventional Commits and create atomic commits as you work:
- Distinctive: line 60
Create small, focused commits that each represent a single logical change:
- Distinctive: line 91
Commit and push on main:
- Very specific: line 95
Wait for CI, HACS and Hassfest to pass on the bump commit (gh run list --branch main, gh run watch <id>).
- Very specific: line 105
Add the Highlights section below the generated notes with the release-highlights skill (.claude/skills/release-highlights/), and run its …
- Distinctive: line 115
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 …
- Very specific: line 171
All drawing happens in the Blitz HTML/CSS engine via the blitz-py package (Stylo CSS + Taffy layout + Parley text + Vello raster — no …
- Very specific: line 241
Animated path (opt-in): when the device's Animations switch is on and a placed widget returns `is_animated() == True, the coordinator calls …
- Very specific: line 279
Every engine call goes through engine.get_engine() (or engine_available() for "usable and above the floor").
- Very specific: line 320
All Python-side fitting is open-loop (predict, then draw) and funnels through _textfit._ref_width, which sanitizes degenerate engine …
- Very specific: line 352
No container queries. filter does blur() and drop-shadow() only: the colour filters (grayscale(), brightness()...) are ignored, and only …
- Distinctive: line 400
Use high contrast colors (light on dark)
- Distinctive: line 424
The value is the widget: Every cell spends its height on the hero.
- Very specific: line 514
Default: no explicit color (body text is var(--text-primary)).
- Distinctive: line 517
Use a role tint only when one of these narrow exceptions applies:
- Very specific: line 532
Don't hardcode SYSTEM_* colors or hex literals in widget code — the regression test tests/test_watchos_design_system.py guards this.
- Very specific: line 535
Don't import from widgets/theme.py for colour values in widgets.
- Distinctive: line 536
Don't tint a hero value just because it "looks nice" — follow the rule above.
- Very specific: line 538
Don't put style="display: flex" inline on an element that carries a .hide-* class — inline styles defeat the media-query hide.
- Very specific: line 540
Don't rely on text-overflow: ellipsis or overflow: hidden for widget text — overflow: hidden crops glyph ascenders/descenders on tight …
- Very specific: line 544
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=…)).
- Very specific: line 551
Read tests/test_watchos_design_system.py before adding a widget — it documents the contract.
- Very specific: line 553
Use card_html() from widgets/_card.py for the standard caption/hero/chips card — consistency for free.
- Very specific: line 594
Use kit classes; add inline style only for widget-specific layout.
- Distinctive: line 611
All pytest tests use mocks and don't require a real device or Home Assistant instance.
- Very specific: line 650
Use core interfaces (hass.states, hass.services) instead of integration details
- Distinctive: line 652
Add regression tests when fixing bugs
- Very specific: line 653
Run pytest and pre-commit before commits
- Distinctive: line 681
When that happens the fix belongs on main, not in the contributor's branch.
- Very specific: line 697
Add tests in tests/widgets/
- Very specific: line 698
Document it: add a factory to generate_widget_sizes() in scripts/generate_samples.py (renders every cell size), a section in …
- Very specific: line 708
Use helper functions from widgets/helpers.py for common operations:
- Distinctive: line 734
When adding a new layout, update these files:
- Very specific: line 753
Run uv run python scripts/update_samples.py to generate images (CI also regenerates them on PRs — see "Samples (README images)")
- Very specific: line 822
When embedding sample/screenshot images of device renders (240x240 PNGs from samples/) in README.md or docs/:
- Very specific: line 825
Outside tables: always use width="200" for consistency across dashboard samples, binary sensor states, domain icons, layouts, etc.
- Very specific: line 846
Create implementation in entities/<platform>.py
- Very specific: line 847
Create stub at custom_components/geekmagic/<platform>.py that re-exports async_setup_entry
- Very specific: line 848
Add Platform.<PLATFORM> to PLATFORMS list in __init__.py
- Very specific: line 867
Sleep: Use asyncio.sleep() instead of time.sleep()
- Very specific: line 905
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, …
- Very specific: line 915
After making changes to the frontend source in custom_components/geekmagic/frontend/:
- Very specific: line 932
Run npm run build to regenerate dist/
- Distinctive: line 933
Commit both source and dist changes
≈ “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.
Files
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 hooksRunning 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, thengeekmagic/preview/render), authenticated with the token indev/.state/token. GET http://127.0.0.1:<FAKE_PORT>/_fake/statereturns 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 itsgeekmagic/preview/renderoutput must be byte-identical to it. - Ports live in
dev/.state/ports.env. Use127.0.0.1, notlocalhost: the project venv's aiodns breaks onlocalhostlookups.
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 featurefix:Bug fixrefactor:Code refactoring (no functional change)docs:Documentation onlytest:Adding/updating testschore:Maintenance (deps, config, tooling)style:Formatting, whitespace (no code change)
Atomic Commits
Create small, focused commits that each represent a single logical change:
- After implementing a feature → commit the feature
- After fixing a bug → commit the fix
- After adding tests → commit the tests
- 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")
- 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
- Patch (
- On an up-to-date
main(git pull --ff-only), updateversionincustom_components/geekmagic/manifest.json - Commit and push on
main:chore: bump version to X.Y.Z - 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. - 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 - Publish the release from that tag:
gh release create X.Y.Z --verify-tag --generate-notes --title X.Y.Z - Add the Highlights section below the generated notes with the
release-highlightsskill (.claude/skills/release-highlights/), and run its verifier. - Report the release URL and what it contains (the generated notes' PR list and the highlights).
Critical rules
- Tag must match
manifest.jsonversion exactly (HA core readsmanifest.jsonand a mismatch breaks update detection): checkgit show <bump-sha>:custom_components/geekmagic/manifest.jsonbefore tagging - Tag the bump commit, not an earlier one — otherwise the tagged tree still has the old version
- Tag format:
X.Y.Z(no leadingv— 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 translationsKey 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.
- Coordinator triggers update on interval
- Layout calculates widget rectangles (slots) — pure geometry
- One
render_layerscall composites the whole screen engine-side: the theme backdrop layer (theme.backdrop_css), one layer per widget cell (each widget'srender_htmlfragment wrapped byhtmldoc.build_cell_document— theme CSS variables + fluid kit +theme.chrome_css), and the optionaltheme.overlay_csslayer (scanlines, vignettes) on top. Each cell layer keeps its own CSS viewport (vmin/vwand@mediarespond to the CELL size) and is CLIPPED to its rect by the engine. Themes withglow_effect(neon) paint each cell once blurred beneath its sharp pass (per-layerblur/opacity). - 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 thanFORCED_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'sfont_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()(orengine_available()for "usable and above the floor"). Neverimport blitz_py, and no module-level engine state (HAS_*constants,try: import) —tests/test_engine_probe.pychecks in a fresh interpreter that importing the integration and its platforms leavesblitz_pyout ofsys.modules. Never memoize an engine-less answer either (_FontRegistry,_textfit._ref_width): the gate can open after a first call. async_setupholds the gate and starts ONE self-test per HA process (engine_probe, task under aHassKey). Any new render path in HA awaitsasync_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'ssys.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 throughLayout.render; a new engine capability adopted in production belongs in that frame too. - A pass is cached in
Storeunder 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_crashedrepair 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 autouseprobe_spawnsfixture (tests/conftest.py).
- 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
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: ellipsispaints "…" only since blitz-py 0.7.0, and only on a singlenowrapline;overflow: hiddencuts glyphs mid-stroke — on tight line-heights (.t-hero's 0.85) it also crops ascenders/descenders, andoverflow-xclips BOTH axes. So CSS can contain overflow but never resolve it nicely: keep truncating long strings in Python (helpers.truncate_text, or the measured_textfitmetrics 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 intofit_herodisables 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 fromheight:100%against a flex parent — measure the plot box in Python and pass a matchingaspect/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'sdisplay: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 isposition: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: noneor they collapse to hairlines. white-space: normalwrapping 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.pybuilds card geometry on top of it. - No container queries.
filterdoesblur()anddrop-shadow()only: the colour filters (grayscale(),brightness()...) are ignored, and only the first function of a list applies.text-shadowandbackground-clip: textwork 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 stateDisplay 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'sspace-evenly. - Sibling harmony. Widgets report
hero_hint(ctx, state) -> (kind, px);Layout._hero_capscaps 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 fromctx.extra["hero_px_cap"]in any widget that fits a hero.
Goals
- 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. - 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.
- 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.
- 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 variable | Use 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:
- 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. - Status state where the colour IS the meaning —
ONin success green,OFFin the muted tone (red is for problems the user chose to paint red, never the default off state). - Mode chip where the tint reinforces an explicit mode label
(climate
HEATINGchip in warning).
- 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
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 testtests/test_watchos_design_system.pyguards this. (Neutralrgba(255,255,255,0.x)tracks/overlays are the exception.) - Don't
importfromwidgets/theme.pyfor 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: ellipsisoroverflow: hiddenfor widget text —overflow: hiddencrops glyph ascenders/descenders on tight line-heights, and the "…" only covers onenowrapline. 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 keepspace-evenly; tall columns group their bands (see progress) rather than fling them to the cell's ends.
Do
- Read
tests/test_watchos_design_system.pybefore adding a widget — it documents the contract. - Use
card_html()fromwidgets/_card.pyfor the standard caption/hero/chips card — consistency for free. - Tint gauge tracks with
css_rgba(accent, theme.tint_track_opacity)whentheme.tint_trackis set (see gauge.py). - Attach
.hide-short/.hide-smallto 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:
| Class | Role |
.t-hero | Primary value — as big as the cell allows (weight 700, -0.02em) |
.t-value | Secondary emphasized value |
.t-unit | Unit suffix (secondary color) |
.t-label | Caps caption (secondary color, 0.05em tracking) |
.t-date | Plain secondary line (the clock's date) |
.caption-row / .card-head | Inline / stacked header (see _card.header_html) |
.icon + .i-lg/.i-md/.i-sm | MDI glyphs (embedded font) |
.hide-short | Hidden when cell < 100px tall |
.hide-narrow | Hidden when cell < 100px wide |
.hide-small | Hidden when either dimension < 130px |
.cell / .cell.row | Flex scaffold, space-evenly |
.chips / .chip / .caption-row | Supporting 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
styleonly 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_compactexists for the cases CSS can't express).
Testing
Tests are organized by component:
tests/test_device.py- HTTP client teststests/test_renderer.py- Canvas/encoding teststests/test_config_flow.py- Config flow and options flow teststests/test_integration.py- Integration setup/teardown teststests/widgets/test_widgets.py- Widget teststests/layouts/test_layouts.py- Layout teststests/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:
- https://github.com/MatthewFlamm/pytest-homeassistant-custom-component
- https://developers.home-assistant.io/docs/development_testing/
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
pytestandpre-commitbefore commits - Never reach into
hass.databy string key, and never call a core API the release notes mark deprecated. Both work right up until they don't: HA'shass.datakeys areHassKeyobjects that only happen to subclassstr, so a raw lookup returnsNoneand silently drops data instead of raising.dr.async_get(hass)/ar.async_get(hass)/er.async_get(hass), anddr.async_entries_for_config_entryoverasync_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:
| Job | Resolves to | As of 2026-09 |
| Python 3.12 | oldest ptc that still supports it | HA 2025.1.4 |
| Python 3.13 | a ptc a few months back | HA 2026.2.3 (stable) |
| Python 3.14 | the newest ptc | HA 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
- Create
custom_components/geekmagic/widgets/mywidget.py - Extend
Widgetbase class - Implement
render_html()and optionallyget_entities() - Register in
widgets/__init__.py(_ALL_WIDGETS— WIDGET_CLASSES and schemas derive from it) - Give the
SCHEMAthe panel's picker metadata:icon(mdi),category(values/home/time/history/pictures/custom), a one-linedescription, anduses_label: Falseif the widget ignores the label. An option that only applies to some choices getsvisible_when({"style": ["bar"]}: every key must match one of its values, against the stored value or the option's default).tests/test_panel_metadata.pychecks all of it. - Add tests in
tests/widgets/ - Document it: add a factory to
generate_widget_sizes()inscripts/generate_samples.py(renders every cell size), a section indocs/widgets.md(size row + options), and a row in the README's Widgets table (fullscreen / 2×2 / 3×3 only) - Give it a picker preview: map its type to a sample name in
frontend/src/widget-previews.json(or add it toWITHOUT_PREVIEWintests/test_widget_previews.py), then runscripts/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 extendingLayoutlayouts/__init__.py- Import and export the new classconst.py- AddLAYOUT_<NAME>constant, add it toLAYOUT_SLOT_COUNTS, and give it a display name inLAYOUT_NAMESview.py- Add toLAYOUT_CLASSESdict
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 togenerate_layout_samples()- Run
uv run python scripts/update_samples.pyto 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.pyIt 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 absolutehttps://raw.githubusercontent.com/adrienbrault/geekmagic-hacs/main/samples/...URLs, so images render in HACS too. Indocs/, use relative paths (../samples/...): only GitHub renders those pages, and relative paths also work on a PR branch before its samples reachmain. - Outside tables: always use
width="200"for consistency across dashboard samples, binary sensor states, domain icons, layouts, etc. - Inside tables: omit the
widthattribute — 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
- Create implementation in
entities/<platform>.py - Create stub at
custom_components/geekmagic/<platform>.pythat re-exportsasync_setup_entry - Add
Platform.<PLATFORM>toPLATFORMSlist 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(),pathlibread/write - Network I/O: urllib operations (use
aiohttpinstead) - Heavy computation: CPU-intensive tasks like image rendering
- Sleep: Use
asyncio.sleep()instead oftime.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 bundleImportant: 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
- Make changes in
frontend/src/ - Run
npm run buildto regeneratedist/ - Commit both source and dist changes
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
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.

