# Surface

How host observations and ordered requests use the attribute graph without adding a separate reactive runtime.

<a id="ownership"></a>

## One environment object, separate attributes

`Surface` is the application’s host context: activation, viewport, title, location, capabilities, and methods for requesting host changes. It is distinct from a native GPU presentation surface. For application examples and field tables, see [Browser & Native](/docs/browser-native#surface).

An adapter calls `SurfaceDriver::install` before view evaluation. The driver allocates separate `State` attributes for activation, viewport, title, location, and capabilities, plus a request queue. It installs a stable `Rc<Surface>` with `App::set_environment_object`, without introducing a wrapper view. Views retrieve the object through the existing typed environment mechanism.

The driver retains the writable observation handles; `Surface` exposes `Read<T>` handles. Consumers subscribe only to the fields they actually read. Publishing a title cannot by itself invalidate a viewport-only consumer. Capabilities are set at installation; the current driver has no API for changing them later.

<a id="read-handles"></a>

## Read handles reuse graph dependencies

`State::read_only` exposes an existing attribute through `Read<T>`. `Binding<T>` stores the same read-handle representation alongside its write closure, preserves its inherent `get` and `with` methods, and implements `Deref<Target = Read<T>>`. `Binding::read_only` clones the shared reader. There is no public `Readable` trait.

`ViewContext::read` and `with` accept `&Read<T>`, so ordinary bindings and wrapped bindings such as `Rc<Binding<T>>` work through deref coercion. `Read::get` and `Read::with` are inherent methods and can also be called inside `Derived` computations. Their underlying reads participate in the existing dependency capture.

The private reader uses `Rc` and dynamic dispatch, as bindings already did. Creating a read handle from state allocates a reader wrapper; cloning a read handle or obtaining one from a binding only increments an `Rc` count. These operations allocate no graph nodes. State-backed `get` clones the stored value; `with` borrows it. Mapped readers compute a projection, and their source is another read handle, so they do not retain the source binding’s write closure.

<a id="observations"></a>

## Publish observations before preparation

Adapters sample host state on the UI thread and call `publish_active`, `publish_viewport`, `publish_title`, or `publish_location` before preparing affected views. Publications use `set_if_changed`, so equal observations do not invalidate readers. Viewport publication rejects non-finite or negative dimensions and non-finite or non-positive scale factors.

`publish_active` updates `Surface.is_active` independently of element focus. Deactivation retains the logical focus selection and hides built-in indicators. This observation is separate from the internal lifecycle flag checked by host requests; an inactive window is still an open surface.

A new viewport starts as `None`. Content-sized browser mounts publish no constrained height; fill mounts and native windows publish `Some(height)`. Breakpoint computations can use `Derived::distinct` to suppress downstream work while measurements change within the same size class.

Observation is separate from intent: publishing an incoming title or URL never enqueues a matching outgoing command. Applications should preserve that separation when reacting to location changes, so browser traversal or native incoming links do not produce navigation loops.

<a id="requests"></a>

## Admit ordered host requests

`Surface::set_title` and `navigate` check the active flag, capabilities, and a capacity of 128 queued requests. Admission failures return `Closed`, `Unsupported`, or `Full` immediately. Each admitted request allocates a `State<RequestStatus>` initialized to `Pending`; the caller receives a read-only status handle, while the queued `SurfaceRequest` retains the writable handle and command.

The queue is an ordinary `State<Vec<SurfaceRequest>>`. A dedicated `Observer` subscribes to it, and writes use the existing graph waker to schedule host work. `take_requests` checks that observer’s dirty state, drains the queue, and marks it clean. It does not depend on a view subscribing to the queue or on a nonempty patch batch.

Commands execute in admission order. Relative navigation references resolve at execution time against the location produced by preceding successful commands. The adapter publishes the resulting observation and calls `SurfaceRequest::complete` with success or an error. Completion changes a pending status to `Applied` or `Failed(error)` and ignores repeated completion attempts.

| Phase | Responsibility |
| --- | --- |
| Observe | Sample host state and publish changed attributes before view preparation. |
| Mutate | Actions, queued host updates, and incoming messages can update state or admit requests. |
| Prepare / apply / commit | Evaluate affected views, apply semantic patches, accept dependencies, and run committed effects. |
| Execute requests | Drain host commands after the commit opportunity, including turns with no prepared view update. |
| Publish completion | Update observations and request statuses; dependent views can run in a subsequent turn. |

> The queue does not make arbitrary writes during view evaluation transactional. Enqueue from actions or committed effects. A discarded candidate never starts its staged effects, so requests placed inside effect setup are not issued for that candidate.

<a id="browser"></a>

## Browser sampling and document ownership

`SurfaceObserver` watches the host content box with `ResizeObserver`, document-head changes with `MutationObserver`, and window focus/blur, resize, history traversal, hash, and Refract location events. A resolution media query tracks device pixel ratio changes and is rearmed after the ratio changes. Callbacks record measurements or mark the surface dirty and schedule the mount; graph publication occurs during the normal flush.

Sampling batches viewport, document title, and location publications. The first size sample falls back to client dimensions minus padding until a resize observation is available. A `DocumentLease` allows one controlling mount per document within the adapter instance. Observing mounts retain all read capabilities while their title and navigation request flags remain disabled.

Title commands update `document.title` and publish the observed result. Navigation uses `pushState` or `replaceState`, then reads and publishes the actual URL. Replace preserves the existing browser history state; push uses a null state. Browser exceptions become `SurfaceError::Host`, and URL resolution failures become `InvalidUrl`.

Refract dispatches a `refract-location` event after its own history writes so observing mounts can resample. External history writes require `Mount::refresh_location()` because push and replace do not emit `popstate`. Relative URLs resolve against the application location, not an HTML base element.

<a id="native"></a>

## Native window metadata and memory history

`NativeSurface` owns a driver and `MemoryHistory`. It starts from `NativeOptions::title` and `initial_url`, with title and navigation capabilities enabled. Before preparation it samples Winit window activation, inner size, and scale factor, converting physical dimensions to logical pixels. Title commands call the window’s title setter and publish the adapter-maintained value.

`MemoryHistory` stores URL entries and a cursor. Push truncates forward entries before appending; replace updates the current entry. Equal URLs remain distinct history entries even though publishing an equal location does not invalidate graph readers. Traversal outside the stored range leaves history unchanged.

`NativeHandle::feed_location` and `go` enqueue UI-thread work through the existing scheduler. They update memory history and publish location without creating an outgoing Surface request. The history is application state for the current process, not an operating-system deep-link registration or persistent navigation service.

<a id="disposal"></a>

## Close before disposing the runtime

Adapters call `SurfaceDriver::close` while the runtime is still available. It closes the request lifecycle and fails queued requests with `Closed`; retained surface handles reject further requests. If a custom adapter has already taken requests out of the queue, it must complete those requests itself.

Dropping the driver also marks the surface inactive, but cannot update request statuses without a runtime. Custom hosts should explicitly close it before disposal. Browser teardown disconnects observers, removes listeners, and releases document ownership; native teardown closes the driver before disposing the app.

<a id="source"></a>

## Implementation and verification

The feature uses existing state, observers, derived values, environment objects, and wakeups. It adds no new graph propagation primitive. Custom adapters should install one driver per app, publish host observations, execute and complete requests after committing view work, and close the driver before disposal.

`TestHost::install_surface` opts a test into a deterministic surface and memory history. `set_viewport` and `go` feed observations, and flushing settles request-driven updates. Core integration tests cover isolated subscriptions, equal samples, ordered requests, failures, disposal, and discarded effects; native tests and browser fixtures cover adapter behavior.

| Concern | Source |
| --- | --- |
| Read-only handles and bindings | `crates/graph/src/state.rs` |
| Public API, driver, queue, and history | `crates/core/src/runtime/surface.rs` |
| Browser observations and commands | `crates/web/src/surface.rs` and `crates/web/src/dom.rs` |
| Native observations, commands, and scheduling | `crates/native/src/surface.rs`, `app.rs`, and `scheduler.rs` |
| Deterministic surface checks | `crates/test/tests/surface.rs` |
| Browser surface checks | `crates/web/tests/browser/surface_fixture.rs` and `surface.html` |
| Responsive sidebar and URL integration | `examples/chat/src/model.rs` and `examples/chat/src/surface.rs` |
