agentleFS
adrienbraultadrienbrault/geekmagic-hacs/AGENTS.md

geekmagic-hacs

AGENTS.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: Follow Conventional Commits and create atomic commits as you work: Always run pre-commit before committing: uv run pre-commit run --all This validates tests, linting, formatting, and type checking in one command. HACS detects new versions via GitHub releases. When the user asks for a release, Codex does all of it: bump, wait for CI, tag, push, publish the release with GitHub's…

  • Installs packages
  • Commits and pushes
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 35,040 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository3 other files it gives its agents.

The file

Show its rules and text

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

48 rules. About 0 are common, 14 are distinctive, and 34 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈14

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 34

    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 21
  3. Distinctive:

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

    line 33
  4. Distinctive:

    Commit and push on main:

    line 64
  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 68
  6. 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 84
  7. Distinctive:

    Use high contrast colors (light on dark)

    line 172
  8. Very specific:

    Default: THEME_TEXT_PRIMARY (white).

    line 226
  9. Distinctive:

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

    line 229
  10. Very specific:

    Don't hardcode SYSTEM_* in widget code — the regression test tests/test_watchos_design_system.py::TestNoHardcodedSystemColors guards this.

    line 243
  11. Very specific:

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

    line 246
  12. Distinctive:

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

    line 247
  13. Very specific:

    Don't use Column(justify="center") if the cell is taller than the natural content height — content will cluster centred and waste space.

    line 249
  14. Very specific:

    Default to justify="space-evenly" for top-to-bottom content distribution: it puts equal spacing before, between, and after the children, …

    line 251
  15. Very specific:

    Don't use absolute Padding(top=..., bottom=...) for layout when child heights vary with cell size — they only work at the exact tuning …

    line 260
  16. Very specific:

    Prefer flex-style Column/Row with Spacer.

    line 262
  17. Very specific:

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

    line 266
  18. Very specific:

    Use ctx.track_color(tint) for any bar/ring/arc track — picks up the theme's tint_track setting automatically.

    line 268
  19. Very specific:

    Use ctx.fit_text() for hero values that should auto-scale to fill their box — guarantees the value stays inside its budget.

    line 270
  20. Very specific:

    Use the BarGauge factory's mode="auto" (default) — it picks compact/stacked/vertical for you.

    line 272
  21. Distinctive:

    Use these for new widgets - they scale proportionally to container height:

    line 281
  22. Very specific:

    Prefer semantic sizes (primary, secondary, tertiary) for new code

    line 330
  23. Very specific:

    Use ctx.fit_text() when text should fill available space

    line 331
  24. Very specific:

    Add bold=True for values that need emphasis

    line 332
  25. Distinctive:

    Never specify pixel sizes directly

    line 333
  26. Distinctive:

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

    line 345
  27. Very specific:

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

    line 356
  28. Distinctive:

    Add regression tests when fixing bugs

    line 358
  29. Very specific:

    Run pytest and pre-commit before commits

    line 359
  30. Distinctive:

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

    line 387
  31. Very specific:

    Add to WIDGET_CLASSES in coordinator.py

    line 395
  32. Very specific:

    Add tests in tests/widgets/

    line 396
  33. Very specific:

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

    line 400
  34. Very specific:

    Use widgets/layout_helpers.py for common rendering patterns:

    line 415
  35. Distinctive:

    When adding a new layout, update these files:

    line 429
  36. Very specific:

    Add entry to layoutConfig object with CSS class and cell count

    line 441
  37. Very specific:

    Add CSS grid styles for the layout icon visualization in the <style> section

    line 442
  38. Very specific:

    Run npm run build in frontend/ directory to rebuild

    line 443
  39. Very specific:

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

    line 448
  40. Very specific:

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

    line 479
  41. Very specific:

    Outside tables: always use width="200" for consistency across Dashboard Samples, Binary Sensor States, Domain Icons, Layout Examples, etc.

    line 481
  42. Very specific:

    Create implementation in entities/<platform>.py

    line 502
  43. Very specific:

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

    line 503
  44. Very specific:

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

    line 504
  45. Very specific:

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

    line 523
  46. Very specific:

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

    line 549
  47. Very specific:

    Run npm run build to regenerate dist/

    line 566
  48. Distinctive:

    Commit both source and dist changes

    line 567

≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.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
AGENTS.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
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

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, Codex 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. Report the release URL and what it contains (the generated notes' PR list).

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
├── device.py         # HTTP API client for GeekMagic
├── renderer.py       # Pillow image generation
├── const.py          # Constants and config keys
├── widgets/          # Widget components
│   ├── base.py       # Widget base class
│   ├── clock.py      # Clock widget
│   ├── entity.py     # HA entity display
│   ├── media.py      # Media player widget
│   ├── chart.py      # Sparkline chart
│   ├── 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
│   ├── entity.py     # Base GeekMagicEntity class
│   ├── number.py     # Number entities (brightness, etc.)
│   ├── select.py     # Select entities (layout, widget type)
│   ├── switch.py     # Switch entities (boolean options)
│   ├── text.py       # Text entities (names, labels)
│   ├── 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
├── text.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

  1. Coordinator triggers update on interval
  2. Layout calculates widget rectangles (slots)
  3. Each widget renders into its slot using Pillow
  4. Image converted to JPEG and uploaded to device

Widget Interface

class Widget(ABC):
    def render(self, ctx: RenderContext, hass) -> None:
        """Draw widget using the render context (local coordinates)."""

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

Layout Interface

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

    def render(self, renderer, draw, hass) -> None:
        """Render all widgets in their slots."""

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

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 role sentinels from widgets/components.py, never hardcoded SYSTEM_BLUE/SYSTEM_ORANGE/etc. The sentinels resolve to the active theme's palette at render time.

Available sentinels (resolve to theme.<role>):

SentinelUse for
THEME_TEXT_PRIMARYDefault for hero values (white-ish on dark themes)
THEME_TEXT_SECONDARYSupporting info (dates, units, "Sunny" condition)
THEME_TEXT_TERTIARYCaps captions, very-low-priority text
THEME_PRIMARYBrand accent — fallback for chart / progress
THEME_SECONDARYNight, lightning, less-prominent accents
THEME_SUCCESSON / connected / wind
THEME_WARNINGSunny / hot temp / heating / caution
THEME_ERROROff / disconnected / extreme / preheating
THEME_INFOCool / cold / water / rain / cooling / humidity
THEME_MUTEDIdle / off / fog / disabled

Rule of thumb for hero value colour:

  • Default: THEME_TEXT_PRIMARY (white). Use this for entity value, clock time, weather temp, climate temp, multi-progress hero, bar-gauge compact value.
  • 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 error red.
    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_* in widget code — the regression test tests/test_watchos_design_system.py::TestNoHardcodedSystemColors guards this.
  • Don't import directly from widgets/theme.py for colour values.
  • 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 use Column(justify="center") if the cell is taller than the natural content height — content will cluster centred and waste space. Default to justify="space-evenly" for top-to-bottom content distribution: it puts equal spacing before, between, and after the children, which reads better in most cells than space-between (which pins the first/last children flush to the edges and can leave them feeling crowded). Only fall back to space-between when the cell is so short that any breathing room would push content off screen, or when you specifically want the first/last items hard against the cell edge. For Rows (horizontal), space-between is still the right call (label left / value right pattern).
  • Don't use absolute Padding(top=..., bottom=...) for layout when child heights vary with cell size — they only work at the exact tuning point. Prefer flex-style Column/Row with Spacer.

Do

  • Read tests/test_watchos_design_system.py before adding a widget — it documents the contract.
  • Use ctx.track_color(tint) for any bar/ring/arc track — picks up the theme's tint_track setting automatically.
  • Use ctx.fit_text() for hero values that should auto-scale to fill their box — guarantees the value stays inside its budget.
  • Use the BarGauge factory's mode="auto" (default) — it picks compact/stacked/vertical for you.

Font Sizing System

Fonts are automatically scaled based on container height. Two naming systems are supported:

Semantic Sizes (Preferred)

Use these for new widgets - they scale proportionally to container height:

SizeRatioUse Case
primary35%Main value (clock time, large number)
secondary20%Supporting info (date, unit)
tertiary12%Labels, captions
# Get font with semantic size
font = ctx.get_font("primary", bold=True)
font = ctx.get_font("secondary")
font = ctx.get_font("tertiary", adjust=-1)  # Slightly smaller

Auto-Fit Text

For text that should fill available space (like clock displays):

# Get largest font that fits within bounds
font = ctx.fit_text("12:45", max_width=ctx.width * 0.95)
font = ctx.fit_text("Hello", max_width=100, max_height=50, bold=True)

Relative Adjustments

Fine-tune sizes with adjust parameter (-2 to +2, each step is ~15%):

font = ctx.get_font("secondary", adjust=+1)  # 15% larger
font = ctx.get_font("primary", adjust=-1)  # 15% smaller

Legacy Sizes

Still supported for backward compatibility:

Size NameUse Case
tinySmall labels
smallLabels, status
regularStandard text
mediumEmphasized values
largePrimary values
xlargeHero values
hugeMaximum emphasis

Best practices:

  • Prefer semantic sizes (primary, secondary, tertiary) for new code
  • Use ctx.fit_text() when text should fill available space
  • Add bold=True for values that need emphasis
  • Never specify pixel sizes directly

Testing

Tests are organized by component:

  • tests/test_device.py - HTTP client tests
  • tests/test_renderer.py - Pillow rendering 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

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

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() and optionally get_entities()
  4. Register in widgets/__init__.py
  5. Add to WIDGET_CLASSES in coordinator.py
  6. Add tests in tests/widgets/

Widget Helper Functions

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

from ..widgets.helpers import (
    truncate_text,  # Truncate long text with ellipsis
    extract_numeric,  # Get float from entity state
    resolve_label,  # Get label from config or friendly_name
    calculate_percent,  # Calculate percentage in range
    is_entity_on,  # Check binary state
    get_unit,  # Get unit of measurement
)

Layout Helper Functions

Use widgets/layout_helpers.py for common rendering patterns:

from ..widgets.layout_helpers import (
    layout_icon_label_value,  # [Icon] [Label] ... [Value]
    layout_centered_value,  # Centered value with label below
    layout_bar_with_label,  # Progress bar with label/value above
    layout_list_rows,  # Calculate row positions for lists
    draw_title,  # Draw title at top
)

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 and add to LAYOUT_SLOT_COUNTS
  • coordinator.py - Add to LAYOUT_CLASSES dict

2. Frontend

  • frontend/src/geekmagic-panel.ts:
    • Add entry to layoutConfig object with CSS class and cell count
    • Add CSS grid styles for the layout icon visualization in the <style> section
  • Run npm run build in frontend/ directory to rebuild

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)")
  • README.md - Add to "Layout Examples" section and "Layout Types" table

4. Tests

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

Samples (README images)

samples/ holds the README's rendered device images. 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.

CI keeps them 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.

README Image Conventions

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

  • Outside tables: always use width="200" for consistency across Dashboard Samples, Binary Sensor States, Domain Icons, Layout Examples, 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.

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.