LunCoSim UI architecture and panel implementation patterns. Use this skill whenever working on any user interface for the LunCoSim solar system simulation — adding panels, building dashboards, creating inspectors, spawning UI, telemetry displays, docking layouts, themes, or anything involving egui, lunco-workbench, or Panel. Also use when the user mentions typed commands, WidgetSystem, or 3D world-space UI. Even if the request seems simple (like "add a button"), use this skill because the pan...
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 Lunco Ui?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/luncosim-lunco-ui)
---
name: lunco-ui
description: >
LunCoSim UI architecture and panel implementation patterns.
Use this skill whenever working on any user interface for the LunCoSim
solar system simulation — adding panels, building dashboards, creating
inspectors, spawning UI, telemetry displays, docking layouts, themes,
or anything involving egui, lunco-workbench, or Panel.
Also use when the user mentions typed commands, WidgetSystem, or 3D
world-space UI. Even if the request seems simple (like "add a button"),
use this skill because the panel registration and command patterns
are project-specific and not obvious from Bevy alone.
---
# LunCoSim UI Architecture
## MANDATORY: Read Architecture First
Before implementing ANY UI, read:
```
crates/lunco-ui/ARCHITECTURE.md
```
It explains the full architecture, step-by-step panel integration guide,
and design decisions. This skill is a quick-reference summary.
Windows **Settings → Debug → Show console on next start** dispatches
`SetDebugConsoleStartup`; `lunco-luncosim-ui::debug_console` owns the persisted
preference and pre-app console setup. Changes apply on restart. Use the
[native startup acceptance check](../../scripts/api/test_windows_console.py)
and the [console guide](../../docs/apps/luncosim/README.md#windows-debug-console)
when changing this menu or process boundary.
**Settings → General** holds the global scene-loading preference; **Settings →
Project** edits the local override, and Twin settings owns the shared
override. Show the inherited value and report higher-priority overrides when
present. Route project and Twin edits through typed commands. Verify the menu
and panels with native input and `GetSceneLoadingSettings` in an owned session.
The Scenarios menu always starts with **Restart Scenario**, disabled when no
live scene is loaded. Each Twin submenu offers **Load Default Scene**, regular
scenes, and a separate **Test Scenes** submenu. The empty-viewport welcome card
is shown only while no live scene is mounted; a Twin with no live scene offers
its configured default and every regular indexed scene in a scrollable list.
Test scenes remain available from the Twin's Scenarios submenu and never appear
in that card. With no Twin active, the welcome card shows the Crater Cup example
mission and Open Twin; tutorials remain in Scenarios and quick navigation.
Use `SceneMountState` so an Editor preview cannot hide the empty live state.
Verify its buttons with
`scripts/api/test_scene_loading_ui.py --port <free-port>`.
## Graph readability
Analyze places the live viewport in the center and Graphs in the bottom dock,
with Signals and Ports alongside. Lunica keeps the model workspace central;
the Modelica view's **Graphs** toolbar button opens the canonical plot in a
resizable bottom dock on demand, and **View → Lunica → Graphs** provides the
same entry point. The plot's Variables and Runs pickers select result curves;
live channels can also be chosen in Signals. Empty plots explain how to add
data, and mixed-unit plots explain that they share one vertical axis. Author
default placement through `assets/scripting/policy/workbench_perspectives.rhai`;
increment the perspective revision when changing default placement so saved
layouts adopt it. Hosts without a live viewport use a central graph. Verify
placement and graph reopening with
`scripts/api/test_workbench_perspectives.py --port <free-port>` and inspect its
Lunica and Analyze screenshots. The no-model workspace and Welcome surfaces
share equally sized primary actions, centered as a pair and stacked in narrow
panels.
For a viewport demonstration, enable **Settings → HUD → Telemetry graphs**.
Use the card's **Parameters** picker to browse source/component groups or
filter names and descriptions, then choose up to four parameters. The selected
parameters stay pinned above the groups. Units and Y scales
stay independent; time axes stay aligned. The browser's **Show in HUD** starts
with its selected channel. The title-bar history dropdown selects the retained time window;
**Style** exposes layout and native per-plot appearance controls. Use **+** for
another independent HUD; drag an edge or corner to resize, and use **×** to close it.
Settings → HUD visibility toggles retain parameters while hidden. The picker stays
open while browsing and selecting; **Done** or an outside click dismisses it. Each instance has
its own position, dimensions, visibility and parameters. No document
or dock tab opens. A Twin calls `SetGraphHud { signals, visible: true }`, where
signals contain explicit `target_gid`, `signal` and `caption` entries. Inspect
with `InspectGraphHud` (the `huds` collection); style its native plot ids with
`ConfigureLinePlot`. Omitting `hud` addresses the primary HUD. Allocate others
with `CreateGraphHud` and close them with `RemoveGraphHud`.
Selections validate atomically, retained channels preserve their styles, and
scene teardown releases the HUD-owned grid and plots. Verify parameter choice,
units, hide/show, invalid batches, instance isolation, native drag resizing,
unchanged history and scene retirement with
`scripts/api/test_graph_hud.py`, plus native-click and screenshot review.
Telemetry browser rows reserve the measured value and unit at the right edge
before allocating the channel name and hierarchy indentation. Bound each row
with an explicit visible rectangle and the theme's window padding at the right
edge, including in justified parents. Truncate names and bound indentation on
narrow panels; keep numeric cells on one line.
For small multiples, use `ConfigureSignalGrid` with an explicit source, signal
and caption for every cell. Discover active scalar channels through
`ListTelemetryChannels`; inspect allocated plot ids with `InspectSignalGrid`.
Style them through `ConfigureLinePlot`, then reveal registered instance kind
`signal_grid` in a dock or floating host. The shared grid supports up to 64
channels and reuses native plots, rather than adding an alternate renderer or
duplicating telemetry. A few cells support explanation; dense views show scope.
An admitted channel can be plotted before its first sample; its native plot
shows the waiting-for-telemetry state. Restored graphs retry unresolved signal
selections on descriptor changes rather than scanning them every frame, and
retired or invalid sources are logged and left closed.
Time-series grids share their native X viewport and cursor by default. A
late-starting sensor or an idle channel therefore stays aligned with the other
measurements. Y scales and units remain independent; phase-space X bindings
are not linked. `ConfigureSignalGrid.sync_time_axes:false` opts out.
`InspectSignalGrid` reports the selected mode and common native time interval.
For captured charts, `show_hover_values:false` hides hover readouts and
crosshairs without hiding axes or changing the recorded samples.
Give simultaneous quantities distinct, consistent colours. Set
`ConfigureLinePlot.series_color:[r,g,b]` for a single-quantity live or historical
plot. For multiple live bindings on one plot, use `ConfigurePlotBinding` with
the existing `plot`, `signal`, `label` and `color:[r,g,b]`. An empty colour array
restores automatic colours; omitted fields preserve the existing presentation.
These settings change presentation only, never the measured source or units.
`SetTelemetryBrowserView` can pin `target_gid` independently of editor selection,
select and reveal a `signal`, and set `show_internal` or `show_preview`. Hide the
inline preview when the main Graphs panel already shows that channel. An empty
signal leaves list navigation to the operator. A missing pinned owner is
reported visibly. The browser's Display menu controls its inline preview height
without changing stored history or global UI scale.
Use the native line plot toolbar's `Line` control to set curve thickness from
0.5 to 8 logical pixels. It is saved per visualization in `LinePlotStyle` and
uses the existing typed edit observer. Keep global UI zoom at the operator's
preferred scale; curve width does not change typography or signal samples.
Verify the saved width and rendered stroke in the actual plot panel.
## Camera windows and image controls
The main Camera picker includes mounted sensor cameras, grouped by controlled
USD owner with path-aware search. Use **Image controls…** for the selected main
camera. Start the first independent camera view from **Settings → HUD → + Add
camera view**; the menu shows the active count out of eight and disables the
action at the limit. Each camera window keeps source, resolution and **Style**
controls on one toolbar line, with the graph HUD frame and `+`/`×` buttons.
Its image controls affect only that feed. Fixed color exposure (EV100), depth
range, noise, seed, animation, quantization and shader asset are live typed settings.
The main camera's fixed EV100 takes precedence over **Settings → General →
Fixed viewport exposure**.
See [camera image controls](../../docs/architecture/render-decoupling.md#camera-image-controls)
for owners, shader bindings, physical scope and completion events. Verify both
actual rendered depth/noise and negative `SetCameraImageEffects` admissions;
a successful allocation is not pixel evidence. UI draft/search state belongs
to the scene resource. Camera and graph windows restore their per-scene source,
selection, size and position from the active Twin's `.lunco/workspace.json`.
Settings → Project controls **Save and restore View layout** and **Reset saved View layout**.
Camera selection/viewing never toggles physical power.
The performance status bar consumes the execution owner's
`engine-health.modelica_worker_ms_per_physics_step` and displays milliseconds per
physics step. Keep completion throughput out of the cost readout. The metric
sums measured worker service over the shared one-second window and normalizes by
completed physics ticks; parallel contributions overlap. Exact sample counts,
wall duration, and per-instance service stay available through the same exposure.
Paused physics and cleared scenes have no per-step sample.
The HUD measures the complete metric line at the active UI font size. It reserves
that width in the status bar, or uses compact text and scales it to remain on
one row when the window is narrow; it does not truncate physics or Modelica timing.
## Core Principles
### Shared text entry
Build application text fields with
`lunco_workbench_widgets::text_editor::{singleline, multiline, code}` and
customize the returned builder for domain-specific hints, widths, fonts, or
commit behavior. Do not instantiate `egui::TextEdit` directly in panel code.
Single-line fields keep egui's caret-follow horizontal scrolling; place
multiline editors and long result lists in a bounded `ScrollArea` owned by the
panel layout.
Render recovery warnings and terminal presentation failures belong in Recent
Events through the existing StatusBus and RuntimeDiagnostics owners. Keep them
out of floating viewport banners; presentation-stop decisions stay at the
render recovery owner.
The required `application.scenarios.menu` Rhai policy owns the full Scenarios
tree, including scene grouping and dividers, current-scene radio selection,
restart, downloaded Twins, and the test-content checkbox. It orders Twin
content before Tutorials and keeps Tutorials and Library together. Its typed facts come from the
admitted scene inventory, committed `CurrentScenePath`, workspace Twin
identities, download registry, and persisted `AssetVisibilitySettings`; the
policy is reevaluated when those inputs change. The preference hides or shows
Library tests. The checkbox is under **Settings → Sim Core**. Twin tests remain
in each Twin's **Test Scenes** submenu. Rhai changes the persisted preference through the typed
`SetShowTestAssets` command. Keep scene labels, grouping, and menu/tool
arguments in policy; do not add a native Scenarios menu or a parallel scene
selection path.
The application asset-lifecycle policy contributes authored tutorial catalogs
to the same top-level menu through provider merging; tutorial labels and
catalog rules also stay in Rhai.
The generic `ScriptUiRequest::WorkbenchMenus` host renders policy-contributed
trees, divider rows, policy-ordered same-label contributions, replaceable Settings submenus, and viewport actions. It supplies radio/checkbox controls,
provider/Twin lifetime validation, and tool-hook routing; it does not choose
which scenes or groups to show. Rhai supplies the same admitted scene list to
quick-open. `lunco-assets-runtime` owns inventory discovery, not menu policy.
Twin-owned provider trees and quick-open actions are shown only for the active
workspace Twin; application-owned contributions remain available when the
active Twin changes.
For retained runtime UI capture, `runtime.ui.recording` receives only surfaces
allowed by their exposure, perspective, gate and active Twin setting. Switching
perspectives refreshes this selection without requiring an exposure change.
Required surfaces still wait for mounting, layout and render acknowledgement;
do not select candidates by whether their render root is already mounted.
1. **UI lives in `src/ui/`** — domain crates have `src/ui/mod.rs` exporting a `*UiPlugin`. UI code never lives outside `ui/` directories.
2. **UI never mutates state** — all interactions emit typed command events (the `#[Command]` structs, triggered via `ctx.trigger(...)`) that observers handle. This makes the UI AI-native: AI observes the same command stream as humans and can emit identical commands.
3. **Panels are `Panel` impls** (the contract lives in `lunco_workbench_core`) — registered via `lunco_workbench_core::WorkbenchPanelAppExt::register_panel()`. The concrete shell drains that registration into its docking system.
4. **Headless must work** — removing UI plugins (Layers 3 and 4) leaves a functioning simulation. See `AGENTS.md` §4.1 for the four-layer architecture.
5. **Typography roles are shared.** `ThemePlugin` maps egui's built-in styles and `TypographyRole` styles from `Theme.typography` across egui surfaces in `ThemeApplySet`. Render systems outside the workbench should run after that set. Let ordinary widgets use the mapped Body, Button, Heading, Small, and Monospace styles. Use `TypographyRole::text_style()` for `RichText` and `TypographyRole::font_id(ui.style())` for custom painter text. Guidance and status messages use Body; Caption is for secondary metadata and compact status-bar summaries. Dense data roles are for chart labels, timestamps, and similarly compact values. Authored model text and world-space labels retain their content/spatial owner.
The workbench is deliberately split into contracts, reusable presentation,
optional guided presentation, and the concrete shell. `lunco-workbench-core` contains
the stable `Panel`/`PanelCtx`, `InstancePanel`, `PerspectiveLayoutPlan`, menu
registry, `WorkbenchSnapshot`, scheduling labels, and perspective command
payloads. It is safe for domain UI crates that need panel behavior or published
layout facts and does not pull the renderer or `egui_dock`. `lunco-workbench-guided-ui`
owns optional Rhai-driven HUDs, spotlights, coach-mark tours, and guided-recovery
surfaces; hosts add it explicitly after the shell. `GuidedHudVisibility` supplies
the default perspective for complete hint/objective/action cards. LunCoSim uses
View. Authored scripts declare overrides with `hud_perspectives(ids)`; an empty
list explicitly allows every perspective. Scope belongs to each card. Read
`runtime-ui` for card identity and callback teardown; coach marks and spotlights
keep their own anchor semantics. `lunco-workbench` is the
concrete shell: it owns
docking, egui/bevy integration, persistence, source editing, and shell-only
widgets such as icons and tree renderers. `lunco-workbench-widgets` owns the
shell-independent icon, text-editor, and tree helpers. Virtualized trees use
`tree::branch_header` for a fixed row stride; recursive trees use `tree::branch`
for an indented body, sharing the same disclosure state and controls.
`lunco-workbench-browser` is the
optional reusable Twin browser feature: it owns browser state, selected file/library/domain views,
and filesystem/library sections, including the asset-provisioning dependency.
Domain crates must not read the shell's private `WorkbenchLayout`; use
`WorkbenchSnapshot` for layout facts and typed workbench/browser actions for
navigation. Twin-root file rows queue source opens through `BrowserActions`;
the browser dispatches them after rendering with the captured Twin root and a
`LocalUser` origin, while domain documents stay with their owning dispatchers.
Sections with an already resolved path can dispatch a typed command through
`BrowserCtx::trigger_command` with its explicit origin. Scene Files keeps its
large USD-layer group compact and expands groups that contain active search
results.
Universal runtime inspections should read an authoritative view model produced
outside egui. For ports, use `PortRegistry::entity_port_infos` so values,
units, ranges, source, authority, and writability come from backend owners;
sample at a bounded cadence when the data has no shared change marker. Writable
rows emit the existing typed command and validate against the metadata contract;
the panel must not infer policy from names or mutate port storage directly. If
the view caches metadata, its invalidation must use the owner-provided
`PortBackend::topology_key` and the durable owner-published
`PortTopologyRevision`. Providers publish it from component lifecycle
observers and change-filtered structural identity checks; Avian groups declare
their identity key and invalidation hook beside their membership predicate. Do
not use a broad scene revision or entity-count poll as a port-topology signal.
Large inspection surfaces must virtualize their fixed-height browser rows and
request live values only for expanded/visible bodies through the existing owner.
The USD Prim tree caches open rows and uses the
shared tree disclosure controls with preview-scoped identities; preserve
selection reveal, offscreen scrolling, and the typed display-mode commands.
The bundled-library browser consumes the asset manifest's revision, not a
per-frame hash of all paths. The normal sample path reads live values
through the registry rather than rerunning backend list/metadata callbacks.
Connections offers **Topology**, **Interface** and **Bindings** over the same
source graph. Select the scene/document with `SetConnectionSource`.
Use `SetConnectionWorkspace` for mode, local-wire disclosure and
live-value/highlight controls. Prefer the independent input/output lists and
the local-binding table when examining one model; their rows do not imply
input-to-output computation. Keep `local_bindings_as_rows` and exact
`icon_program` selection in the existing Rhai `diagram.layout` policy, with
typed validation at its owner. Render source-authored Modelica icons through
`lunco-modelica-icon-ui`; preserve USD handles and the full attached-program
list. Source icon facts come from the existing asynchronous Modelica asset
loader, including inheritance within the loaded source.
Manual wiring, disconnect and explicit source replacement use the existing
USD endpoint validator and journal lowering. Source Save/Undo/Redo are separate
from layout history; model editing opens the established Modelica editor at the
class selected by the USD program.
Binding-form submissions use typed `ApplyConnectionBinding`, with the current
`InspectConnectionDiagram.source_generation` and exact endpoint keys. An edit
names its original pair so source/target changes remove that pair atomically,
preserve unrelated fan-in and undo as one change. Stale generations and absent
originals reject; terminal completion comes from `ApplyUsdOps`.
Layout and disclosure refreshes preserve the draft's exact endpoints.
Live status joins the authored property pair to its projected wire, then
consumes the binding, hold, diagnostic and port owners at a bounded
cadence for visible consumers. Highlight observed changes only while the fixed
clock advances; a preview has document-only status and no live values.
Run `scripts/api/test_connection_workspace.py --port <free-port>` for native
wiring, preview isolation, icon, view, journal and runtime evidence; its verdicts
are in `assets/scripting/tests/test_connection_workspace.rhai`.
For USD topology, extend the existing Connections projector in
`crates/lunco-luncosim-edit-ui/src/ui/connection_canvas/`. Default to the active
`SceneMountState` mount; Editor document focus is an explicit alternate source.
Read composed USD, including prims without ECS projections, independently of
Modelica compilation. Cache facts and consume stage deltas, never traverse in
paint. Start at the loaded root with direct hierarchy children; use cached
USD ancestry for drill-in and explicit descendant expansion. Preserve full property identities; causal edges have
arrows, acausal/joint edges do not. Never fabricate missing interfaces.
Scene selection uses mount-scoped entity targets, documents use `SelectUsdPrim`.
Use `Edit connections` / `OpenUsdSourceDocument` to establish the document
boundary without replacing the scene. The USD document owner resolves the exact
registered source on a worker and reuses its file-preparation lifecycle.
USD browser clicks use this source-only command too. `OpenFile` can open a
different workspace/Twin and is not an additional-preview command. Verify
source isolation through `assets/scenarios/tests/usd_source_isolation.rhai`,
launched by `scripts/api/test_usd_source_isolation.py` with an exact scene,
source and composed selection path in an owned production session. Successful
and rejected sources preserve the
active Twin and physics topology, and physics continues while a preview opens.
Creating a USD Stage also publishes `UsdDocumentReady`, so an untitled
document opens in its own Editor preview even when the Twin has no live scene.
The preview does not select or mount the Twin's default scene. Verify creation,
editing, save and reopen with `scripts/api/test_scene_loading_settings.py`.
A folder without its own `twin.toml` is a temporary workspace: show no open
Twin, omit project settings, and offer only root-level USD files without
discovering child Twins. Show an empty message when none exist. The Editor still
opens standalone documents.
Scene clear and reload also retire `StatusBus` history, progress and handles
through its owner-installed scene resource registration. Check the recent-status
popup after clearing a compiling scene; old completion text must not remain.
One document may have several preview leases over the same stage. Structural
edits and subtree refreshes must update each lease through the shared USD
projector. Readiness requires the exact stage's consumed document generation
and completed visual work under that preview root; framing must also stay in
that hierarchy. The `usd_material_edit_projection` production gate verifies
creation and removal through projected bounds in two same-document leases.
Wait for that readiness before composed preview inspection; allocated stage
handles may still be preparing their dependency recipe.
Use the composed USD reader's runtime-provider schema contract to display exact
authored interface references before runtime projection. Runtime owners validate
availability and types; the diagram does not admit connections to simulation.
Publish endpoint
failures with exact identities in Recent events, not in the diagram toolbar.
Use `diagram.layout` for authored Rhai layout policy over immutable graph
facts, including independent view keys and typed interface roles. Run it on bounded workers with source/scope revision fencing and the
Application/Visualization/Preparation context; validate complete finite
placements before rendering and apply saved placements afterward. The policy
may return a bounded display label and schematic accent role; consume both in
the view without modifying USD identities. Breadcrumbs,
Back and searchable Find system share cached USD ancestry. Double-click uses
`OpenConnectionNode` and `diagram.open.plan`: systems open USD child topology,
leaf Modelica programs use the existing schema editor, and Rhai/Python use
source. Navigation must preserve exact source identity and reject missing cards.
Modelica `OpenFile` resolves registered asset URIs on its worker through
`SchemeRegistry`, preserving the document owner and read-only library state.
Exercise the installed policy with `assets/scripting/tests/test_diagram_layout.rhai`.
For system-diagram acceptance and model/view ownership, read
[Usable USD system models](../compose-multidomain-twin/references/inspectable-usd-systems.md).
Check source-graph retention and reopened views as well as visual fit.
Use `diagram.group.plan` for optional Rhai grouping over immutable program-source,
typed-port, topology and standard CollectionAPI facts; Rust validates and renders
its disjoint partition on the existing layout worker. Expanded frames and collapsed
summary cards preserve full USD topology. Resolve summary ports to their exact
original endpoint before authoring or inspecting a connection.
Component collections use their owning system's label; USD lighting collections
(`lightLink`, `shadowLink`, `filterLink`) remain illumination membership and do
not partition the engineering diagram. Use the typed
`SetConnectionGroup`, `SetConnectionGroupCollapsed`, `RemoveConnectionGroup`,
`MoveConnectionGroup` and `SetConnectionGrouping` commands; group movement is one
journaled edit for all member placements. Manual membership, disclosure, exclusions
and the grouping switch belong to each existing named view.
Membership edits validate against the full current source graph, including
members of collapsed groups, and reject summary-card keys or absent prims.
Salvage usable groups
and placements independently when an optional view file is damaged. Verify installed
policies through `assets/scripting/tests/test_diagram_groups.rhai` as well as the
layout gate; exercise collapse/expand, movement and rejection in the production API.
Persist named scopes and layouts in separate `.lunco-view.toml` project
artifacts using `lunco-doc::diagram_view` / `DocumentHost`, through typed view
commands. Each view has independent placement; USD files only own topology.
Saved source addresses use `lunco-assets-core` stable source URIs rather than
mount authorities, so views can reopen after the Twin is remounted.
Use the authored **Systems** perspective (`ActivatePerspective { id: "systems" }`)
for a full workspace Connections canvas; the Editor also exposes the same panel.
Collapsed port captions resolve their original endpoints; generated group keys are never
display labels. Repeated port names retain the member label for disambiguation.
System framing includes routed feedback wires as well as node rectangles.
Connections refreshes generated bends before drawing each changed drag
position and when Escape restores the starting positions. Verify the route
while the pointer is held through `InspectConnectionDiagram.connections[].route`
and a native screenshot. A position commit remains a view-document edit.
Ordinary and summary card widths are computed from endpoint captions at the
renderer owner; right-side port anchors use the resulting card width. Summary
geometry is passed as `summary_width` / `summary_height` in each layout group fact. The policy
uses those dimensions; it does not estimate card geometry independently.
Collapsed cards cap their height at sixteen port rows and distribute every exact
endpoint along that boundary. Captions appear only when the actual row spacing
permits readable text; the inspector retains all original endpoint identities.
Parallel feedback bindings of the same node pair and wire kind share a routed
lane; each edge still retains its own original ports for tracing and inspection.
`Save views` / `Load views` use bounded asynchronous `lunco-storage` work and
recover valid entries from missing/corrupted optional view files with warnings
and automatic layout. Different sources or unsupported versions use the loaded
USD automatic view; duplicate file owners and stale loads reject.
Mouse port connections use journaled `ApplyUsdOps`, retain declared types and
unrelated links, and Save/Undo stay source-document-owned. Layout Undo/Redo
belongs to the view document. `Canvas.movable_layout` permits node arrangement
in read-only scene views. Consume `InspectConnectionDiagram` for exact source,
view IDs, layouts, rendered ports, and logical screen coordinates. Verify scene
inspection retains same-prim bindings in the full graph and local-binding rows;
explicit Local wires reveals their routes. Drilling into a system
shows input/output/acausal interface terminals and child prims. `nodes[].key`
is the independent placement identity; `nodes[].path` stays the exact USD
prim for authoring and selection. `nodes[].role` identifies boundary terminals;
never infer runtime ownership from port names. `connections[]` retains exact
USD endpoints alongside their presentation keys. Verify input/input and
output/output boundary forwarding and rejection of terminal deletion. Verify
navigation, independent named layouts, file roundtrip, and mouse gestures in an
owned production API session, plus pure document/projector/interpreter tests.
Drag Library/Twin sources into a document diagram: USD becomes a reference;
Modelica/Rhai must land on an existing host prim. Models-palette drags retain
their typed authored port contract. Inspect `nodes[].programs` for backend,
source and resolver issues, including hidden children attributed to their
nearest visible ancestor. Drop naming/routing belongs to `diagram.drop.plan`
in `assets/scripting/policy/diagram_drop.rhai`; Rust validates its typed plan
and uses the existing journal batch. Verify terminal outcomes and placement
after source success with `connection_diagram_authoring.rhai`, including
missing-host and unsupported-source rejection. Exercise the installed policy
with `assets/scripting/tests/test_diagram_drop.rhai`.
Use `connection_diagram_wiring.rhai` for composed sink authoring, undo and
missing-target rejection in an owned document preview.
The contextual Connections inspector opens exact program facets with
`OpenConnectionNode.program_path`; an omitted program path retains normal
policy-driven double-click navigation. Show USD path/type, ports, peers and
Modelica/Rhai sources together beside the graph, using a floating panel on
compact widths. `SelectConnectionElement` validates exact cards/ports and
shares source-scoped scene/document selection. Selected nodes emphasize
incident links; selected ports emphasize exact endpoint matches, and unrelated
wires use shared disabled opacity. Use cached graph adjacency for peer rows.
Find searches prims, ports and program sources; reveal may navigate to the
exact hidden prim's parent. `NavigateConnectionDiagram` keeps view, scope,
expansion and viewport history; Back restores them after layout completes.
Verify tracing, navigation restoration and invalid identities with
`connection_diagram_explore.rhai`. Keep the header to source/mode and primary
actions, then navigation. Put named views, schema options and repository files
under View, variants under Details, and gestures under Help. Show USD dirty
state independently from view dirty state. Port dragging, click-to-connect
and the inspector Connect to picker must share endpoint/type validation; valid
targets show rings and invalid targets explain rejection before release. The
shared canvas validator rejects before EdgeCreated; ApplyUsdOps owns admission
and journaling. Distinct same-prim ports may author valid feedback.
Composed edits preserve the viewport through asynchronous layout. Verify native
dragging, undo and rejected directions with `connection_diagram_gestures.rhai`
in a visible Connections document. Supply `doc_id`, exact `source`/`sink` view
keys, `source_port`/`sink_port` and a same-direction `invalid_port` on the sink;
place the two cards within the focused viewport before running the gate.
Show acausal connectors as hollow diamonds with explicit
labels and separate counts; zero causal outputs does not mean a physical model
is disconnected. Show prim type and no authored ports for geometry/cameras.
Use `FrameConnectionDiagram` for Focus/Fit over the current view key; the render
boundary consumes its request through the shared viewport. Focus preserves
scope and topology and fits at most natural scale. Open uses the existing
double-click command. Verify exact card centering, complete-system fit and
missing-card rejection with `connection_diagram_focus.rhai`; inspect viewport
and node dimensions through the existing diagram query.
The Editor's `authoring_review` panel is the shared human-facing evidence
surface for authored/runtime inspection. Its target chain must keep `selected`,
`controlled`, and the active camera target as separate rows; do not collapse
them into a vehicle-specific status or infer control from selection. Render
retained `RuntimeDiagnostics` with the producer, severity, exact subject, and
message, and route a subject action through the canonical typed selection
command when a live `GlobalEntityId` exists. Inspection checkboxes use the
existing `DiagnosticVisualStore` leases for joints, frames, mass, forces, wheel
forces, and collision geometry. The panel is presentation only: measurements,
tolerances, provenance, candidate grouping, and preview/document navigation
remain authored Rhai over typed USD queries.
Use the `workbench.perspectives.defaults` and `workbench.perspectives.twin`
hooks to assemble task layouts in Rhai. Read `InspectWorkbench` for exact
registered panels, instance kinds and canonical instance ids.
For additional named plots, resolve their actual ids and titles through
`InspectWorkbench.docked_instance_tabs`; do not infer the next plot number.
Rust validates and applies `PerspectiveLayoutPlan`; do not add a Rust preset for changeable
presentation policy. See [Twin perspectives](../../docs/tutorials/05-twin-perspectives.md)
for the return schema, namespace, lifecycle and production acceptance. Policy
updates preserve visited user layouts; explicit Reset Layout uses the new plan.
The default Editor has no central tabs. Open documents and tools explicitly,
or declare them in the owning perspective policy; do not seed empty editors.
The center is empty when no center panel or document is open. Closing the last
center tab leaves the scene or canvas area visible without a tab strip. Reopen a
panel from View; its declared slot is restored while open documents remain
available in their own tabs. Closing a singleton from its tab updates the saved
slot intent after the egui pass, so the closed feature stays closed when
revisiting the perspective.
`PerspectiveAdmission` fences workspace restoration while definitions prepare.
Activation of the current task preserves its dock; Reset Layout is explicit.
For a title-free measurement/diagram overlay, author `floating` in that same
policy: select either `panel` or `kind` + `instance`, `corner`, logical-pixel
`width`/`height`/`inset`. Keep it exclusive with dock placement. The shared
host reuses the registered panel, publishes its rect and pointer ownership,
and survives clean recording. Empty `center` leaves full-size scene background
without a viewport tab header. Do not create a film-specific graph renderer.
Reopening an initial instance uses its authored slot through the existing
`egui_dock` owner, including when closing its last tab removed that leaf.
`default_slot()` seeds layout intent only before the first perspective is
active. After that, the active `Perspective` owns its slot declarations;
late panel registration adds the renderer without changing the current
presentation unless the panel declares `visible_in_perspective()` for the
active perspective. Use that contribution when a plugin-owned panel belongs
in another package's perspective, so the perspective does not need a dependency
on the panel package or a copied panel id. Cached user layouts still restore as
saved; contributions apply when a perspective builds its default layout.
Modelica preparation emits discrete lifecycle notices for its compilation queue,
solver-cache lookup, equation lowering, cache reuse, and elapsed preparation time.
The shared Modelica notice observer projects Info, Warn, and Error into Recent
status. Preparation notices are session/source-fenced and never solver results;
they must not release the simulation hold or change the model's time or outputs.
The workbench status history is one shared presentation surface: render Info,
Warn, Error, and Attention through the same responsive
level/source/message/action row.
Active `TwinClosed` retires progress, outcomes, and discrete history together;
the new Twin's strip and popup must not display outgoing events. Publication
counters remain monotonic, and late outgoing BusyHandle drops cannot clear
replacement progress. Closing a non-active Twin preserves the active status.
The sky-clock menu and HUD share a seek draft owned by the installed
`SceneTimeState.transition_id`; scene replacement seeds it from the new clock,
and controls remain hidden or unavailable until scene time is ready.
The status popup is sized to roughly
half the available parent window and clamped to 420–960 logical px;
the message column consumes the remaining inner width rather than an arbitrary
fixed fraction. A new terminal RuntimeFault opens the popup automatically, but
its explanation is published as the ordinary Modelica Error event in history.
Selecting that row expands the complete message. Compile failures explain why
simulation did not start and include unmatched unknown names, categories, and
referencing equation rows when Rumoca can diagnose them. Step failures list
Modelica values not produced, their last accepted values, and sample and target times.
Use one scroll area with a stable `id_salt` in this popup so egui keeps one
history surface and does not report duplicate scroll-state IDs. Ordinary
warnings and non-terminal errors remain in history without opening the popup.
Modelica opening handles end when the document is installed; diagram projection
tracks its own requested work. Verify completion with a hidden or text-only
document as well as a visible diagram so opening never depends on panel rendering.
Diagnostic rows keep the shared column geometry, expose row activation through
the cursor and tooltip, and add the complete diagnostic as an optional body
under that row. Emit the existing typed action for Attention; do not create
level-specific row layouts or source-specific styling. StatusBus
coalesces consecutive identical discrete snapshots before this shared reader.
Keep the expanded history view discrete: do not append active progress to its
event list. Hide the entire event summary from the strip while that history
view is open, including its fallback to the latest discrete event; preserve
the strip click target so it can close the popup. Active progress shows a
compact notice anchored above the strip as a non-exclusive `UI_ORDER` overlay,
never an egui popup, so it cannot close a menu the user opens while loading. Scene progress is titled “Scene loading…” or “Scene unloading…” for a
clear transition; other progress keeps its source label. The complete
owner-written message wraps inside the card, and the status strip uses the same
concise scene label. Do not infer phase from free-form text. Terrain tile
streaming, optional terrain
refinement, and post-projection scene geometry stay published for readiness
consumers but drive the workbench loading notice only during an admitted or
active scene transition. This prevents camera movement after scene load from
reopening the loading notice. “Recent status details” opens the history popup,
which stays open when work completes. The compact notice disappears on
completion; do not stack it with the history view or auto-close a history view
the user expanded.
Human-facing source text uses the mounted Twin's display name and relative path.
Keep canonical `twin://` addresses in `CurrentScenePath`, command payloads, and
API readiness labels; use `asset_path::display_source_path` or
`asset_path::display_source_text` at UI presentation boundaries.
Use native egui buttons for the clickable status summary and its empty
history-open state. The enclosing layout response anchors the popup; it does
not own the click. Verify both opening the complete warning and closing history
through injected window input in a production desktop session.
Stack application surfaces through `lunco-theme`, top to bottom: menus and
popups (egui `Foreground`), UI windows/dialogs/notices (`UI_ORDER`), the
general HUD (`HudTier::General`: sky clock, toasts, global notices), and the
specific HUD (`HudTier::Specific`: lesson or vehicle readouts). Create HUD areas
with `HudTier::area`/`HudTier::layer`; the workbench applies
`stack_hud_layers` once per pass. Never give a persistent overlay `Foreground`.
Authored runtime HUI paints before egui and stays below every egui tier.
The workbench host clears the window behind both UI passes during loading
and on the welcome screen, so authored download notices can draw before
the scene camera is available.
Tutorial rings, coach/recovery cards, and completion prompts use
`lunco_workbench_guided_ui::GUIDED_OVERLAY_ORDER` (`UI_ORDER`); the lesson HUD is
a specific-HUD readout;
their scrims use the shared `GUIDED_SCRIM_ORDER` (`egui::Order::Background`).
Workbench menus and window controls are egui `Foreground` surfaces and therefore
remain above both tutorial layers visually and for input. The workbench measures
the live menu row and right-side control group; on compact widths it keeps File
and View direct and places registered domain menus plus Edit, Settings, Help, and
Time under one keyboard-reachable `More` entry. The direct and overflow surfaces
call the same menu renderers, so command semantics and callback state have one
owner. Build responsive menu measurements from the registry snapshot and group
scripted contributions only when their popup opens. Keep this one shared layer
contract; do not rely on system execution order
or give a tutorial surface a `Foreground`/`Tooltip` order that can cover
application controls. The tutorial
draw systems are chained within their shared layer, so their relative paint order
is deterministic as well.
Rhai-contributed workbench menus use the shared
`lunco_workbench::menu_popup_max_width` helper with the egui content viewport,
fix that width before laying out wrapped rows, and let short lists shrink
vertically instead of reserving an empty scroll region. Completion state uses
the shared vector `UiIcon::Check` and `UiIcon::Pending` with accessible status
text; do not render status words or font-dependent glyphs as a second status
system. Menu contributions retain typed action descriptions under a
provider-owned ECS root; replace the root and widget scope together. Menu rows
stay disabled until the current Rhai endpoint is registered. Empty-viewport
actions use the same live readiness check, and quick-open destinations come
from current provider state. On selection the shell resolves the endpoint
again, then pins the owner-bound invocation child to its exact provider and
target Twin. Retire that child on every admission failure or completion, and
retire the provider root on replacement or its Twin's close. See `runtime-ui`
for the full callback lifecycle and production gate.
The workbench scopes only its private mutable layout out of the `World` while
painting. The authoritative `WorkbenchMenuRegistry` remains installed and is
read through an immutable frame snapshot, so layout resets do not clear menu
contributions. `PanelCtx` and `MenuCtx` trigger intents, together with shell
menu actions, go through `DeferredWorldTriggers` and are applied after the
egui pass restores the layout; do not call observer events directly from a
render callback when a typed context can queue the intent.
Egui developer overlays are owned by the shell's persisted
`WorkbenchAppearanceSettings::egui_debug_overlays`, off by default. Debug builds
offer the opt-in under Settings → Appearance. Do not enable diagnostics in
panel-local styles; the shell applies the preference to both theme styles on
all contexts before each egui pass.
Panel entries in the View menu use `PanelMenuGroup` for their primary workflow:
Build owns live-Twin construction panels, Analyze owns telemetry, graphs,
ports and joint measurements, Editor owns authored document editing panels,
and Lunica owns Modelica workbench panels. Put shared panels in
their primary home once; leave `Other` for integrations with no workflow home
and `Hidden` for internal panels that should not be user-toggleable.
Document-private viewport mounts retire at `DocumentClosed`, or when their
final preview lease ends with no workspace projection owner. Mount-set changes
prune their catalog entries before replacement scans; closing a preview must
not unregister a shared workspace authority.
Guided HUDs and runtime dropdown state register their scene lifetime at
initialization, including final cleanup after shutdown/removal callbacks.
Keep objectives visibility as an application preference. Immediate cleanup of
active-session controls on `TwinClosed` checks `was_active`; an inactive Twin
closure must preserve those controls.
Inspector parameter drafts pin their document and preview identity. Document
closure and preview removal retire them without painting; an unrelated scene
reload preserves drafts for surviving document previews. Live readouts use
the shared scene-resource lifetime, and shared shader-schema entries expire
with their assets. Queued gestures and menus pin the committed scene generation.
Callback commands also carry their exact `ToolHookBinding`; retired or replaced
bindings reject before execution. Registration scope remains application/Twin
owned, independently of an invocation's scene and callback leases. See the
[invocation ownership contract](../../docs/architecture/rhai-integration.md#how-to-load--run-a-scenario).
For Twin-browser work, use `lunco_workbench_browser::BrowserQuery` as the single
transient search field. Sections filter their own authoritative view-models by
human-readable names/paths, retain matching ancestors, and emit the existing
typed navigation actions. Do not add a per-domain search resource or make the
browser search generated ids.
Shared scene-catalog choices retire closed-mount entries at `TwinClosed`; the
catalog owner invalidates scan generations while preserving application library
and surviving-mount entries. Native spawn preflight uses the discovered asset's
admitted Twin root; checking only its filesystem path loses authored Twin
reference context and can hide valid parts. See the
[lifecycle contract](../../docs/architecture/61-scene-lifecycle-and-teardown.md).
Native USD Scene Files reads the published `SceneFileView`; never traverse or
stat files during paint or its main-thread input capture. Its single bounded
worker pins source owners/generations and a `TwinRootsSnapshot`, coalesces the
latest request, and rejects stale publication after source or mount retirement.
Keep valid rows during same-scope refresh, clear them on scope change, and make
preparation/admission errors visible without automatic retries. Verify the
active `TwinClosed` edge cancels the pending task, coalesced request and refresh
state immediately. `DocumentClosed` removes published USD rows at that edge.
Snapshots resolve authored logical Twin names against live mounts; publication
still requires the captured scope and revision. Verify the generic
`browser_retirement` and `scene_file_` lifetime/publication seams and the asset-owner closure
budget/error test; see the
[closure contract](../../docs/architecture/16-document-identity-and-collaboration.md#dependency-closure-separates-asset-traversal-from-usd-interpretation).
For hierarchy rows, use `lunco_workbench_widgets::tree::{branch, branch_header, leaf}` and
`tree::{label, selectable_label}` for row text. The shared renderer resolves
`Theme.typography.tree` and owns the
disclosure control, full-width row geometry, left-aligned label presentation,
persistent expansion identity, indentation, and the default depth-based
expansion policy. Domain panels own only their view-model filtering, stable
`egui::Id`, selection/loading state, and typed actions. Do not create a second
`CollapsingHeader`/`CollapsingState` path for a tree, or duplicate selectable-row
sizing and alignment at call sites. Do not move domain selection or loading
policy into the shared renderer. Search may force matching branches open for
the current frame; ordinary expansion remains persistent UI state.
Selectable tree rows use `tree::selectable_label`, even when they support drag
and drop or reserve trailing value columns. Wrap the shared label as the drag
source instead of replacing it with a direct `Button::selectable` call.
Project-owned settings are not user-global settings: read the active Twin's
manifest through the workspace resource and emit a typed event for changes.
Workbench hot-exit documents, tabs, and dock windows are scoped to the active
Twin. With no active Twin, use the host's startup layout and skip workspace
state load/save; do not restore loose Editor or Modelica tabs from an
app-global no-folder session.
Workspace snapshots load, prepare file-backed documents, serialize, and save on
Bevy's task pool through `lunco-storage`. Domain codecs restore documents
through their existing registries and lifecycle events. Document-backed view
tabs can remap many saved views onto one canonical document. Each instance-panel
owner declares `requires_instance_remap`: Source, Modelica and USD views use
session-allocated IDs, so unmatched restored tabs are discarded. Stable-instance
panels retain their own IDs.
Document-close owners emit `CloseTab` for every retired view. The layout owner
removes the instance from the live dock and all cached perspective docks.
Verify replacement while another perspective is active, then return to the
Editor: retired source and Modelica views must be absent, including their tabs.
For dataset consent, use the Rhai-owned progress/action model documented in
[runtime-ui](../runtime-ui/SKILL.md). Closing the prompt preserves mandatory
scene-data holds. New scene/runtime requirements reopen it; required-data
consent has no persistent suppression setting.
The Entities panel follows `SceneMountState::active_root` through the shared
`UsdSceneRoot` ancestry helper. Membership follows scene hierarchy through
nested grids and remains independent of physics frames. Additive mounts and
render-only previews are excluded. Membership is an application-owned scene
fact, not a Twin preference. Clear the derived tree on active `TwinClosed` so
outgoing rows cannot linger.
The native Updates submenu is content-sized by the workbench's shared menu
container. Keep its identity block explicit (`Version`, `GitHub Actions build`,
and `Update channel`), derive the run/attempt label only from the CI-stamped
nightly version, and show an explicit unavailable state for local builds. Do
not present a source SHA as the GitHub build number or force a feature-local
minimum width.
Generated USD runtime scene edits use the same Twin-owned settings boundary:
`usd.runtime_persistence` is one boolean opt-in for both reading and writing
the `.lunco/runtime` cache. The Settings menu reads the USD owner's policy and
emits `SetTwinSetting`; it must not register a global autosave section or
invent a second persistence path.
Camera labels are a shared projection owned by
`lunco-usd-bevy::camera_switch::camera_display_labels`. Reuse it in workbench
camera lists, the USD/entity trees, and Inspector; keep the full USD path as
the selection/tooltip identity. Unique leaves are compact, duplicate leaves
gain nearest-owner context, generated ID suffixes stay out of primary text,
and only an unavoidable normalized collision gets an ordinal.
Document-scoped editor panels use the existing `UsdPreviewId` session as their
view-model key. Keep each open session's tree, canvas, authored Inspector data,
joint/animation state, authored layer, and projection generation isolated;
the Editor perspective opens the prim tree in the upper-left pane and keeps the
Twin browser beside the Prims tab, so document choice and authored
hierarchy remain visible together. The prim tree consumes the full width of its
pane and uses immediate structural collapse rendering; do not add a nested
auto-shrinking scroll region or animated body that can paint stale outlines
over neighbouring rows.
All hierarchy rows use `lunco_workbench_widgets::tree::{branch, leaf}` and
`tree::{label, selectable_label}`; depth-based initial expansion uses
`tree::default_open_at_depth`. The Ports entity browser follows the same
contract as the Twin, Entity, USD, Modelica, library, and telemetry trees. Ports
folds composed paths into short component labels with stage-scoped disclosure
IDs. Components start folded; Scene uses the existing mounted-stage source
predicate and All components includes application and preview owners. Keep its
virtualized rows in hierarchy order; active search reveals matches without changing
normal expansion. Reserve numeric values and units before names and indentation.
Use compact magnitudes with exact values/bounds on hover; omit redundant
dimensionless markers. Prioritize the selected value and controls, with secondary
metadata in Details. Port selection opens the resizable detail pane; preserve the
typed Apply/Release actions and sample only visible owners plus the selected port.
Verify native folding, search/no-match recovery, selection/details, narrow widths,
and scene retirement in an owned production session. Raw
`CollapsingHeader` is for non-tree sections, not a second tree implementation.
The Prims rows reuse the Entities selectable-row presentation
and expose preview-scoped Visible, Invisible, and Contour controls at the
trailing edge. Those controls dispatch
`SetUsdPrimDisplayMode`; the viewport projects the typed intent and the render
binder owns wireframe rendering. Strip leading decorative bullet, circle, and
square markers from the row's presentation label without changing the authored name.
The viewport panel paints the session selected by the focused `UsdPreviewViewId`. Views share that
session projection while keeping independent camera/render-target state. The
viewport applies `UsdPreviewRenderBudget` to visible view targets (2048 px per
axis, 4,194,304 pixels per view, and 8,388,608 visible pixels per frame by
default) and leaves hidden cameras inactive. The generic ECS selection is a
focused-session projection and must be restored from editor-owned session
selection on focus changes. Dispatch edits with the session's explicit
document, authored layer, and generation through the typed USD command surface.
The full-width Prims tree owns a single vertical scroll surface; a newly
selected primary row opens its ancestors and scrolls into view, while a stable
selection leaves manual scrolling untouched.
For path-based editor selection, use `SelectUsdPrim` with the focused preview;
never resolve a USD path globally across live and preview projections.
The USD visual preview is an egui image over an offscreen camera, so its
selection surface must publish image-local primary clicks with Shift/Ctrl
modifier state. The editor selection owner maps that position through the
focused camera and ray-casts only the preview's composed hierarchy, selecting
the nearest non-empty `UsdPrimPath` ancestor. The viewport's exact image rect
is also the sole geometry source for render-target sizing and gizmo handle
mapping; do not use the surrounding toolbar-bearing panel rect. When a gizmo
handle owns a primary drag, the preview camera's competing pan path is
suppressed so the pointer remains in gizmo mode.
Scene click ownership is perspective-scoped. Read the shared
`lunco_interaction_core::SceneInteractionMode` contract: View/simulation owns unmodified
clicks for possession, while Shift/Ctrl clicks remain explicit selection or
removal intents; editor-facing perspectives own unmodified clicks for
selection and gizmos. Do not add a second per-crate mode flag or let global
pointer observers infer ownership from the hit entity.
The workbench host is also the app-level semantic input surface. The shared
contract is owned by `lunco-control-core`; editor actions
such as Cancel must consume the shared `UserIntent`/`InputBindingsSettings`
path, not a raw `KeyCode` or an assumption that an isolated USD preview has a
local avatar. `CancelIntent` suppresses the action while egui owns keyboard
focus, preserving text-field editing.
Avatar presentation has one wall-clock interaction cadence. Free-avatar port
writes, locomotion, and camera look application belong to
`lunco_time::InteractionSchedule`, not `FixedUpdate` or a direct `Update` pose
writer. Render-frame pointer input may be buffered before that schedule, but
the interaction step must consume it once alongside movement so pause and
simulation rate changes cannot split orientation from translation.
For authored UI workflows, use the controller's `InjectWindowInput` command and
the Rhai helpers in `prelude/input.rhai`. They enqueue typed key, pointer, and
scroll events through the same Bevy aggregate `WindowEvent` and typed input
messages produced by `bevy_winit`; picking, egui, focus, and semantic bindings
therefore keep their normal owners. Rhai composes chords, clicks, drags, and
workflow timing. Do not call a scene tool directly, synthesize a
`ScenePointer`/intent event, or create a second UI automation command for a
particular panel. Coordinates are logical primary-window pixels, and the
command is local to the client window.
In View, a click on a vehicle part resolves through the enclosing authored
`ControlBinding`/`MobilityRoot` before considering nested component input
surfaces, so the vehicle remains the possession target. Standalone non-avatar
input surfaces remain valid direct targets.
For interactive reusable-assembly authoring, follow the
[edit-usd-assembly runbook](../edit-usd-assembly/SKILL.md): the production
window must remain headful and visible to the user, each coherent typed edit
must be followed by a screenshot the agent inspects, and user feedback is a
required checkpoint before the next material edit or save. Do not turn a panel
into a direct file writer or a second session/state owner.
World-space vehicle trails are transient render presentation, not UI-owned
state. Read solved wheel contacts after `WheelRaycastResultsSet`, retain bounded
stroke history, and clear it on frame changes and `SceneTeardown`. A moving
endpoint provides sub-spacing continuity; missing wheel support starts a new
stroke, including airborne and inverted motion. Wheel marks set
`SurfaceCurveAnnotation.receives_lighting` and blend into the ground material
before lighting, so they receive shadows. Route overlays retain their unlit
colour. Use the physical wheel's full
width for both shared-tire and native-material contact realizations; the
optional `JointedWheelTire` force component must not gate contact history.
DEM contacts resolve their `ColliderTileOf` owner and reuse streaming
`SurfaceCurveAnnotation` segments painted on terrain fragments; ordinary static
supports use the shared contact-plane ribbon builder. Do not derive tracks from
root motion, visual wheel roll, controller input or authored routes. Inspect
`InspectVehicleTrail` and exercise `vehicle_trail_contact.rhai` through the
production API; verify the exact target scene visually. See the canonical
[motion trail contract](../../docs/architecture/50-usd-driven-visuals.md#motion-trails-are-bounded-physics-history)
for history, admission budgets and publication fencing.
## Runtime-authored HTML/CSS surfaces
For an application or Twin HUD, telemetry card, progress overlay, or simple runtime
control that should change without a Rust rebuild, use the dedicated
[runtime-ui skill](../runtime-ui/SKILL.md) and
[`docs/architecture/runtime-authored-ui.md`](../../docs/architecture/runtime-authored-ui.md).
HUI/Flair reads the generic `EngineExposures` registry and shares the
workbench's dock and pointer geometry. Ordinary surfaces draw on
`WorkbenchEguiHost`. Surfaces with `"overlay": true` draw above dock panels
on `WorkbenchOverlayCamera`. Both share the scene camera's main texture and
MSAA/HDR key. Use `"owner": "application"` in the application manifest when a
surface needs to survive scene teardown and Twin changes. Use `Panel`/egui for
docked editors and `runtime-ui` for authored HTML/CSS surfaces. The
manifest controls the retained surface's outer rectangle: the runtime pins its
minimum and maximum size to the resolved placement and clips overflow, while
the authored CSS/profile must fit its contents inside that boundary. The
`lunco-ui::modal` host is the canonical owner of queued modal outcomes,
scrim, focus, Esc dismissal, and typed `CloseModal` dispatch. Base HUI does not
provide those dialog semantics. The separate `bevy_hui_widgets 0.6.0` crate
offers primitive input, slider, and select mechanics, but it is not included in
LunCoSim and does not define clipboard, validation, keyboard-navigation,
accessibility, or modal semantics; do not route a rich editor through it
without a new typed contract and acceptance tests.
For lander control cards, keep GNC identity and state on the existing authored
USD boundary: resolve the column-zero `lunco:ui:schemaNode`, then read its
`ModelicaModel`/`SimComponent` lifecycle and authored causal ports. Do not use
the generic `Autopilot` actor as a lander GNC indicator, infer GNC from a prim
name, or create a second status store. Add operator channels with
`LunCoTelemetryAPI` on the guidance component so the compact card and the
telemetry browser read the same SignalRegistry samples. The card must expose
unavailable, compiling, ready, active, paused, handoff, and failure states;
absence of an actuator sample is not permission to hide the authored surface.
The runtime exposure producer must additionally scope card roots to the active
`SceneMountState` root. Preview, additive, and outgoing scene entities are not
operator HUD sources, and a repeated ECS projection of one composed `(stage,
prim path)` must not fill a second manifest slot; report the duplicate at the
projection owner and retain one active identity. Scene-derived exposure
namespaces are hidden synchronously on `SceneTeardown` so deferred despawns
cannot leave the outgoing card visible; the next active scene repopulates them,
while retained application facts such as `camera-status` remain available.
The Modelica diagram's `Show nets` checkbox is the Connections legend's single
workbench/egui presentation control, backed by the per-tab
`lunco-canvas::Canvas`. It hides rendered and interactive connection edges
without changing authored topology. Keep the legend and this dynamic graph
control in the canvas panel; HUI/Rhai does not provide the dynamic list and
graph-state contract it would require.
For demonstrations, set `DiagramPresentationSettings.show_controls` to false
through Rhai or Settings → Appearance. This shared, persisted preference removes
diagram editing/navigation chrome from Modelica and connection views while
preserving wires, live values and diagnostics. Do not clear topology or remove
the navigation overlay object to obtain a clean view. Restore the same setting
after filming if the operator is returning to editing.
Modelica **semantic zoom** is an opt-in native presentation mode in Settings →
Appearance, or `ConfigureDiagramPresentation { semantic_zoom: true }`. Scrolling
into a component replaces its icon with its actual nested Modelica diagram,
recursively; leaf components show their parsed equations and algorithms. Inline
previews are read-only, retain full instance paths for values, and use the same
native canvas layers. Double-click still opens the definition for editing. Turn
it off to restore the ordinary icon view. Preparation is background work under
the existing diagram node budget; cycles and limits show diagnostic cards. Source epochs invalidate nested previews after cross-file edits.
At deep zoom, `lunco-theme::presentation::diagram_text_galley` bounds physical
glyph rasterization and scales meshes to preserve authored text dimensions; use
that owner for diagram/icon text instead of requesting enormous atlas glyphs.
Canvas-owned diagram overlays must stay inside the owning leaf: direct painting
uses the canvas clip rectangle, while an `egui::Area` uses `constrain_to` with
the measured leaf rectangle. Non-interactive overlays do not claim pointer
input, and modal dialogs use the shared `lunco-ui::modal` host.
## Adding a Panel
```rust
use lunco_workbench_core::{Panel, PanelCtx, PanelId, PanelSlot};
use lunco_workbench::WorkbenchAppExt;
use lunco_ui::prelude::*;
pub struct MyPanel;
impl Panel for MyPanel {
fn id(&self) -> PanelId { PanelId("my_panel") }
fn title(&self) -> String { "My Panel".into() }
fn default_slot(&self) -> PanelSlot { PanelSlot::RightInspector }
fn render(&mut self, ui: &mut egui::Ui, ctx: &mut PanelCtx) {
// READ state — view-model resources / selected components via the
// ctx, never raw `&mut World` scans, never mutate.
if let Some(sel) = ctx.resource::<UiSelection>() {
// ... read sel ...
}
// EMIT a typed command event — never mutate directly.
if ui.button("Action").clicked() {
ctx.trigger(MyCommand { /* ... */ });
}
// Other supported mutations are queued through the same context:
// ctx.set_resource(MyResource::default());
}
}
// Register in ui/mod.rs through the concrete shell:
// app.register_panel(MyPanel);
```
## What NOT to Do
| ❌ Don't | ✅ Do |
|----------|------|
| Mutate resources directly from UI | `ctx.trigger(TypedCommand { .. })` (or `ctx.defer`), let observers handle it |
| Put UI code in `lib.rs` or outside `ui/` | All UI in `src/ui/` subdirectory |
| Use `world.query()` every frame for graphs | Use `WidgetSystem` for O(1) cached queries |
| Copy a SignalRegistry history every graph paint | Use the visualization-owned history fingerprint cache; copy only at the egui plot data boundary |
| Reproject every canvas edge every paint | Cache screen geometry by scene generation and viewport key; keep selection/tool state live |
| Walk the dock tree once per anchor group | Publish all slot anchors from one dock traversal |
| Build custom docking/themes | Use lunco-workbench — it's already there |
## Discovering Existing Commands
Commands are typed structs marked `#[Command]`, handled by observers
marked `#[on_command(TypeName)]` (both from `lunco_core`). To find what
commands exist:
```bash
# Find all command observers
grep -rn "#\[on_command(" crates/
# Find all command struct definitions
grep -rn "#\[Command" crates/
# Find where a command is emitted from UI
grep -rn "\.trigger(" crates/
```
To add a new command: define a `#[Command]` struct + `#[on_command(..)]`
observer in the relevant domain crate (see the `test-via-api` skill's
"Add a command" section for the full pattern).
## When to Use WidgetSystem
| Use `WidgetSystem` | Use raw queries |
|-------------------|-----------------|
| Queries same entities every frame | Reading 1-2 resources |
| 10+ query fields | Simple UI, minimal ECS |
| 100+ rendered items | Infrequent panels |
## File Structure
```
crates/lunco-ui/ ← mechanisms (WidgetSystem, typed commands, 3D UI)
crates/lunco-*/src/ui/ ← domain-specific panels
```
Wheel-track history uses `VehicleTrailSettings.max_points_per_wheel` (default
32768, about 16 km at half-metre spacing). Terrain annotations preserve retained
history through adaptive spatial subdivision; they never shorten a lane because
a root cell is crowded. Moving heads and retirement emit stable segment deltas;
`InspectVehicleTrail.annotation_edits` exposes the consumed update count.
Dirty-range uploads preserve the resident texture and its material bindings.
Budget errors are terminal publication diagnostics.
Validate long curved paths as well as live contact, and inspect actual GPU
output after image capacity grows.
Instance navigation uses the reflected `OpenTab` and `CloseTab` commands with
`{ kind: String, instance: u64 }`; discover kinds and canonical identities from
`InspectWorkbench`. Unknown kinds reject at the shell. Preserve deferred
command outcomes when the dock is temporarily scoped out. Saved dock snapshots
carry central-instance intent independently of policy defaults.
`scene_mounted` reports an actual mounted payload; `scene_generation` is a
lifecycle revision and may describe a committed Clear.
## Twin navigation and orientation
In document tasks, explicit center-instance opens establish center intent at the dock owner, even
when Editor starts empty. Verify the actual rendered editor rectangle beside
the browser, rather than only its allocated tab/source identity. Scene-backed perspectives
keep background previews parked so they cannot cover the live world.
The Twin panel defaults to the active Twin's files. Its selector displays one
registered Files, Library or specialist view at a time. Changing views clears
`BrowserQuery`; `SetBrowserSection` rejects unknown identities without changing
selection. Untitled/loose documents get standalone rows; saved Twin files appear
once with open/dirty markers. Scene choices remain in Scenarios. Editor tab
hover/context menus consume exact URI/purpose from `navigation_source`, with
Reveal in Twin using the existing typed command. Keep source context local to
its tab. The file tree rebuilds on workspace/query changes outside paint;
scene choices use `list_indexed_scene_assets` over admitted inventories.
Quick navigation uses the core `NavigationRegistry` provider mechanism. Reuse
existing inventories, canonical identities, and typed commands; do not parse or
perform I/O during paint. Ctrl/Cmd+P initially lists Twin files, while typing or
choosing a scope exposes libraries/scenes/actions. Scene results explicitly say
Load. Ctrl/Cmd+Shift+P opens panel/perspective actions. Alt+Left/Right visits bounded
document/perspective history without loading worlds. Active `TwinClosed` retires
search and history; queued requests and destination identities must reject stale
ownership. Verify with the authored `workbench_navigation.rhai` gate via
`scripts/api/test_workbench_navigation.py --port <free-port>`, plus native shortcut
input and screenshots of a populated Twin browser, preview and search.
### Configurable command shortcuts
Settings → Keybindings uses the `input_settings` Rhai perspective. Register an
existing typed command, then author its shortcut in the input-bindings document;
do not add per-panel hardcoded command-key handlers. `lunco-input-core` owns
normalization and collision precedence. `lunco-workbench` validates edits and
dispatches through the transport-free reflected command core. Menu labels read
`ActiveInputBindings::label` so remapping and Twin overrides remain visible.
Twin bindings displace conflicting global chords in the effective snapshot only;
Recent Events reports the winner and displaced identity when conflicts change.
Use `InspectInputBindings` plus native injected key events in authored behavior
trees to verify override, rejection, notification and restoration. Run
`scripts/api/test_command_keybindings.py --port <owned-free-port>` and inspect
the settings capture.
## Editing, compact layouts, and control access
Use the [workbench editing contract](../../docs/architecture/11-workbench.md#panel-visibility-drafts-and-export-snapshots)
for panel visibility, draft ownership, and immutable CSV export semantics.
`InspectBehaviourEditor` supports production observation of draft retention,
compile completion and retirement. Panel names distinguish Signals, Camera &
Control, Scene Properties, Component Properties, Model State, Source Viewer,
Programs, Component Library, Behaviour Editor and Rhai Console; keep canonical
panel IDs in commands. Verify wrapped toolbars at 1280×800 and 960×540.
Authored press controls expose native keyboard navigation and an accessible
Controls-menu route. Follow the
[runtime UI accessibility contract](../../docs/architecture/runtime-authored-ui.md#keyboard-and-assistive-control-access)
and inspect labels, hidden/disabled admission, focus outline and scene retirement.
Keep source identity separate from asset-loading lifetime: use
`AssetFile.source_uri` for catalog IDs, authored program/shader references and
persisted source tabs; use its `asset_path` only for native loading/cache leases.
Narrow Requirements docks use readable selectable cards; All columns exposes the
full table. Verify the source action opens the indexed SysML document.
SysML source navigation reuses its canonical editor in a resizable window. Keep
retained source drafts in `SysmlRequirementsState` and retire them on `TwinClosed`,
including hidden panels. Preserve the canonical typed apply/save path.
Shader Create/Import returns a terminal result with a stable `source_uri`; use
that result before applying it. Existing shader files reject creation/import
without replacement. Behaviour Editor keeps Apply pending until the USD owner
completes `SaveScenario`. Test these negative and successful results with
`scripts/api/test_ui_review_followup.py --port <free-port>`; its rapid exits also
require a clean process exit. A dirty SysML source draft disables Close editor
until Save or Discard resolves it. Runtime press admission is shared across
pointer, keyboard, menu and assistive clicks; preserve authored tab order and
retire nodes/tab stops when their callback or surface lease ends.
Unapplied editor buffers register application close checks through
`lunco-workbench-core::app_close::AppCloseGuards`. Read current owner resources
and exact source leases at admission; do not copy draft text into a second dirty
registry. Return a warning and typed reveal callback until Run/Revert or
Save/Discard resolves the draft. Normal close and final dirty-document exit use
the same guard consumer. Retired scene/Twin leases must not block closing.
Application close captures exact dirty document IDs and prompts once per
document. Wait for document retirement, not a fixed number of frames. Save
failure and Save-As picker cancellation must release that document's pending
close; Cancel cancels the remaining request. Test the native Cancel and Don't
save actions through `scripts/api/test_runtime_accessibility.py --port <free-port>`.
The Twin files dirty projection reads all document kinds from Workspace.