Files
LEDMatrix/test/test_schema_style_expansion.py
68d03ea260 feat: universal element style system — resolver, schema expansion, live preview (#394)
* feat(element-style): universal per-element style resolver

One shared implementation of the three things every customizable plugin
re-invented: a font loader, the customization.layout x/y-offset reader,
and the "did the user actually override this font?" check.

The override check is the load-bearing piece: the web UI's save flow
writes full schema defaults into config.json on every save, and the
plugin manager merges defaults again before instantiation, so key
presence never means user intent. The resolver compares against the
plugin's own schema defaults (via schema_manager), degrading to
caller-supplied classic defaults when unavailable. This retires the
hand-maintained _CLASSIC_FONT_DEFAULTS dicts that shipped broken twice.

The loader is a superset of the four per-plugin variants: alias
resolution (baseball), truetype for TTF/OTF/BDF (FreeType loads BDF at
native size), .pil sidecar fallback for BDF (football), fallback font,
PIL default — never raises. Also introduces the text_color convention
([r,g,b], absent = keep the plugin's hardcoded color).

BasePlugin gains a lazy style_resolver property (invalidated on config
change) and element_style() sugar; standalone helpers receive the
resolver from their owning plugin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

* feat(element-style): x-style-elements schema expansion + color provenance

Plugins can now declare styleable display elements once, compactly, on
their customization schema ("x-style-elements") instead of hand-copying
the ~50-line font/font_size/text_color/offset property blocks (currently
duplicated 52x across the plugin monorepo). SchemaManager.load_schema
expands declarations before caching, so the config form, save path,
validation, and defaults generation all see the same shape; the single
expansion implementation lives in src.element_style and is also applied
by defaults_from_schema_file, keeping the web UI's view and a plugin's
raw-schema-file view of the defaults provably identical (parity test).

Generated blocks use only widgets the config form already renders
(font-selector, color-picker, number inputs) and update x-propertyOrder
when present (the template only renders listed keys). Expansion is
idempotent, never mutates its input or the cached/on-disk schema, and a
hand-written block for the same element always wins.

Color gets the same provenance rule as fonts: the web form always posts
the RGB inputs, so a saved config carries the schema-default color
whether or not the user touched it — the resolver now only honors a
color that DIFFERS from the schema default, and keeps the plugin's
classic (possibly state-dependent, e.g. gold-on-touchdown) color
otherwise.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

* feat(web): live plugin preview on the config page

Adds POST /api/v3/plugins/preview: renders a plugin headlessly with the
CANDIDATE (unsaved) config and returns a PNG — so users can see exactly
what the panel will show before saving, at their real panel size (from
display.hardware) or a chosen test size.

Two extractions make it drift-proof rather than parallel-implemented:
- dev_server's _render_once moves to
  src/plugin_system/testing/render_service.py (pure PIL via
  VisualTestDisplayManager, install_deps=False always — safe in the web
  process, which never touches display hardware); the dev server now
  wraps it.
- save_plugin_config's ~350-line form->config conversion is extracted
  verbatim as parse_plugin_config_form and shared by the preview
  endpoint, so preview and save can never interpret the form
  differently.

update() is skipped by default (no network on the request thread);
plugins with a test/harness.json get their mock-data fixture primed
instead, and ?skip_update=0 opts into a live update. The config page
gains a Live Preview panel (HTMX hx-include of the existing form, size
selector, pixelated img fragment) — works for every plugin with zero
per-plugin code, including the x-style-elements font/size/color fields.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

* fix(web): expand x-style-elements in the config-page form render too

pages_v3's plugin-config partial loads config_schema.json directly from
disk rather than through SchemaManager.load_schema, so declared style
elements expanded everywhere EXCEPT the form the user actually sees.
Found live on the devpi: the API served the expanded schema and the
save path validated against it, but the config page rendered no
font/color/offset fields. Apply the same (idempotent) expansion here.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

* fix(web): preview size selector — htmx caches hx-post, use hx-vals

Found live on the devpi: selecting a preview size did nothing because
htmx snapshots the request path when it processes the button, so the
size dropdown's onchange mutation of hx-post never took effect. The size
now travels as a __preview_size=WxH form field attached via hx-vals
(evaluated at request time); the endpoint honors it (query args still
win for API callers) and strips it before form parsing so it can't leak
into the candidate config.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

* fix(web): allowlist plugin_id in the preview endpoint's dir lookup

Same defense as the dev server's find_plugin_dir (and pages_v3's
existing pattern): plugin_id arrives in request input and is used to
build filesystem paths — reject anything outside ^[a-zA-Z0-9_-]{1,64}$
before touching the filesystem.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

* fix: harden preview + resolver edges found in self-review

- extract_schema_defaults now matches SchemaManager's array handling
  ([] for arrays without defaults, [item] for item-level defaults) —
  the documented parity guarantee was false for array-typed properties;
  parity test extended to cover them.
- render_plugin_once calls plugin cleanup() in a finally (image captured
  first — cleanup may clear the canvas): preview instances could leak
  sessions/threads per request in the long-running web process.
- Preview JSON path deep-merges the candidate onto the saved config,
  matching the form path — a shallow update() silently dropped saved
  sibling values in any nested section the candidate touched.
- Preview render is bounded (15s, 504 on timeout, daemonized worker):
  a hanging plugin display() no longer pins a web worker forever.
- ElementStyleResolver.is_for(config): public staleness check for
  callers that cache a resolver, instead of poking _config.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

* fix(render-service): adopt the dev server's exception-detail policy

Port c6962701's convention into the shared render service (which
supersedes the inline _render_once it patched): full tracebacks to the
server log via exc_info, only the exception class name to the client.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FqzC1nzTWL4kaqgMaQZFam

---------

Co-authored-by: Chuck <chuck@example.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 10:40:03 -04:00

274 lines
12 KiB
Python

"""Tests for x-style-elements schema expansion.
A plugin declares styleable elements once, compactly; expansion generates
the full customization property blocks at schema-load time. The invariants
that matter:
- idempotent (expand(expand(s)) == expand(s)) and the input is never mutated
- both load paths (cached GET, uncached save) see the identical shape
- generated defaults flow into generate_default_config, and saving twice is
round-trip stable (merge_with_defaults produces no churn)
- hand-written property blocks for the same element always win
- defaults_from_schema_file (what plugins use to build resolvers from their
RAW schema file) agrees exactly with the schema manager's expanded view
"""
import copy
import json
import os
import sys
import jsonschema
import pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from src.element_style import ( # noqa: E402
defaults_from_schema_file,
expand_style_elements,
extract_schema_defaults,
get_style_elements,
)
from src.plugin_system.schema_manager import SchemaManager # noqa: E402
PRESS_START = "PressStart2P-Regular.ttf"
def _declared_schema():
return {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"enabled": {"type": "boolean", "default": True},
"customization": {
"type": "object",
"title": "Display Customization",
"x-style-elements": {
"score_text": {
"title": "Game Score",
"font": {"default": PRESS_START},
"size": {"default": 10, "min": 4, "max": 16},
"color": True,
"offsets": True,
},
"detail_text": {
"font": {"default": "4x6-font.ttf"},
"size": {"default": 6},
},
},
"properties": {},
"additionalProperties": False,
},
},
}
class TestExpansionShape:
def test_generates_element_blocks(self):
expanded = expand_style_elements(_declared_schema())
cust = expanded["properties"]["customization"]["properties"]
score = cust["score_text"]
assert score["x-style-managed"] is True
assert score["title"] == "Game Score"
assert score["properties"]["font"]["default"] == PRESS_START
assert score["properties"]["font"]["x-widget"] == "font-selector"
assert score["properties"]["font_size"]["default"] == 10
assert score["properties"]["font_size"]["minimum"] == 4
assert score["properties"]["font_size"]["maximum"] == 16
assert score["properties"]["text_color"]["x-widget"] == "color-picker"
assert score["properties"]["text_color"]["default"] == [255, 255, 255]
assert score["additionalProperties"] is False
def test_color_and_offsets_are_optional(self):
expanded = expand_style_elements(_declared_schema())
cust = expanded["properties"]["customization"]["properties"]
detail = cust["detail_text"]
assert "text_color" not in detail["properties"]
assert detail["title"] == "Detail Text" # prettified from the key
layout = cust["layout"]["properties"]
assert "score_text" in layout
assert "detail_text" not in layout
def test_offsets_block_shape(self):
expanded = expand_style_elements(_declared_schema())
layout = expanded["properties"]["customization"]["properties"]["layout"]
assert layout["x-style-managed"] is True
entry = layout["properties"]["score_text"]
assert entry["properties"]["x_offset"]["default"] == 0
assert entry["properties"]["y_offset"]["default"] == 0
def test_declared_color_default(self):
schema = _declared_schema()
decl = schema["properties"]["customization"]["x-style-elements"]
decl["score_text"]["color"] = {"default": [255, 215, 0]}
expanded = expand_style_elements(schema)
color = (expanded["properties"]["customization"]["properties"]
["score_text"]["properties"]["text_color"])
assert color["default"] == [255, 215, 0]
def test_declaration_survives_expansion(self):
"""The declaration is the element registry for tooling — it must
remain readable from the expanded schema."""
expanded = expand_style_elements(_declared_schema())
assert set(get_style_elements(expanded)) == {"score_text", "detail_text"}
assert set(SchemaManager.get_style_elements(expanded)) == {
"score_text", "detail_text"}
def test_no_declaration_returns_same_object(self):
schema = {"type": "object", "properties": {"enabled": {"default": True}}}
assert expand_style_elements(schema) is schema
def test_valid_draft7(self):
jsonschema.Draft7Validator.check_schema(
expand_style_elements(_declared_schema()))
def test_property_order_updated_when_present(self):
schema = _declared_schema()
schema["properties"]["customization"]["x-propertyOrder"] = []
expanded = expand_style_elements(schema)
order = expanded["properties"]["customization"]["x-propertyOrder"]
# generated elements before layout (the template only renders keys
# in x-propertyOrder when one exists)
assert set(order) == {"score_text", "detail_text", "layout"}
assert order.index("score_text") < order.index("layout")
def test_malformed_declaration_is_harmless(self):
schema = _declared_schema()
schema["properties"]["customization"]["x-style-elements"] = {
"bad": "not a dict", "score_text": {"size": {"default": 10}}}
expanded = expand_style_elements(schema)
cust = expanded["properties"]["customization"]["properties"]
assert "bad" not in cust
assert "score_text" in cust
class TestExpansionInvariants:
def test_idempotent(self):
once = expand_style_elements(_declared_schema())
twice = expand_style_elements(once)
assert once == twice
def test_input_never_mutated(self):
schema = _declared_schema()
snapshot = copy.deepcopy(schema)
expand_style_elements(schema)
assert schema == snapshot
def test_hand_written_block_wins(self):
schema = _declared_schema()
hand_written = {
"type": "object",
"properties": {"font": {"type": "string", "default": "custom.ttf"}},
}
schema["properties"]["customization"]["properties"]["score_text"] = \
copy.deepcopy(hand_written)
expanded = expand_style_elements(schema)
assert (expanded["properties"]["customization"]["properties"]["score_text"]
== hand_written)
def test_hand_written_layout_entry_wins(self):
schema = _declared_schema()
schema["properties"]["customization"]["properties"]["layout"] = {
"type": "object",
"properties": {"score_text": {"type": "object", "properties": {
"x_offset": {"type": "integer", "default": 5}}}},
}
expanded = expand_style_elements(schema)
layout = expanded["properties"]["customization"]["properties"]["layout"]
assert layout["properties"]["score_text"]["properties"]["x_offset"]["default"] == 5
class TestSchemaManagerIntegration:
def _manager_with_schema(self, tmp_path, schema):
plugin_dir = tmp_path / "test-plugin"
plugin_dir.mkdir()
(plugin_dir / "config_schema.json").write_text(json.dumps(schema))
return SchemaManager(plugins_dir=tmp_path)
def test_load_schema_expands(self, tmp_path):
mgr = self._manager_with_schema(tmp_path, _declared_schema())
loaded = mgr.load_schema("test-plugin")
assert "score_text" in loaded["properties"]["customization"]["properties"]
def test_cached_and_uncached_loads_agree(self, tmp_path):
"""The save path uses use_cache=False while the form GET uses the
cache — they must see the identical expanded shape."""
mgr = self._manager_with_schema(tmp_path, _declared_schema())
cached = mgr.load_schema("test-plugin", use_cache=True)
again = mgr.load_schema("test-plugin", use_cache=True)
uncached = mgr.load_schema("test-plugin", use_cache=False)
assert cached == uncached == again
def test_disk_file_untouched(self, tmp_path):
schema = _declared_schema()
mgr = self._manager_with_schema(tmp_path, schema)
mgr.load_schema("test-plugin")
on_disk = json.loads(
(tmp_path / "test-plugin" / "config_schema.json").read_text())
assert on_disk == schema
assert "score_text" not in on_disk["properties"]["customization"]["properties"]
def test_defaults_include_generated_elements(self, tmp_path):
mgr = self._manager_with_schema(tmp_path, _declared_schema())
defaults = mgr.generate_default_config("test-plugin")
assert defaults["customization"]["score_text"]["font"] == PRESS_START
assert defaults["customization"]["score_text"]["font_size"] == 10
assert defaults["customization"]["score_text"]["text_color"] == [255, 255, 255]
assert defaults["customization"]["layout"]["score_text"]["x_offset"] == 0
def test_save_twice_is_round_trip_stable(self, tmp_path):
"""merge_with_defaults(merged, defaults) must be a fixed point —
saving a config twice can't keep growing/altering it."""
mgr = self._manager_with_schema(tmp_path, _declared_schema())
defaults = mgr.generate_default_config("test-plugin")
user_config = {"enabled": True, "customization": {
"score_text": {"font_size": 14}}}
merged_once = mgr.merge_with_defaults(user_config, defaults)
merged_twice = mgr.merge_with_defaults(merged_once, defaults)
assert merged_once == merged_twice
assert merged_once["customization"]["score_text"]["font_size"] == 14
class TestResolverParity:
def test_defaults_from_schema_file_matches_manager_view(self, tmp_path):
"""Plugins build resolvers from their RAW schema file; the web UI
merges defaults from the EXPANDED schema. Both must produce the
same defaults or override detection diverges between contexts."""
schema = _declared_schema()
plugin_dir = tmp_path / "test-plugin"
plugin_dir.mkdir()
schema_path = plugin_dir / "config_schema.json"
schema_path.write_text(json.dumps(schema))
mgr = SchemaManager(plugins_dir=tmp_path)
manager_defaults = mgr.extract_defaults_from_schema(
mgr.load_schema("test-plugin"))
raw_file_defaults = defaults_from_schema_file(str(schema_path))
assert raw_file_defaults == manager_defaults
def test_resolver_treats_generated_defaults_as_untouched(self, tmp_path):
"""End to end: a config saved through the web UI (all generated
defaults baked in) must not read as a user override, and the
schema-default color must not clobber a classic color."""
from src.element_style import ElementStyleResolver
schema_path = tmp_path / "config_schema.json"
schema_path.write_text(json.dumps(_declared_schema()))
defaults = defaults_from_schema_file(str(schema_path))
saved_config = {"enabled": True, "customization": {
"score_text": {"font": PRESS_START, "font_size": 10,
"text_color": [255, 255, 255]},
"layout": {"score_text": {"x_offset": 0, "y_offset": 0}},
}}
resolver = ElementStyleResolver(saved_config, defaults)
style = resolver.style("score_text", classic_font=PRESS_START,
classic_size=10, classic_color=(255, 215, 0))
assert not style.user_forced
assert not style.user_forced_color
assert style.color == (255, 215, 0) # semantic classic color survives
assert style.offset == (0, 0)
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-v"]))