Author or review a reloadable application or Twin HTML/CSS-like runtime surface in LunCoSim. Use this for HUDs, telemetry cards, progress overlays, view switchers, runtime UI bindings, HTML/CSS hot reload, HUI, Flair, EngineExposures, or questions about the limits of the native HTML UI. Use lunco-ui instead for workbench/egui panels and docking internals.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Runtime Ui?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/luncosim-runtime-ui)
---
name: runtime-ui
description: >
Author or review a reloadable application or Twin HTML/CSS-like runtime
surface in LunCoSim. Use this for HUDs, telemetry cards, progress overlays, view
switchers, runtime UI bindings, HTML/CSS hot reload, HUI, Flair,
EngineExposures, or questions about the limits of the native HTML UI. Use
lunco-ui instead for workbench/egui panels and docking internals.
---
# Runtime-authored UI
## Read first
Before changing a runtime surface, read:
1. [`docs/architecture/runtime-authored-ui.md`](../../docs/architecture/runtime-authored-ui.md)
2. [`assets/ui/README.md`](../../assets/ui/README.md)
3. [`skills/lunco-ui/SKILL.md`](../lunco-ui/SKILL.md) when the surface overlaps
egui, the workbench, or docking
4. [`skills/test-via-api/SKILL.md`](../test-via-api/SKILL.md) for live verification
The generic implementation is `lunco-workbench-runtime-ui`; the `luncosim`
windowed host in `crates/lunco-luncosim-ui/src/ui/` supplies app-specific gates,
capture mode, and action handling. Do not assume that `lunica` or a headless
server has this surface manifest.
The committed dependency baseline is `bevy_hui 0.8.0`, `bevy_flair 0.9.0`,
and Bevy `0.20.0`. Verify the lockfile and upstream release notes before
changing it. See the
[dependency baseline](../../docs/architecture/runtime-authored-ui.md#version-and-capability-baseline)
for the Flair fork. The separate
`bevy_hui_widgets 0.6.0` crate provides primitive text-input, slider, and select
components, but is intentionally not a LunCoSim dependency: it does not define
our clipboard, validation, keyboard-navigation, accessibility, or modal
semantics.
## Choose the right layer
Use runtime HTML/CSS for a small authored presentation surface that should be
changed without recompiling Rust: HUDs, status cards, progress overlays,
telemetry summaries, and simple buttons.
Use `lunco-workbench`/egui for the application shell, docking, code editors,
large inspectors, rich text input, complex forms, modal dialogs, and controls
that need semantics not present in the runtime contract. Runtime UI shares
the workbench's dock geometry and pointer ownership. An authored overlay
draws above the shell through the workbench overlay pass.
The standard Twin, file and library Twin browser is the optional
`lunco-workbench-browser` feature layered on the shell; do not recreate its
views in an authored runtime surface.
`lunco-ui::modal` remains the owner for rich dialogs requiring focus, queued
outcomes, editing, validation, or accessibility. The generic runtime surface
also supports a deliberately small authored modal contract: a viewport surface
may declare `modal: true` and an authored `dismiss_action`; visible controls
own their computed input regions and Escape emits that semantic action. Generic
keyed collection hosts provide dynamic rows, while Rhai owns the records,
labels, ordering, visibility, and action meaning. Do not grow this into a
second rich-dialog implementation without a separate typed contract and
acceptance tests.
For tabbed workspaces, prefer one `selection_setting` containing the active
page ID. Rhai handles the tab action and writes that setting; the generic
runtime mounts the matching Twin-authored page under the stable shell. Use the
per-page boolean `setting` form only to preserve an older workspace contract.
Do not mix both selection forms in one workspace.
Twin-authored actions are open-ended semantic identifiers. The reusable
`program-browser` surface publishes typed arrays of records; its HUI row
template is reconciled by the generic keyed collection host. To diagnose a
program row, check the composed child or `programs` target and its live
projection under the primary scene mount. A surface may also
declare a generic dropdown: the manifest supplies the trigger, option source,
key/label/action field names, and Rhai-owned width/max-height sources. The
compact `camera-status` surface is one consumer of that primitive, not a
camera-specific widget. Twin-authored `data_sources` publish typed records for
native controls without a hidden HUI collection host. A dropdown can use
`width_px` and `max_height_px` when no scalar producer is needed, and it anchors
to its pressed HUI control. Dropdowns can copy declared option fields into
their selected action's typed parameter map; the manifest owns the field
mapping while Rhai owns option rows and policy.
`program_editor` owns selection, editor focus, atomic source switching, and
creation for any authored program, regardless of whether its owner is a rover,
lander, route, or another model. Rich source text entry remains in the existing
Rhai editor/REPL until HUI gains tested typed input semantics.
For dynamic semantic controls, use the HUI convention
`on_press="runtime_ui_authored_action" tag:action="{action}"`. Additional
`tag:*` values become a typed `HookValue` parameter map on the generic action
event; the runtime does not concatenate names and values into a protocol
string. This permits Twin-defined actions and dynamic controls without
registering one Rust callback per item. Do not use JavaScript or encode action
payloads as JSON.
Collection hosts retain the Rhai-authored row order, clip their list, and
consume wheel input at the host boundary. They own row lifecycle only; do not
add a per-surface Rust list resource or a fixed row-count view model.
Use stable `id` attributes and `#id` selectors for authored HUI nodes. Flair
supports class selectors, but HUI 0.7 does not turn an HTML `class` attribute
into a `ClassList`; it treats that attribute as an unknown style property.
For a live camera inset, bind the existing feed with `tag:camera_feed="1"`
inside an admitted surface. A descendant may project an exact subject path
with `tag:camera_marker="/World/Site"`. Use snake_case tag keys, explicit
feed selection and dimensions. Require `minimum_scene_items` when an empty
view is invalid. Verify frame zero, missing-source capture blocking and source
restoration; `visual_pending_reasons` reports that gate. See the native image
contract in `docs/architecture/runtime-authored-ui.md`. Never replace it with
periodic screenshots or world-space guide crosses.
Project-owned visibility policy belongs in the active Twin manifest's generic
`[settings]` table. A surface declares `setting` plus `setting_default` in
`runtime_surfaces.json`; Rhai reads/writes the same scope with
`get_twin_setting`/`set_twin_setting`. Keep user-global diagnostics, theme,
input visualisation, and window preferences in `lunco-settings`. Missing Twin
keys use the surface's authored default, so Rust does not grow a field for
each new preference.
## Camera views and configurable mission cards
Windowed LunCoSim supports up to eight live camera windows. Call
`CreateCameraFeed` for an independent id, then
`SetCameraFeed { feed, source: <exact camera gid>, label, width, height }`.
Omitted `feed` selects primary view 1. `RemoveCameraFeed` releases a window;
`InspectCameraFeeds` reports all selections. Native windows provide a camera
picker, resolution menu, new-view button, move, resize and close. Use
`SetCameraFeedResolution { feed, match_window, width, height }` for fixed pixels
or live image-area matching. The menu also copies the app window's current
physical dimensions. Omitted dimensions in `SetCameraFeed` preserve the view's
resolution policy. Allocation limits and rejection details are reported by
`InspectCameraFeeds`; an invalid request preserves the last valid target.
Use two physically separated
native sensor cameras for stereo, and verify both rendered views in the owned
session. See the [render owner contract](../../docs/architecture/render-decoupling.md#live-camera-observations)
and `camera_feed_live.rhai` production acceptance. For grouped navigation and
live depth/noise controls, follow [camera windows](../lunco-ui/SKILL.md#camera-windows-and-image-controls).
Run `scripts/api/test_camera_views.py --port <free-port>` for the windowed
pixel and world-fixed-sky gate. Capture only after the view reports `ready`.
Named guided cards accept `SetGuidedHudLayout { hud, width, text_scale,
draggable }`. Layout is scene scoped and exposed in `InspectGuidedHud`; invalid
bounds reject before mutation. A card's context menu changes the same settings.
Twin Rhai owns which telemetry lines to publish, and can retain chosen groups
through existing Twin settings. `guided_hud_layout.rhai` covers layout admission
and rejection. HUI control surfaces remain configurable through their Twin
manifest, template and stylesheet.
## Authoring workflow
### 1. Define a generic capability namespace
Add or extend an engine-side producer only when the value is not already
available. Publish authoritative, presentation-ready named values through
`EngineExposures`:
```rust
let mut ui = exposures.writer("mission-status");
ui.visible(has_mission);
ui.property("title", mission_title);
ui.property("state", state_label);
ui.property("state_color", "var(--ok-color)");
```
The namespace is a capability boundary shared by HTML, egui, API, telemetry,
and remote consumers. Do not add `domain_to_view`, `vessel_exposure`, or a
widget-specific Rust registry. Resolve source state in the engine producer;
keep markup unaware of ECS/domain types.
Initialize `EngineExposures` and scene-derived producer caches through
`AppSceneExt::init_scene_resource`. Surfaces default to scene lifetime,
including hidden properties and subject identities. Application-owned producers
must explicitly call `retain_across_scenes(namespace)`; never retain a namespace
that can contain Twin-owned values. Change-gated producers that survive a scene
must republish once when their namespace is absent after reset. Remove an
authored namespace with `remove_surface` when its source is deleted or renamed.
The production Twin retirement gate seeds an unsaved authored surface through
`ApplyUsdOp` and uses Rhai `ReadExposures` verdicts across replacement and
same-path reopening.
Engine health follows the same generic path. Read the typed
`EngineHealthSnapshot`/`PhysicsHealthSnapshot` publication and expose named
properties through the ordinary `engine-health` namespace; do not add a HUD
reader for `DiagnosticsStore`, an Avian timing query, or another source-specific
bridge. Native UI, HUI, API, telemetry, and recording consumers all read the
common publication. For scalar participant state, use the shared
`PortRegistry`; do not create a parallel port reader for a HUD.
`SimulationProgress` owner and reason facts are projected into each authored
runtime surface as typed `simulation_progress` data. Let the active Rhai policy
turn those facts into user-facing labels such as `PHYSICS LOADING` or
`WAITING FOR TERRAIN`; the engine does not hardcode HUD wording. Progress changes
invalidate the existing surface projection, so a readiness label does not poll
the simulation. Preparation updates status content without revealing an
unpossessed scene surface. Visibility follows the authored mode throughout
loading: `possessed` requires local control and `always` requires an available
subject. This keeps unpossessed HUDs hidden on startup.
Use the optional typed `pause` fact (`condition`, `detail`) for a coupled
subject's retained stop condition. Keep the wording in Rhai and qualify the
paused HUD after its model clock has stopped; a model's transient failure output
is not the retained pause owner.
For recording, verify the required surface in an encoded trial with live data.
The readiness owner tracks whether its retained tree has consumed an exposure
snapshot; it must not wait for equality with a later global publication revision.
Camera, layout and render extraction remain required before capture admission.
Command and one-shot REPL timing is also generic presentation data. Read the
`application-cadence` exposure for command and REPL sequence/interval/rate
values; do not attach a HUD timer to `Time<Virtual>`, count API requests as
completed script evaluations, or read the command/REPL owners directly.
Producers must use change detection, revisions, or dirty flags. Continuous
values are coalesced to the current bounded presentation cadence (20 Hz).
`EngineExposures.revision` changes when a complete surface changes or retires;
it is not a frame counter. Do not use JSON to detect internal changes.
The `runtime.ui.surface` policy consumes one immutable fact snapshot through shared
bounded async admission in the same headless and windowed owner. Use
one Rhai entry returning `#{visible: bool, properties: map}`; the owner validates
and publishes both together. Do not split visibility/properties into separate
hook calls or pass the complete rich fact map to by-value formatting helpers.
Participant output samples retain their slot order and immutable names across admission.
The worker builds both the complete and authored public output maps from the same samples.
Camera surfaces use the same decision with their captured Presentation context.
Use
`ReadExposures` to wait for `state == "ready"` before asserting their properties.
A new identity starts hidden and `pending`; `failed` exposes an owner error
without partial properties and requires source/identity replacement to recover.
Ready telemetry samples remain available while the next sample prepares. Never
feed UI completion timing into simulation decisions or send live World/USD
readers to the worker. See the
[publication contract](../../docs/architecture/runtime-authored-ui.md).
Run the held-physics preparation and negative-result gate with the built
production binary in both host modes:
```sh
python3 scripts/api/test_runtime_ui_preparation.py --port 4374 --log target/ui-preparation-headless.log
python3 scripts/api/test_runtime_ui_preparation.py --port 4375 --windowed --log target/ui-preparation-windowed.log
python3 scripts/api/test_runtime_policy_transaction.py --port 4376 --log target/ui-policy-transaction.log
```
For the startup visibility rule, run the six authored policy checks in a
production scene-test session. The `lander_controls` gate also checks the
composed lander HUD is hidden before local possession and visible afterward:
```bash
SCENE_API_PORT_BASE=<free-port> ./scripts/run_scene_tests.sh --no-build --exact lander_controls -j 1
```
`SetRhaiPolicy` creates a complete source policy through one compound document
intent. Use that producer or `ApplyUsdOps` for file-backed policy changes; do
not enqueue its scope, source, entry and execution fields as parallel edits.
File-backed `LunCoPolicy` uses the registered asset-typed `info:sourceAsset`;
remove its inline `info:sourceCode` opinion so the file is authoritative.
Resolve source assets within their admitted Twin/source scope and verify the
actual installed hook and ready consumer, in addition to saved USD readback.
The runtime reads `UsdReadObject::asset_identifier` through the shared prepared/
live policy reader, preserving the contributing layer's anchor for referenced
policies. Raw authored asset text is not a file-I/O identifier; source-identifier
errors must reject installation visibly rather than guessing the scene root.
When one producer owns several surfaces, keep invalidation domains separate so
continuous motion does not rebuild static authored topology. Use the existing
authoritative stage revision for USD-derived membership and cache that
membership plus static authored metadata such as program source facts and
declared public-output names. Do not reread those facts at publication cadence,
rescan all prims, or add a second revision/source registry. Keep simulation
status, telemetry, outputs, and Rhai policy results live.
Authored runtime-surface fields belong on a prim with `LunCoUiSchemaAPI`.
Their live edits refresh exposure discovery through the stage revision; they do
not require recreating scene entities or resetting simulation state.
For camera status, Rust publishes the current camera fact and compact label
through the generic exposure namespace. The shared
`lunco-usd-bevy::camera_switch::camera_display_labels` resolver is also used by
the picker, Camera menu, USD/entity trees, and Inspector: unique leaves stand
alone, duplicate leaves gain nearest-owner context and then ancestors,
generated hexadecimal/UUID-like owner suffixes are hidden, and an unavoidable
normalized collision gets an ordinal. The full USD path remains the typed
selection value and hover/diagnostic text. Rhai owns selection policy
(`set_camera(name)`) and can read the fact with `get_exposure(...)`; HUI/CSS
owns rendering. Camera status emits `CameraSelectionStatusChanged` after its
camera/viewport lifecycle projection changes, and the exposure observer
consumes that event. The UI is revision-gated. Do not add a Rhai `on_tick`
loop, a timer poll, or a per-frame camera scan for this HUD.
Rejected camera commands may use the shared warning toast. Camera admission
findings come from one camera-contract state and project to structured runtime
diagnostics and Recent Events. A valid operator camera keeps the viewport ready;
unresolved director tracks are warnings until director control resumes. Recent
Events presents camera findings as warnings, emitted directly as telemetry
rather than runtime errors, so the generic warning observer never dispatches a
toast. Keep camera messages out of the Camera menu.
Register open egui dropdown bounds with `ScenePickGate` so option clicks do not
fall through to the 3D scene.
### 2. Add the template and stylesheet
Place application files under `assets/ui/`, or Twin files under its own `ui/`.
The stable contract is:
- HUI `<template>`, `<property>`, `<node>`, `<text>`, and `<button>`;
- stable `id` values and `{property}` interpolation;
- `on_press="callback_name"` for semantic actions;
- Flair CSS-like layout and visual properties, custom properties, and
`var(...)`.
Declare every property that the bridge should write:
```html
<template>
<property name="title">Status</property>
<property name="state">offline</property>
<node id="status-root">
<text id="status-title">{title}</text>
<text id="status-state">{state}</text>
</node>
</template>
```
Only bindings with `"css": true` also project `--ui-<property-name>` into CSS.
For collection rows, explicitly list presentation fields in the collection's
`css` array. Each row publishes its own `--ui-<field-name>` custom properties.
Use these in Flair for dynamic layout, including collapsed details and hidden
actions; HUI inline styles do not own rendered layout.
Use that flag for authored CSS values, never labels, descriptions, or error
messages. An omitted bindings map projects text only. Keep
the manifest-owned outer rectangle separate from CSS-owned internal layout:
```css
@import "ui/runtime_fonts.css";
#status-root {
display: flex;
flex-direction: column;
gap: 6px;
padding: 12px;
background-color: var(--panel-background);
}
#status-state {
color: var(--ui-state-color);
}
```
Use the bundled font import for telemetry/status glyphs. Do not rely on Bevy's
minimal `default_font` or a host-installed fallback.
### 3. Register bindings, gates, actions, and placement
Add a surface entry to the application manifest or a Twin-owned JSON document
with `kind: "lunco.runtime-ui-manifest.v1"`. Normal Twin loading discovers it
through the shared JSON asset lifecycle. Use the default `workspace` owner
for scene and Twin controls. A Twin can add or replace shared workspace
surfaces by ID. Set `"owner": "application"` in the application manifest for
a surface that stays available across Twin changes. Its ID and namespace are
reserved, and its actions carry no Twin target. Set `"overlay": true` when
either kind of surface needs to draw above dock panels.
[Ownership and publisher requirements](../../docs/architecture/runtime-authored-ui.md#application-and-workspace-surface-ownership)
Paths resolve from the manifest's source root. Use explicit `lunco://`
references for shared imports. Exercise application controls before a Twin opens
and after changing or closing it. Verify workspace controls through direct
`OpenTwin`, same-Twin reopen, and replacement with another Twin. Use the rendered
controls to check retirement and callback routing.
Example surface entry:
```json
{
"id": "mission-status",
"template": "ui/status.html",
"stylesheet": "ui/status.css",
"namespace": "mission-status",
"bindings": {
"title": { "source": "title" },
"state": { "source": "state" }
},
"actions": [
{ "callback": "runtime_status_focus_moon", "action": "view.body.moon" }
],
"visible_in_perspective": "sandbox_view",
"interactive": true,
"placement": {
"mode": "window",
"anchor": "top_right",
"offset": [-16.0, 16.0],
"width": 260.0,
"height": 84.0
}
}
```
Surface `id` values and callback names must be unique within the manifest. The
loader rejects unknown fields, unsafe asset paths, and invalid geometry.
Authored semantic actions are accepted and delivered to Rhai; do not add a Rust
enum arm for each Twin, route, rover, or lander.
Binding target names must be declared template properties. `map` translates
exact rendered strings, which is useful for `true`/`false`, body ids, `display`,
or CSS colors. It does not perform arithmetic or general expressions; publish a
formatted presentation value when that is what the surface needs.
Placement modes:
- `viewport` fills the window;
- `dock_panel` uses the workbench's authoritative `PanelRects` plus an inset;
- `window` uses logical-point width/height, a corner/center anchor, and an offset.
Only a `window` surface may set `draggable: true`. The primary-button drag
stores a finite logical top-left override by stable surface id, clamps it to
the live target after resize/DPI changes, and persists it in the active Twin's
existing workbench workspace state. A primary-button double click removes the
override and restores the authored anchor. The shipped `celestial-view`
switcher is a draggable window with a top-centre authored default; Settings ▸
HUD also exposes a surface-specific reset that removes its per-Twin override.
Manifest reconciliation prunes unknown surface ids, and `TwinClosed` clears the
in-memory layout scope.
Native camera-feed windows and telemetry graph HUDs also persist their
selection and logical-point size/position in the Twin's
`.lunco/workspace.json`. Snapshots are kept per scene path and restored after
the matching scene mounts; camera restore waits for its source projection,
switching scenes retains each one's layout, capture waits for scene transitions
to commit, and graph views wait for their scalar sources to publish. **Settings →
Project → Save and restore View layout** defaults on and stores the project override as
`ui.restore_view_state` in `.lunco/settings.json`. **Reset saved View layout**
restores the authored View dock and clears camera, graph, and draggable-surface
placements. Keep capture and restore in the UI view owners, with the
workspace-state adapter carrying typed snapshot records across process runs.
Script-driven hint/objective/action cards belong to `lunco-workbench-guided-ui`.
Omitting `hud` uses the calling script's card; unscripted API/REPL input uses
a distinct command-context card. Several scenario/tool producers
share a scene card by supplying the same explicit `hud` id, for example
`hint("mission-controls", text)` and
`guided_hud_actions("mission-controls", tool, hook, actions)`. The Twin is part
of the identity; never choose a card by last writer, hook name, or label.
`GuidedHudVisibility` supplies the host default (View in LunCoSim).
`hud_perspectives(ids)` or `hud_perspectives(hud, ids)` declares a per-card
allowlist; `[]` explicitly allows all. Unknown ids reject atomically. Scope
covers the whole card before rendering or input creation. Switching perspective
preserves content. Coach, spotlight, and recovery presentation remains separate.
`SetGuidedHudActions` validates the endpoint and action ids, creates an explicit
`ToolHookBinding` entity, and retires the prior binding. The UI carries that
entity into `RunRhaiToolHook.binding`; the shared scripting queue validates its
exact endpoint, registered owner, Twin, and scene generation at admission and
again at execution. The immutable action row's widget identity includes its
binding entity, so replacement also retires in-progress input. Empty actions
retire the binding. Script removal immediately clears its card,
including while the driver is paused or preparing. Script-instance retirement
(including recompilation) clears implicit script cards; scene replacement clears
all cards; `TwinClosed` clears that Twin's cards. All three despawn their leases.
Stop hooks may clear existing content/actions idempotently; clears never create
cards. New content, perspective declarations, and bindings reject during stop.
HUI, dropdown, Escape, and native menu actions capture `RuntimeUiActionScope`
at emission; validate the exact owner and source lease again when executing.
Scene-authored actions additionally retain their lifecycle generation. Never resolve the next active Twin for an
old event. Named cards are scene-owned, so callback tools can update them independently of
a scenario host. `ClearGuidedOverlay` clears the calling script's card and the
active coach/spotlight presentation, preserving other cards. Inspect the admitted
scope, content, and visibility through `InspectGuidedHud`. Its optional `tour`
report exposes the active coach's exact Twin/script owner, step and anchor.
Script-opened scene menus retain the same captured scope while open and clear
on scene transition or owning Twin close; stop hooks cannot open menus. Each
popup has its own widget identity and child callback leases. Replacement or
dismissal retires unselected leases; selection transfers one `Invocation`
binding to the queue, which releases it on execution or rejection. HUD rows
use `Surface` retention. Scene transitions retire scene-bound queued work even
while the interpreter is preparing; owner-bound application tools stay available. Never leave a selected popup endpoint unowned.
Run `python3 scripts/api/test_guided_ui_callbacks.py --port PORT` for the
production popup/menu input, replacement, dismissal, reset, and Twin-replacement
gate. Installed workbench menus retain typed action descriptions beneath a
fresh installation root, independently of tool registration and scene
readiness. Rows stay disabled until the current tool endpoint is registered;
the visible popup refreshes readiness as registration changes, and selection
resolves the endpoint again. Twin-owned menu trees and quick-open entries are
visible only for their exact active Twin. Selection validates the provider and
Twin, then creates an owner-bound invocation child. Menus remain available
during scene reset; provider or Twin replacement revokes old input and selected
work. Every terminal admission/queue path releases the exact invocation lease,
including overload with an omitted request owner.
Nested deferred calls retain their typed caller context and capabilities through
`CommandOrigin::Rhai`/`WorldScriptExecution`, including `target_twin_id` independently
of the execution route. Never rebuild a stopping caller as
UI/REPL evaluation. The gate stops `guided_hud_teardown.rhai`, then inspects the
completed authored verdict from both deferred queues. The wrapper uses
temporary application-source fixtures for the native asset watcher and removes
them after its owned runtime exits.
Run `assets/scripting/tests/test_guided_hud.rhai` with
`scripts/api/run_rhai_test.sh PORT FILE` in an owned windowed production session.
It checks View/Build/Editor, independent teaching scope, preservation, and invalid
scope/endpoint rejection. Capture screenshots to verify actual placement/input;
headless presentation acknowledgements do not prove visibility.
`assets/scenarios/tests/guided_hud_teardown.rhai` reports `HUD_TEARDOWN` after
its host is stopped; it also publishes a script-owned teaching card with an
explicit all-perspectives scope. Register the generic `hud_binding_probe.rhai` test library
only in an isolated test Twin when exercising real pointer callbacks and Twin
replacement; never persist test tools into a user's Twin.
Press activation uses one exact-entity admission owner for pointer, keyboard,
Controls menu and native assistive actions. Reparenting outside a live interactive
surface or removing callbacks retires accessibility/menu/tab membership. Labels
track current hierarchy/text/tags, and `tag:ui_tab_index` survives disable/enable.
Use the generic callback-lease test and the Linux native accessibility driver
when changing this boundary. For focus presentation, also run a windowless
recording to check the host with no primary egui context.
`interactive: true` enables input ownership for visible HUI controls that carry
an authored `on_press` action. The runtime adds `Pickable` to those visible
controls and feeds each computed Bevy UI rectangle into the existing
`ScenePickGate`; it never registers the surface root or a full-window
`viewport` rectangle. The active presentation camera is enabled for UI picking
with Bevy's marker filter, so decorative retained nodes without `Pickable` pass
scene hits through. Visible HUI nodes in a `draggable` window surface,
including its root, receive pick markers so pointer drags can bubble to that
surface's owner. This keeps HUDs transparent to camera dragging and scene clicks
outside their explicit controls. Do not add a parallel pointer/interception
system. Do not add per-frame position correction; placement is applied after
HUI/Flair style work with change detection, and the startup resolver ignores a
zero-sized target in favor of the live primary window
dimensions.
### 4. Map actions through the existing command path
The HTML callback name is only an authored binding. The manifest maps it to a
semantic action string; the runtime emits a typed action event; the owning
Rhai program maps that action to a typed command/event. A template must not
mutate resources or call a domain API directly.
The generic dropdown mechanic owns only popup lifecycle, typed record
projection, scrolling, and authored dimensions. It does not parse action
prefixes or construct options. HUI 0.7 has no native select/accessibility
tree, so this shared egui primitive is the low-level option. Camera, program,
route, and future domain policies remain authored in Rhai.
If a new domain action is needed, author its semantic identifier and handle it
in the owning Rhai program through the existing typed command/query/event
surface. Do not add a legacy callback alias or a widget-specific Rust shim
merely to make one template work.
For the shared lunar view surface, publish the scene `SiteAnchor` position as a
typed f64 vector in the Moon inertial frame. Show a separate mission-site HUI
card when that site and the Moon orbital pin are available; it must not depend
on a possessed vessel or appear inside the body mode selector. Rhai computes a
target direction, reads the persisted camera animation-duration setting, then
sends a generic `AnimateOrbitCameraDirection` request. The camera owner
animates along the existing orbit while preserving its current radius and
vertical offset.
## Reload loop
On native desktop, keep one production `luncosim` process running and edit assets:
| Edit | Live effect |
|---|---|
| `assets/ui/*.html` | HUI rebuilds the affected retained surface tree. |
| `assets/ui/*.css` / imports | Flair reapplies the stylesheet. |
| `assets/ui/runtime_surfaces.json` | Surface roots and action registrations are rebuilt. |
| Rust producer/observer | Rebuild the production binary; replace the session through API `Exit`. |
`ReloadShader` reloads WESL. Bare engine paths resolve to `lunco://`; explicit
source paths remain exact. An empty path queues every loaded WESL asset, and an
inactive target fails visibly. Reload cancels a pending source edit for that
asset. `SetShaderSource` validates syntax and queues dependency preparation
through Bevy’s registered readers. Only the latest edit for the captured Twin
mount can publish; GPU validation follows in the renderer. `RunScenario`
hot-reloads Rhai. HTML/CSS use their asset owners. The native file watcher is
absent from the headless server; web builds use bundled static assets and
browser cache rules.
HUI caveats: one root per template component, no recursive imports, and a
nested component template reload may require reloading the top-level template
again. Never manually write Bevy styling components under the surface from Rust;
HUI/Flair owns those components.
The runtime style handoff must follow HUI Build and all exposure/collection
compilation, and precede HUI Style in Update. It caches/removes runtime
`HtmlStyle` before inline defaults can overwrite retained CSS layout; selector
names are attached at the same boundary. Flair's Prepare set runs in PostUpdate,
so an Update edge to that set cannot enforce this handoff. Preserve unrelated
HUI templates' styles. Use the focused
`hui_rebuild_preserves_retained_runtime_styles_only` test, then inspect native
template/stylesheet reload and scene-restart screenshots.
Use a single `<node>` as the root of every template, including collection-row
templates. Keep `<button>` and `<text>` elements below that root because HUI
reuses the scope entity during hot reload and Flair retains its selector type
metadata there.
Lifecycle invariant: when an exposure or presentation gate turns off, the
bridge removes the retained root whenever any HUI state remains, even if its
local mounted marker is stale after a deferred rebuild. A hidden surface must
not leave a stale progress card in the render tree.
## Verification
For a markup/style-only change:
1. Start the already-built production binary with an explicit free API port.
2. Wait for `/api/ready` to report `ready:true`, `world_hold:false`, and
`pending_count:0` when scene readiness is relevant.
3. Edit the asset and observe the live window; do not rebuild or relaunch just
for HTML/CSS.
4. Query the capability side with `ReadExposures` and capture a screenshot with
`CaptureScreenshot` when the visual result matters.
5. Check logs for HUI/Flair parse or asset errors.
For a Rust change, build the production binary in this worktree and set
`LUNCOSIM_BIN` to it. Each agent owns a distinct free API port and launches from
the same checkout and working directory as its terminal. Before replacing your
own session, send API `Exit` and verify its process and port are gone. Do not
control another agent's session or use `pkill`.
Useful diagnosis order:
- missing surface → namespace, exposure visibility, perspective, gate,
placement, asset paths;
- blank value → declared `<property>`, exact binding source, exact `map` key;
- dead button → callback spelling, manifest action, host observer;
- tofu → explicit bundled font import and asset path;
- startup jump → manifest placement and change-detected post-style boundary;
- slow frame → exposure revision/cadence, tree size, egui, physics, and GPU
measurements separately. Do not infer that HTML is the bottleneck from FPS
alone.
For the dataset consent surface, trace `DatasetScope::id()` through
`ListDatasets`, the row/action scope, and `assets::request_required`.
Use `engine` or `twin:<source_identity>`; never pass a display label as the
selector. UUID-backed Twins use `uuid-<simple-uuid>` as their source identity.
UI admission validates source/owner lifetime, independently of loading status.
Application-owned exposure namespaces retain owner-scoped callbacks; scene
namespaces pin the live scene lifecycle. Simulation admission stays in the
shared progress gate. Use `"overlay": true` for a notice that must remain
above dock panels. Its pickable HUI card reserves the measured rectangle in
`ScenePickGate`, including while scene loading is held. The overlay layer
and the surface owner's lifetime are independent.
Validate Details, Download, Cancel, dismissal and application/Twin UI tools
while data admission is held. With
`scripts/api/test_scene_asset_requirements.py --exercise-controls`, use the
captured control screenshots to enter logical coordinates. Pass the resulting
`clicks.json` with `--clicks` to replay the same layout. Command-only tests
do not prove button input.
Retain retry/cancel actions. Dismissal means background work, and completion remains
visible until dismissed. Use the owning terrain map and camera-cover states
for visual preparation after disk installation. Run `test_download_policies.rhai` and the windowed
`dataset_provisioning_surface.rhai` gate against a declared missing scope,
including invalid-scope/request rejection. Check Recent Events for discrete
dataset lifecycle transitions and verify Twin replacement retires the scope.
## Current non-goals
Do not assume support for browser DOM APIs, JavaScript, forms, text editing,
virtualised lists, full accessibility, arbitrary web CSS, `!important`, global
stylesheets, font fallback chains, or reliable mixed-unit `calc()`. Add a
deliberate engine/runtime contract and tests before expanding the surface
language.
For docked engineering task layouts, use the workbench perspective hooks rather
than a retained HUD as a second docking system. [Twin perspectives](../../docs/tutorials/05-twin-perspectives.md)
shows Rhai assembly from registered panels; retained surfaces may still choose
visibility through their existing perspective ids.
Subject surface facts include `coordinates` from `SurfacePoseQuery`: IAU/WGCCRE
body-fixed latitude (north positive), longitude (east positive), and height above
the body's mean sphere, all f64. Compact and detailed vessel HUDs share the
coordinate-formatting policy, including degrees, hemispheres and height datum.
Bind frame labels and numeric height from that policy; do not overwrite an
unavailable height with a world-Y value. Do not label these coordinates
`MOON_ME` or `MOON_PA`: those require an explicit frame transform. In a scene
without a site anchor the coordinate mode is explicitly world metres; an
unresolvable or ambiguous site frame publishes coordinates as unavailable.
The shared `asset-consent` view separates source verification and artifact
preparation. Its `assets.provision` Rhai policy returns row `download_status`,
`preparation_status`, `detail` and `source_url` fields in addition to semantic
actions. Rust publishes the typed worker snapshots; templates never read files.
`runtime_ui::on_action` routes `process` through the existing asset tool and
`open_web_url` through the shell's validated `OpenWebUrl` browser adapter.
Verify missing, downloaded/unprepared, failed and ready views with the production
pipeline driver and inspect its actual captures before choosing click positions.
Settings ▸ Data & libraries uses the same row policy with grouped, searchable
entries. Verify Rebuild forces stage execution and Reload scene follows the
shared readiness lifecycle. The dialog shows simulation holds/faults separately
from artifact readiness; dismissing it must preserve a manual transport pause.
The asset preparation surface receives `required_for_scene` separately from
`recommended`. Only composed scene dependencies trigger its mandatory readiness
flow. Queued operations offer cancellation; per-file progress names its source.
Dismissing the window keeps missing scene data held and never starts transport.
Desktop startup work has its own `startup-assets` namespace and compact
authored overlay, available on the empty welcome screen. Change the selection
and engine-scope rule in `assets/scripting/policy/startup_assets.rhai`. The
`startup` fact of the
application `assets.provision` policy projects the selected dataset states
and scopes dismissal to the startup card. Open a Twin during a cold startup
and check that its required-data controls take the foreground while both sets
of transfers share the configured queue. Close that notice and check that the
startup card returns with current progress. Verify a cold cache, failure and
retry, dismissal during work, and a cached relaunch in the production desktop
app. See the [startup asset contract](../../docs/architecture/asset-processing.md#desktop-startup-assets).
For scrollable collections, add a sibling authored track and set the collection's
`scrollbar` to its node id. The runtime binds native Bevy ScrollArea/Scrollbar;
verify visible thumb movement with wheel and pointer dragging in the real app,
including a small viewport. Keep actions/status outside the scrolling list, use
compact completed rows, and let Rhai order outstanding work before ready rows.