feat(dev): preview a plugin's Vegas strip in the dev server

The dev server's View selector gains "Vegas strip (live elements)" and
"Vegas strip (plain Vegas content)": the plugin's block of the Vegas ticker,
laid out by the ticker's own code (render_vegas_strip, as render_plugin.py
--vegas uses), with its live elements listed. /api/render takes
"vegas": "live" | "plain"; the display view is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chuck
2026-09-30 20:14:01 -04:00
co-authored by Claude Opus 5.5
parent 559ef14a5c
commit f96c815e0e
3 changed files with 121 additions and 4 deletions
+54 -3
View File
@@ -200,12 +200,21 @@ def api_plugin_defaults(plugin_id):
return jsonify({'defaults': defaults})
#: /api/render "vegas" values: the plugin's block of the Vegas strip, built
#: from its live elements (falling back to its Vegas content, as the ticker
#: does) or from its ordinary Vegas content only.
VEGAS_VIEWS = ('live', 'plain')
def _render_once(plugin_id, plugin_dir, manifest, config, mock_data, width, height,
skip_update):
skip_update, vegas=None):
"""Render one plugin at one size. Returns the /api/render response dict.
A fresh plugin instance per call, mirroring the safety harness, so sizes
never share state.
never share state. With ``vegas`` set ('live' or 'plain') the image is the
plugin's block of the Vegas strip instead of its display(), laid out by
the ticker's own code (src/plugin_system/testing/vegas.py), and the
response lists where each live element sits in it.
"""
from src.plugin_system.testing import VisualTestDisplayManager, MockCacheManager, MockPluginManager
from src.plugin_system.plugin_loader import PluginLoader
@@ -243,6 +252,10 @@ def _render_once(plugin_id, plugin_dir, manifest, config, mock_data, width, heig
logger.warning("update() raised for plugin %s", plugin_id, exc_info=True)
warnings.append(f"update() raised: {type(e).__name__} — see server log")
if vegas:
return _vegas_response(plugin_id, plugin_instance, display_manager, vegas,
start_time, errors, warnings)
# Run display()
try:
plugin_instance.display(force_clear=True)
@@ -262,6 +275,40 @@ def _render_once(plugin_id, plugin_dir, manifest, config, mock_data, width, heig
}
def _vegas_response(plugin_id, plugin_instance, display_manager, vegas, start_time,
errors, warnings):
"""The /api/render response for the Vegas strip view."""
import base64
import io
from src.plugin_system.testing.vegas import render_vegas_strip
block, layout = None, []
try:
block, layout = render_vegas_strip(plugin_instance, plugin_id, display_manager,
live=(vegas == 'live'))
except Exception as e:
logger.warning("Vegas render raised for plugin %s", plugin_id, exc_info=True)
errors.append(f"Vegas render raised: {type(e).__name__} — see server log")
if block is None:
if not errors:
errors.append("The plugin has no Vegas content")
block = display_manager.image
elif vegas == 'live' and not layout:
warnings.append("No live elements: this is the plugin's ordinary Vegas content")
buffer = io.BytesIO()
block.convert('RGB').save(buffer, format='PNG')
return {
'image': 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii'),
'width': block.width,
'height': block.height,
'render_time_ms': round((time.time() - start_time) * 1000, 1),
'errors': errors,
'warnings': warnings,
'live_elements': [{'key': key, 'x': x, 'width': width} for x, key, width in layout],
}
def _trusted_plugin_dir(plugin_dir: Path) -> Optional[Path]:
"""Re-derive a plugin directory from the search dirs' own listings.
@@ -333,6 +380,10 @@ def api_render():
if not (MIN_HEIGHT <= height <= MAX_HEIGHT):
return jsonify({'error': f'height must be between {MIN_HEIGHT} and {MAX_HEIGHT}'}), 400
vegas = data.get('vegas') or None
if vegas is not None and vegas not in VEGAS_VIEWS:
return jsonify({'error': f'vegas must be one of {", ".join(VEGAS_VIEWS)}'}), 400
try:
plugin_dir, manifest, config, mock_data, skip_update = _parse_render_request(data)
except LookupError:
@@ -345,7 +396,7 @@ def api_render():
try:
result = _render_once(data['plugin_id'], plugin_dir, manifest, config,
mock_data, width, height, skip_update)
mock_data, width, height, skip_update, vegas=vegas)
except Exception:
app.logger.exception('plugin load failed during render')
return jsonify({'error': 'Failed to load plugin; see server log'}), 500
+18 -1
View File
@@ -247,6 +247,19 @@
</div>
</details>
<!-- What to render: the plugin's screen, or its block of the Vegas strip -->
<div class="flex items-center gap-2">
<label for="viewSelect" class="text-xs whitespace-nowrap" style="color: var(--text-secondary);">View</label>
<select id="viewSelect" onchange="onConfigChange()"
class="flex-1 px-2 py-1.5 rounded-lg text-xs"
style="background: var(--bg-primary); color: var(--text-primary); border: 1px solid var(--border-color);"
title="Vegas strip: the plugin's block of the Vegas ticker, laid out as the ticker lays it out">
<option value="">Display</option>
<option value="live">Vegas strip (live elements)</option>
<option value="plain">Vegas strip (plain Vegas content)</option>
</select>
</div>
<!-- Render buttons -->
<div class="flex gap-2">
<button onclick="renderPlugin()" id="renderBtn"
@@ -489,6 +502,7 @@
width: width,
height: height,
mock_data: mockData,
vegas: document.getElementById('viewSelect').value || null,
}),
});
@@ -510,8 +524,11 @@
updateZoom();
// Show render time
const live = data.live_elements;
document.getElementById('renderTimeText').textContent =
`${data.render_time_ms}ms`;
`${data.render_time_ms}ms` + (live ? ` · ${data.width}px strip, ` +
`${live.length} live element(s)` +
(live.length ? `: ${live.map(e => e.key).join(', ')}` : '') : '');
// Show warnings/errors
showMessages(data.errors || [], data.warnings || []);
+49
View File
@@ -0,0 +1,49 @@
"""scripts/dev_server.py's Vegas strip view, on the stub fixture plugin."""
import importlib.util
from pathlib import Path
import pytest
REPO = Path(__file__).resolve().parent.parent
STUB = REPO / "test" / "fixtures" / "plugins" / "vegas-live-stub"
@pytest.fixture
def client(monkeypatch):
spec = importlib.util.spec_from_file_location("dev_server_vegas_under_test",
REPO / "scripts" / "dev_server.py")
dev_server = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dev_server)
monkeypatch.setattr(dev_server, "find_plugin_dir", lambda pid: STUB)
monkeypatch.setattr(dev_server, "_trusted_plugin_dir", lambda d: STUB)
return dev_server.app.test_client()
def _render(client, **extra):
return client.post("/api/render", json={"plugin_id": "vegas-live-stub", "width": 192,
"height": 48, "config": {"enabled": True},
**extra})
def test_the_live_strip_lists_its_elements(client):
data = _render(client, vegas="live").get_json()
assert data["image"].startswith("data:image/png;base64,")
assert data["height"] == 48 and data["width"] > 192
keys = [e["key"] for e in data["live_elements"]]
assert keys[:2] == ["card:0", "card:1"] and "map" in keys
assert not data["errors"]
def test_the_plain_strip_has_no_live_elements(client):
data = _render(client, vegas="plain").get_json()
assert data["live_elements"] == [] and not data["errors"]
def test_the_display_view_is_unchanged(client):
data = _render(client).get_json()
assert (data["width"], data["height"]) == (192, 48)
assert "live_elements" not in data
def test_an_unknown_view_is_refused(client):
assert _render(client, vegas="sideways").status_code == 400