Panels: inspect and change layouts through commands (#11304) (#11454)

* claim: #11218

* Panels: add shared layout rules and retained content runtime

* claim: #11304

* Panels: inspect and change layouts through shared commands (#11304)

* Panels: account for layout commands in geometry coverage
This commit is contained in:
Nathan Dane
2026-11-03 13:55:50 +00:00
committed by GitHub
parent 372136fa6a
commit fbd30b0bd0
37 changed files with 11837 additions and 13 deletions
+207
View File
@@ -1,5 +1,212 @@
# Control protocol
The [universal panel foundation](panel-foundation.md) supplies typed layout actions
and retained runtime guards. The application-layout commands below are registered
engine commands reached through `engine.execute`, `engine.batch`, `engine.script`
and MCP's existing `execute`/`batch` tools. They require an injected application
backend; enabling the internal panel runtime remains an explicit integration step.
Current product defaults and the production shell are unchanged.
### Application panel and layout commands
Every command has input and output schemas through ordinary command discovery.
Inputs are strict at every parameter-check level: unknown fields, including nested
placement fields, are errors. As with other engine calls, omitted/null parameters
mean an empty object. IDs use the foundation's bounded lowercase ID domains;
dimensions are finite positive outer logical units, at most 32768. Requests are
bounded to 16384 encoded bytes before cloning or deserialising. No command opens a
dialog, edits the document, changes dirty/undo/revision, evaluates or tessellates a
model, fits a body, follows a camera request or selects a ribbon/tool/document tab.
Layout revision is independent of document revision.
Canonical existing targets are typed: `{"target":{"type":"instance","id":"log"}}`.
`section`, `workspace` and `native_host` are the other foundation target types;
each command accepts only the domains listed below. A legacy `id` may replace
`target`, but both together are rejected. It first resolves an exact instance ID.
A kind ID resolves only when its registration is single-instance and exactly one
canonical instance exists, including retained closed state. Multi-instance kinds
are rejected even when only one instance currently exists. No first-match guessing
or implicit instance creation occurs. `panel.open` instead requires separate `kind`
and `instance` fields.
All mutations accept optional `expected_revision:u64`. A stale revision produces
the foundation `revision` rule and leaves the command's layout and catalogue
unchanged. Successful mutations return the committed `LayoutReply` (layout,
revision, interaction, effects, capabilities and availability), never an echoed
placement request. `layout` includes all retained instances with `requested_open`,
ordered sections and their active tabs. Missing availability entries mean available.
Query replies contain no new host effects.
| Command | Parameters and behaviour |
|---|---|
| `panel.list` | `{}` → `{state:LayoutReply,kinds:[PanelSpec]}` from the live sink and registry. |
| `panel.open` | `{kind,instance,destination?,expected_revision?}`. New instances require a destination; closed instances can reuse remembered placement. |
| `panel.close` | `{target:instance,expected_revision?}`. Explicit guarded close retains placement and can refuse cancellation. |
| `panel.move` | `{target:instance,destination,expected_revision?}`. Existing open instances only. |
| `panel.resize` | `{target:section|instance,size:{width,height},expected_revision?}`. Instance must have an open section; all tab bounds intersect. |
| `panel.collapse` | `{target:section|instance,collapsed:bool,expected_revision?}`. Keeps requested dimensions. |
| `panel.float` | Same as move, requiring a `new_section` with `floating` location. |
| `panel.popout` | Same as move, requiring a `new_section` with `window` location and return destination. Desktop/headless without native capability refuse; web explicitly lowers to `floating`. |
| `panel.focus` | `{target:instance,expected_revision?}`. Reopens retained closed state, activates, expands and requests focus. |
| `panel.activate` | `{target:instance,expected_revision?}`. Activates an open tab without expanding or requesting focus. |
| `panel.peek` | `{target:instance,expected_revision?}`. Temporary presentation of a collapsed tab, without persistence changes to size/collapse. |
| `panel.dismiss` | `{expected_revision?}`. Dismisses transient peek. |
| `panel.resize_pair` | `{first:SectionId,second:SectionId,first_size:{width,height},second_size:{width,height},expected_revision?}`. Adjacent sections of one dock; conserves split-axis extent and cross-axis dimensions. |
| `panel.reset_pair` | `{first,second,expected_revision?}`. Resets adjacent sections to the registered default ratio within intersected bounds. |
| `panel.native_close` | `{target:{type:"native_host",id:HostId},expected_revision?}`. Native window close redocks its whole section; it does not explicitly close/cancel content. |
| `layout.save` | `{name,overwrite?:false,expected_revision?}` → `{name,overwritten,state}`. Saves the complete current envelope in the injected catalogue. |
| `layout.apply` | `{name,expected_revision?}`. Applies a named preset to the **current** workspace, rebinding its known layout workspace ID. |
| `layout.reset` | `{expected_revision?}`. Applies the selected workspace's registered immutable default. User presets and other workspace histories remain. Missing defaults return a capability error. |
| `layout.get` | `{}` → `{state,workspaces:[{id,title_key,default_preset,has_remembered_layout}]}`. Selection is only `state.layout.workspace`. |
| `layout.workspace.select` | `{workspace:WorkspaceId,expected_revision?}` → `{previous_workspace,source:"remembered"|"default_preset"|"unchanged",state}`. Registered descriptors only; no implicit creation. |
Destinations are distinct foundation operations, not aliases:
```json
{"type":"new_section","section":"logs","index":0,"location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}
{"type":"join_tab","section":"logs","index":1}
```
New-section indices address the global section order after detachment; join indices
address the destination's tab list after detachment. Joining keeps the destination's
activation, collapse and dimensions. Locations are `dock` (left/right/bottom),
`floating` (`origin:{x,y}`), or `window` (`host`, `origin`, `return_to`). Native
`return_to` contains `{zone,index,size,collapsed,join?:{section,index}}`; it never
recursively contains another native host. Pins and placement/size intersections
retain the foundation's structured refusal rules.
Preset names trim surrounding whitespace, require 1..64 Unicode scalar values and
reject controls anywhere in the supplied name. Raw input is capped at 1024 UTF-8
bytes before trimming; the trimmed name is at most 256 bytes. Names are case-sensitive.
There are at most 64 user presets. Collisions reject unless `overwrite:true` is
explicit; built-ins are immutable. No production kinds, preset contents or workspace
descriptors are invented. Headless starts with an empty registry/catalogue and an
internal current-layout identity, not a registered product workspace. Fixtures and
peer integrations can inject synthetic or real registrations. Missing capabilities
return errors rather than guessed defaults or disk/native success.
Workspace selection stages the outgoing full envelope, destination and selected
workspace together, then uses one guarded `Replace` on the retained runtime.
Same-workspace selection is a true no-op, preserving revision, focus, peek and
effects even if storage staging is unavailable. Applying/resetting a preset never
selects a workspace. Replacements hide omitted content without implicit Close or
Cancel; retained editors, conversations and hidden services survive A→B→A.
Catalogue preparation uses encoded full `LayoutEnvelope` records and explicit
aggregate caps: 64 registered workspaces, 64 built-ins, 64 remembered envelopes,
64 user presets, 16384 metadata bytes, and 4194304 aggregate envelope/recovery bytes.
Each envelope/rejected recovery buffer remains at most 262144 bytes and obeys the
foundation node/depth/collection caps. Quarantine, retained data, shared section
snapshots including projected sections, complete section order and bounded rejected
recovery intent survive save/apply/reset. Conflicting opaque identities, snapshots,
retained data or recovery intent reject atomically. Restoration uses the foundation
decoder and reappearance logic. Storage preparation finishes before live dispatch;
catalogue publication is infallible after successful native/controller guards.
Revision changes during staging reject the staged catalogue. No fallible storage
write after live commit is treated as an atomic success. The shipped catalogue is
in-memory; production preference durability and migrations remain peer work.
Atomic layout batches contain 1..64 commands, using the same parser/executor and
one final guarded Apply or Replace plus one catalogue publication. Queries and
saves may accompany mutations; save/apply/reset/workspace sequences can stage
together. Replies describe the **final committed** state, not hypothetical
intermediate live states. Every `expected_revision` in an atomic batch refers to
the initial live revision. Explicit Close/Open conflicts remain `lifecycle` errors.
Atomic batches cannot combine a snapshot replacement with explicit panel mutations,
or mix document commands with application layout; they return `capability` before
publishing anything. This preserves the foundation's explicit lifecycle intents.
Use `rollback:false` for sequential per-command transactions across these domains;
failures report `rolled_back:false`, `undone:0` and completed results. Scripts use
the same injected backend sequentially and stop at the first failure. A Session-only
executor (including ordinary CLI design scripts without an injected backend)
returns a structured missing-capability error for layout commands.
The GUI route uses the enabled runtime's actual content-service provider and an
injected `NativeHostAdapter`, never a reconstructed LayoutService. Headless MCP
owns one persistent application backend distinct from Session; Remote forwards to
the app and keeps no mirrored layout. Auto mode does not discard headless layout
work when an app appears. Foundation errors retain `{rule,detail}` with bounded
details: control replies add `panel_error` alongside the existing error string;
MCP tool errors add `structuredContent.panel_error`. The error string also encodes
that object, preserving identity through older string-only backend boundaries.
Rust integrations implement `ActionSink::project(LayoutAction)` as a pure
projection on the authoritative service. Its default returns `capability` so an
older inspect/dispatch-only sink cannot accidentally publish unstaged commands.
`LayoutService` and `RuntimeActionSink` provide it using the foundation's own
preparation path. `with_live_layout` refreshes the envelope's shared section memory
and projections without discarding opaque fields, then encodes against the same
foundation limits before publication.
Storage consumers can enumerate `CatalogueState::user_presets()` read-only and
round-trip a complete validated catalogue with `export()` and
`CatalogueState::hydrate(bytes,registry)` or `InMemoryCatalogue::from_snapshot`.
Hydration is independent of live commands; restored users remain explicitly
overwritable users, while built-ins remain immutable. Workspace descriptors,
remembered full envelopes, and rejected recovery bytes are included. The versioned
snapshot uses `SCPCAT01`, then length-prefixed little-endian u32 counts/UTF-8 names
and raw byte records, in built-ins/users/workspaces/remembered order. Each envelope
record contains length-prefixed envelope JSON, a recovery-presence byte (0/1), and,
when present, length-prefixed exact recovery bytes. Workspace descriptors contain
ID/title-key/default-name strings. The snapshot has an additional 8192-byte framing
allowance above the existing aggregate payload/metadata caps (4218880 bytes total).
Every count/string/record is bounded before allocation, and hydration rejects
duplicate names across users/built-ins, duplicate workspace keys, corrupt framing,
trailing data, invalid envelope identities and all existing aggregate/node/depth
limits before a candidate can be published. This seam performs no disk storage.
Reading a retained envelope does not consume quarantine merely because the registry
has grown. `decode_retained_record` validates an already-retained record exactly;
`decode_retained` additionally checks its workspace. Neither reader generates
section order/projections or performs quarantine migration/reappearance. Hydration
preserves the original validated record bytes and rejected binary data, including
records at the per-envelope or aggregate cap when optional panel kinds disappear
or return. Missing registrations do not invalidate unrelated users, built-ins or
workspace memories. Retained validation checks structural ownership, placement
bounds and all applicable known-kind constraints, without invented descriptors.
An exact retained layout can still contain absent kinds and is not live admission.
`StoredEnvelope::project_envelope` (or foundation `project_retained_record`) stages
missing-kind quarantine before a guarded live use, preserving full section order,
activation and opaque records. This staging does not consume existing quarantine;
ordinary save/live overlays therefore keep reappearance retryable after registry
growth. Foundation `decode` also stages migration and attempts restoration, with
its existing fallback/rejected-input result contract.
Materialization may legitimately exceed a cap and reject its staged candidate;
reading/hydrating the accepted original record does not materialize it.
Apply/reset/workspace replacement
explicitly stage restoration, and consume it only with a successful authoritative
Replace and catalogue publication. A failed action leaves the restore obligation
retryable. `panel.popout` requires the panel's `features.popout` on both web and
native policies before any enabled web fallback; `panel.float` remains separate.
Application command, atomic-batch and GUI action boundaries refresh the current
read-only provider/document environment and availability. A document or contextual
model change earlier in a sequential batch/script is visible to the next panel
step without a tick. Queries and failed actions cannot borrow the previous
document's context. No content tick, document edit, geometry work or camera tail is
added to this boundary. All application GUI and command routes use one stored
native adapter, installed once; redock its native sections before disabling it.
Unsupported atomic intent mixtures are rejected by pure structural preflight
before any context/controller publication as well as before layout/native effects.
At MCP tool level, an atomic batch containing any panel/layout command must reach
the authoritative batch transaction. If the endpoint is unavailable or the encoded
request exceeds its transport margin, a structured zero-effect capability/size
refusal replaces the old sequential fallback. No document checkpoint or individual
layout command is sent. Explicit `rollback:false` keeps the sequential fallback
and reports completed layout changes honestly. Document-only batch fallback keeps
its existing checkpoint/rollback behaviour. Explicit null parameters normalize to
an empty object in single, atomic, sequential and script routes for GUI/headless.
Compatibility: `view.layout` still means Floating/Compact **surface styling**.
History-in-Browser, History Bodies/Origin and Render search/options remain content
preferences. Existing `view.history_layout`/`view.render_dock` controls continue to
serve the existing shell. There is no safe universal alias without registered
instance identities: `browser`/`under_browser` combine content with placement, and
Render dock changes can affect a pair. They are not silently mapped to universal
instances. Integrations with explicit identities can issue typed `panel.move`,
`panel.resize` and `panel.collapse` requests for safe placement changes. No command
implicitly selects a layout workspace on a document, ribbon, tool or context change.
For UI-kit review, `ui.status_fixture {"preset":"mode"}` shows bounded status
specimens in the real viewport. Presets are `off`, `mode`, `result`, `attention`,
`row`, `kinds`, `many` and `key`; the reply carries the preset and item count. This
+309
View File
@@ -0,0 +1,309 @@
# Universal panel foundation
The public foundation is `solidcraft_engine::panels` and
`solidcraft_ui_egui::panel_runtime`. It establishes contracts and executable
synthetic fixtures for #11302. The current shell and defaults remain in use.
No panel commands, preferences, content migrations, native windows or docking
gestures are enabled by this change. Classic remains a permanent compatibility
preset. Production adapters land in the separate children of #11218.
## Ownership and integration boundaries
| Owner | Public contract | Responsibility |
| --- | --- | --- |
| Foundation / engine | `PanelRegistry`, `PanelSpec`, `Layout`, `LayoutService`, `ActionSink` | Stable identities, bounded wire values, constraints, atomic actions and inspection. No egui or Session dependency. |
| Foundation / UI | `PanelRuntime`, `ControllerBinding`, `PanelController`, `RuntimeActionSink` | Retained state, ownership, lifecycle preflight, live availability, independent service ticks. |
| Host child | `PanelHost`, `PanelContext`, `ResolvedLayout`, `EguiPanelHost` | Geometry, host composition and later docking interactions. Existing `ui_kit::Container` remains the outer boundary. |
| Command child | `LayoutAction`, `LayoutReply`, `PanelError`, `LayoutTarget` | Register schemas and route GUI/agent requests to the live runtime sink. Do not construct a second service from a saved snapshot. |
| Persistence child | `LayoutEnvelope`, `LayoutPersistence`, `decode`, `encode` | Workspace preference key, atomic storage, presets and future migrations. Keep unrelated preferences. |
| Native child | `NativeHostAdapter`, `HostEffect`, `HostCapabilities` | Preflight resources, native host realization, focus and redock. No native implementation is included here. |
| Surface/accessibility children | `InputRegion`, `ControlId`, `Direction`, `Motion`, `ContrastOutcome` | Painted/input bounds, semantic roles, keyboard routing, mirrored edges, reduced motion and validated theme surfaces. |
| Content children | `PanelModels`, `ContentCommandSink`, `PanelLocalServices`, content slots | Model access, explicit content commands, controllers, owner-scoped services and independently scrolling content. |
Panel kind, instance, section, workspace, document, viewport, native host and
semantic control IDs are different Rust types. Their wire values are bounded
lowercase identifiers. Registry specs and serializable layout never contain
callbacks, document state, egui state or live editors. Only `allowed_zones`,
`edge_rule` and `surface` express placement exceptions. Normal capabilities
(close, tabs, collapse, popout, multiple instances) are shared feature flags.
Layout belongs to the application/workspace; it never enters a design file,
Session revision, dirty flag, undo stack, evaluator or tessellation cache.
`ContentOwner` independently chooses application, workspace, document or window
ownership. A native reparent does not change content ownership. Document switching
retains existing controllers and creates only missing owner/instance bindings.
Complete layout application changes the live workspace without replacing the
runtime or service. Application/document/window controllers keep matching instance
identities; workspace controllers remain under their original workspace owner and
continue ticking while hidden. Switching back reuses those controllers and drafts.
All retained controllers receive service updates even when closed, unavailable,
inactive, collapsed or on another document. Providers must expose models for
retained owners, not redirect old-document reads to the current document.
`SolveApp::enable_panel_runtime` accepts a runtime and `AppPanelServices` explicitly.
Its optional field defaults to `None`, remains on the app across document tabs,
and is ticked from `SolveApp::logic` independently of presentation. Refresh receives
only `&Session`. `disable_panel_runtime` preflights cleanup and requires native
sections to be redocked before dropping their adapter. Tick failures remain
inspectable on `AppPanelRuntime::last_error`; they do not inject untranslated UI.
This is an internal adapter seam, not a preference, environment switch or control
method. `dispatch_panel_layout`, `mount_panels`, `panel_content_action` and
`tick_panel_runtime` forward through the same injected provider. Application
command, atomic-batch and GUI dispatch boundaries refresh the read-only provider
and current document environment before inspection/projection. Availability is
refreshed without ticking content, evaluating models or creating geometry; retained
service failures still require a successful real update to recover. Sequential
programmatic model/document changes are therefore visible to the next panel step
without waiting for a frame tick.
`AppPanelRuntime::set_command_adapters` installs one catalogue and one native
adapter once, before native hosts exist. Both `SolveApp::dispatch_panel_layout(action)`
and command routes use that stored adapter; there is no per-call native argument.
`AppPanelRuntime::dispatch`, content actions and command/batch methods take the current `&Session`
for read-only context refresh. Its runtime is private with a read-only `runtime()`
accessor; service borrowing is internal, so consumers cannot replace the runtime or
dispatch through another adapter through a mutable services callback. Standalone
`PanelRuntime`/`RuntimeActionSink` fixtures retain their explicit fake-adapter seam.
Changing the installed application adapter is refused rather than abandoning its
created hosts. These are integration APIs, not a production native implementation.
## Actions and atomicity
`ActionSink::dispatch` accepts `Inspect`, `Apply { expected_revision, mutations }`
or `Replace { expected_revision, layout }`.
GUI, keyboard and agent adapters share this reducer. `RuntimeActionSink` adds
controller/native lifecycle guards around the same engine service. Runtime users
receive immutable layout inspection; there is no mutable bare-service escape.
Replies describe committed layout, revision, availability, interaction, capabilities
and host effects. Layout revision is independent of document revision.
`Replace` validates a complete preset/saved layout and atomically changes the
workspace on the same authoritative service/revision. It stages availability,
controller factories and native create/rebind/release effects before committing.
Omitted entries and entries marked closed are noncanceling hides: their retained
controllers keep drafts, conversations and service updates, with no collapsed rail
unless the snapshot actually requests one. Restoring the snapshot restores those
controllers. Instance IDs cannot change kind across workspace switches; the service
retains a bounded identity catalogue until explicit Destroy releases an identity
and all of its retained owners. Unknown kinds fail atomically; persistence
adapters first decode/quarantine unknown data and apply the known layout portion.
Registered kinds with missing bindings or unavailable context remain dormant.
After successful replacement, old local input/overlay ownership is released;
failure leaves environment, revision, controllers and local/native hosts intact.
Use this operation for workspace switching rather than rebuilding a runtime or
synthesizing Close/Open batches. `set_environment` changes document/window/viewport
context within the already committed workspace.
- `Open` targets kind **and** instance. New instances require an explicit destination;
an existing closed instance can reopen from its remembered placement and size.
Repeating an open is idempotent unless a new placement is supplied; use `Move`.
- `NewSection` and `JoinTab` are distinct destinations. Section insertion indexes
address the global ordered section list **after** detachment; tab indexes address
the destination list after detachment. Both reject invalid indexes. Empty groups
are removed. Joining retains the group's active tab, dimensions and collapse state.
- `Activate` selects an already-open tab, without requesting keyboard focus or
uncollapsing it. `Focus` can reopen retained closed state, select its tab,
uncollapse it and request host focus. `Peek` temporarily presents a collapsed
tab, without changing persisted size or collapse. Dismiss is transient too.
- `ResizePair` requires adjacent sections of one dock, conserves their split-axis
extent and changes no cross-axis dimension. `ResetPair` returns the pair to
the ratio of active members' registered defaults within intersected bounds.
`SetSize` is a typed explicit outer-size mutation.
- `Close` retains placement/size memory. `Destroy` removes an already-closed
instance and its retained controllers across workspaces/owners. `NativeClose` redocks the whole section
to its recorded return destination, optionally rejoining a stable former tab
group. Missing/reparented groups use the recorded dock fallback; valid joins
retain target activation. It does not close/cancel the content.
A transaction is prepared on a bounded copy and validated before commit. Rejected
transactions preserve layout, revision, interaction, retained controllers and hosts.
Lifecycle preflight is side-effect-free. It checks explicit Close/Reopen/Reparent/
Destroy events before committing; applying those prepared events is infallible.
State notifications are observational and cannot veto a mutation. Factories stage
fresh controllers without publishing external effects, since staging can be
discarded. Native preflight similarly must establish that commit can finish.
Adapters must reserve/stage fallible work, not discover a failure after commit.
Only explicit content actions may Apply/Finish/Cancel/Stop; hiding, tab changes,
collapse, reparent and native redock never implicitly invoke them. Explicit close
cancels transactional controllers for the affected instance across retained owners;
one cancellation refusal rejects the entire batch.
Close or Destroy combined with any other instance-targeted operation on the same
instance in a batch is rejected with `Lifecycle` before mutations/effects. This
includes Close/Open, Close/Move/Open and Destroy/Open; independent instance and
section mutations can still be batched. Explicit Close cancels a live hidden
transaction even if its saved entry was already marked closed by `Replace`.
`ControllerState` distinguishes requested-open, available, presented, activated
and destroyed. Presented requires usable resolved geometry; activated additionally
requires the selected tab/peek. Keyboard focus is separate in `PanelContext`.
`destroy_owner` performs explicit cleanup without editing layout, leaves a bounded
tombstone, and requires `revive_owner` to create fresh content again. `shutdown`
preflights all owners before clearing any and makes the runtime terminal.
Independent updates attempt every retained controller even when staging or another
controller fails. `update_errors` aggregates at most two bounded typed errors per
controller plus staging/reconciliation errors (258 total). Invalid availability
reports become `Availability` failures. Failing content is unavailable, loses stale
presentation/input ownership and cannot become healthy merely by moving it; a
successful later update restores availability. Reconciliation still runs before
the aggregate failure is returned. Injected-provider refresh failures also do not
skip the independent controller update loop.
## Final product decisions
- Zones are logical Left, Right, Bottom, Floating and Window. Top remains reserved
for ribbon/application chrome. RTL mirrors the physical side; persisted IDs and
tab order remain logical.
- `PinOuter` follows whichever logical side the panel occupies, requires its section
first on that edge and excludes Bottom in registry data. It is inactive in free/
native hosts. Competing pinned **instances**, including in one group, are rejected;
no existing panel is silently displaced.
- Tab groups use the intersection of every member's minimum and maximum **width
and height**. Impossible joins and dimensions outside that intersection fail.
- min/default/max are outer logical dimensions. Geometry reports actual outer and
usable body bounds separately. egui applies scale once. Free/native flow starts
Wide at aspect >= 1, otherwise Tall; Tall switches above 1.1 and Wide below 0.9.
Size classes use the shorter usable edge: Compact < 240, Regular 240..480,
Wide > 480. Invalid/nonfinite/oversized dimensions are rejected.
- Capacity shortages produce transient unpresented/overflow records, never reduced
below-minimum content or saved-dimension/collapse rewrites. Collapsed rails are
chrome. Hosts expose overflow access and retry presentation when capacity returns.
- New Open/Focus/Activate/Peek requests for unavailable content fail with an
availability reason. Saved requested-open content remains dormant and reappears
when its owner/context is available. Missing bindings are dormant too.
- Combined History-in-Browser and History Bodies/Origin stay content preferences
or shared components. They do not merge or depend on panel host identity.
- Opaque surface requests win over Translucent, then zone defaults apply (bottom/
native opaque, side/free translucent). Contrast resolution can raise background
alpha only. If full opacity cannot make authored tokens readable, return
`RetainReadableFallback` with a typed reason and keep the validated fallback/last
good tokens and raw imported intent. No claim of 4.5:1 or text recolouring is
permitted to disguise failure. Theme resolution is implemented by the surface child.
## Geometry and local services
`ResolvedPanel` contains outer/body geometry plus explicit paint and input regions.
Validation bounds regions and requires input inside paint; the viewport outside
these regions belongs to the existing camera/navigation path. Semantic controls
carry stable IDs, roles, accessible names and keyboard-focusability. Hosts may use
`consumes_pointer` to compose input ownership without a full-window shield.
The reference `resolve_geometry` is deterministic synthetic mounting geometry,
not production docking. It reports overflow instead of changing desired state.
`PanelContext` carries presentation geometry, owner/scope identities, flow, size
class, direction, focus and motion; services are a separate argument. Content
has Header/Body/Footer slots and chooses scrolling itself. `EguiPanelHost` uses
one kit Container, title/status/attention and semantic content actions; its action
strip can scroll independently of the body. Reduced motion resolves duration to
zero, without delaying identity/focus/lifecycle changes.
The reference egui adapter accepts exactly one full-outer paint rectangle and one
full-outer Surface input region. It rejects sparse, empty-input or partial-input
records with `Capability` before painting or creating widgets. Rich region-aware
surfaces belong to #11307. Every child clip intersects the existing parent clip.
Keyboard ownership, focus, file/pointer drops, overlays, clipboard and picking use
`PanelLocalServices` with explicit workspace/document/viewport scope. Native viewport
identity uses the native host's stable string in the viewport ID domain; platform
adapters map that identity to their actual viewport handle. Reparenting releases
old host-local focus/overlays/drop routing; the controller survives. Never route
a native service request through the root viewport or a different document.
## Persistence and bounds
Envelope format is `solidcraft.panel-layout`, envelope/layout versions are both 1.
`PANEL_API_VERSION` and each live reply's `api_version` are also 1.
Public schema functions describe actions, replies and envelopes. Serde/schema
values are **untrusted wire data**, not validity proofs. Use `decode_action`,
`decode`, `encode` and the reducer. The engine owns versions; persistence adapters
own atomic storage and migration policy, not a second layout model.
Limits: 64-byte IDs, 128 kinds/layout instances/retained instance identities,
64 sections,
32 tabs per section, 64 mutations per transaction, 262144-byte encoded envelope,
32768 logical units per positive size dimension, finite bounded coordinates.
Opaque JSON is limited to 8192 nodes and depth 32; availability reasons to 256
bytes. Region/control, service payload and retained-owner collections are bounded.
Encoding uses a capped writer, not an unbounded serialization followed by a check.
Runtime retention has separate limits: 32 document owners, 128 other owners,
128 controllers per owner, and 20,480 controllers overall. These limits preserve
the application's supported document count without evicting live drafts.
Unknown panel records and raw future fields are retained in bounded quarantine.
`section_snapshots` stores each raw section once, including future fields, desired
tab order and pending activation; quarantined/retained records refer to its ID.
The bounded `section_order` list ranks **all** saved sections, including dormant
sections and known survivors without snapshots. Restoration uses those ranks, not
insertion indexes clamped into an incomplete list, so instance/quarantine processing
order and staged registry reappearance cannot reorder the saved complete layout.
Known live ordering remains authoritative when edited: surviving visible entries
take their latest relative order while dormant gaps remain; newly added entries
anchor before their next surviving visible neighbour.
A retained snapshot from a fully restored episode is opaque metadata, not stale
layout authority. Before newly unknown members are removed on load, current saved
section semantics refresh its tabs, activation, placement, dimensions, collapse
state and rank. Existing opaque keys absent from typed live data are preserved;
current raw values for the same keys supply the latest saved intent. In an active
partial episode, still-dormant members remain in the complete order. Each snapshot's
optional `projected` section records the last materialized state: changed visible
activation overrides a pending choice, while an unchanged generated fallback does
not replace the desired dormant active member. Newly generated fallback selections
are recorded after quarantine filtering, so they cannot be mistaken for user edits.
The same merge runs before direct restoration after an in-memory live edit.
These v1 fields have serde defaults. Earlier v1 envelopes without `section_order`
derive missing section ranks from sorted snapshot indexes; missing projections
conservatively retain dormant activation until a materialized baseline is recorded.
Both the complete rank list and projected sections obey the existing section/tab/
ID limits, plus the envelope's global byte/node/depth bounds. Known layout starts
independently, and known survivors/extra current tabs remain intact during restores.
`restore_quarantine_with_availability` can defer unavailable entries; invalid bounds
or constraints also leave entries quarantined. Successful restoration preserves
raw instance fields in `retained_data` and shared raw section fields/order in
`section_snapshots`, even across later unregister/register cycles. Adapters consume
these explicitly. Restore stages the whole envelope and applies it only if encoding
fits global byte/node/depth caps; successful decode is guaranteed encodable by this
version. An unrepresentable lossless result returns fallback/recovery, not silent
field loss. Unknown corruption, invalid known layouts or future versions
return a validated preset fallback plus a once-reportable notice and bounded rejected
bytes for recovery. The adapter must preserve unrelated preference keys.
## Executable fixtures
`synthetic_registry`, `fixture_service`, `fixture_open`, `transaction`,
`FakePersistence` and `FIXTURE_LAYOUT_V1` are public engine fixtures. The v1 JSON
lives at `crates/engine/src/panels/fixtures/layout-v1.json`. It is authored contract
data, not a captured production design or a generated schema snapshot.
`PanelMountHarness` combines the actual runtime/action service with synthetic
application-owned content, document-owned transactional editor, workspace-owned multi-instance log/pin
controllers, fake models/command sink/local services/native adapter, fake mount
host and persistence adapter. `FixtureProbe` provides snapshots and bounded draft/
failure controls. `apply_layout` exercises saved-layout/workspace transitions through
the actual sink; `without_content` exercises dormant missing bindings. Fake host mounting invokes all three real controller slots with
an egui context; it is headless and does not establish visual correctness.
```rust
use solidcraft_engine::panels::*;
use solidcraft_ui_egui::panel_runtime::PanelMountHarness;
fn specimen() -> PanelResult<()> {
let mut h = PanelMountHarness::new(false)?;
h.dispatch(vec![fixture_open(
"fixture.editor", "editor", "editor-section", Zone::Left, 0,
)?])?;
h.tick()?; // independent services, even with no host mounted
h.mount(LogicalRect {
origin: Point { x: 0.0, y: 0.0 },
size: Size { width: 1200.0, height: 800.0 },
})?;
h.save()?;
Ok(())
}
```
Engine and UI domain test modules contain hostile action sequences, bounds and
collection limits, exactly-once constraints, pins, atomic failures, incompatible
tabs, overflow restoration, availability, close/reopen, schema/envelope fixtures,
controller retention, hidden service updates, explicit editor actions, native
preflight/redock, scoped input, RTL/reduced motion and document/cache isolation.
+9
View File
@@ -1,5 +1,14 @@
# SolidCraft UI kit
The internal opt-in [universal panel foundation](panel-foundation.md) separates
engine layout/specs from retained UI controllers and host-local services.
`panel_runtime::EguiPanelHost` mounts bounded Header/Body/Footer slots through one
existing `ui_kit::Container`; content controls its own scrolling. This reference
adapter requires a full rectangular paint/input surface, rejects sparse geometry,
and preserves parent clipping. `SolveApp::mount_panels` uses the enabled runtime's
injected services. It adds no default
placement/content change. Production docking and panel migrations remain separate.
`viewport_status_item` and `viewport_status_row` draw persistent viewport pills on
`Surface::ViewportStatus`. Callers supply translated names, formatted settings,
kind, stable identity and key availability, and dispatch returned clear/edit actions.