Building a Provider UI on AFUI
The README covers what AFUI hands you. This covers the decisions you make while building on it, roughly in the order you meet them:
- whether the thing you have is a session at all, and what its shape decides;
- the live runtime between your process and its page, and the operations you expose over it and over HTTP;
- view sessions, delivery, the session registry, and ending a session;
- what a frontend override may do, the errors AFUI reports, and the page you write: what it stands on, may load, is written in, and must survive;
- how a host embeds your surface, and how to test it.
Is it a session?
A UI that fails any one of these tests is not a session, and forcing it into one produces something that looks alive and answers nobody.
- There is a web UI. Either you serve it, or you point at one that already exists somewhere else.
- The ending has a name. A session that waits for a decision ends when the person submits something; a session someone just watches ends when they close it. There is no third kind that stays open forever.
- A process’s lifetime bounds it. Whoever created the session owns it: when that process exits, the session ends and its credential is revoked. Nothing outlives its owner.
A notification with no UI fails the first. A page that keeps serving after the command that made it has exited fails the third — that is not a session, it is a server you forgot about.
What a session’s shape decides
A session that waits for a decision returns a typed value: Outcome<T> where
Completed(T) is the person’s answer. A session someone watches has T = ()
and never completes — it ends Closed.
That difference is not cosmetic. It decides the terminal outcome, but it does not give a Provider a second remote-lifetime policy:
- A window bounds itself. The person can see it; leaving it open all
afternoon is still using it. Window delivery never expires, and
Outcome::Expiredcannot occur. - An AFUI-owned remote page has no physical bound. Direct
linkdelivery andafui host servetherefore share AFUI’s attention heartbeat, warning, grace period, and global configuration. A Provider supplies no timeout. - A registered session is not a remote page. Its owner process bounds it; each later AFUI view applies the remote policy without expiring the session underneath.
Getting this backwards is the common failure: putting a timeout on the session itself kills work a person may still be using through another view, while putting separate clocks on direct and shared pages gives the same AFUI URL two different promises.
Say so when a T = () session still waits on a person
afui host list reports waits_for_decision for every entry, so a person
or an agent looking at the list can tell a stopped agent from an open monitor
before assuming nothing is blocked. It is true automatically for any session
whose T is not () — handing a value back is, by definition, waiting on
whoever supplies it. It has no way to see the other shape on its own: a
session with T = () that a person is nonetheless expected to act on — several
unrelated items settled one at a time, say, with nothing ever handed back.
Call UiSession::awaiting_person on that session to say so.
The rule this implies: a session that does not wait for anyone should use
T = (). Reaching for a unit struct instead of () just to look distinct
gets automatically counted as waiting — harmlessly, since that direction is
always safe, but not what you meant.
The live runtime is orthogonal to the terminal outcome
Some interfaces are not one request followed by one answer. A surface may show
live measurements while accepting inspection commands, or receive progress
while a person refines work in progress. That still has one bounded session
lifetime and one terminal Outcome<T>; intermediate traffic uses
UiSessionRuntime.
Attach it with UiSession::with_runtime (or with_runtime_options for limits,
the gate, compression and a bytes policy). The returned runtime is the Provider
side; the trusted page calls afui.connect(). AFUI owns the only transport
protocol between them, afui-session-v2: one binary WebSocket carrying
Protobuf frames, the ordered path, request identity, reconnect and replay,
bounds, keepalive and shutdown. Provider payloads are JSON by default and
contain none of those fields. Every method that sends or receives a payload
has a _raw twin working on UiPayload::Json or UiPayload::Binary; the page
sends a Uint8Array as binary and receives binary as a Uint8Array.
Values, messages and requests
Each kind of traffic is for one shape of data:
| Kind | What it is | Provider side | Page side |
|---|---|---|---|
| value | the current value of a key; only the newest matters | publish_value(audience, key, &v), clear_value(audience, key) | onValue(key, value, {version}) for shared values, runtime.watch(key, handler) for watched values; value is undefined once cleared |
| message | something that happened once; every one must arrive, in order | send_message(audience, &m) | onMessage(m), runtime.sendMessage(m) |
| request | a question with one answer, progress and cancellation | recv() yields UiIncoming::Request; request(viewer_id, &p, timeout) asks a viewer | runtime.request(p, {onProgress, signal}), onRequest(p, {requestId, signal, progress}) |
A page also sends values of its own, runtime.setValue(key, v): a viewport
size, a pointer position, a scroll offset. They are coalesced locally, only the
newest per key is kept, and the Provider reads them with
subscribe_viewer_values() (UiViewerValue, UiViewerValues). setValue
with null clears the key. It throws an error with a code:
ui_value_key_invalid for an empty key, ui_limit_exceeded for a value over
max_viewer_value_bytes or a new key beyond max_viewer_value_keys, and
ui_runtime_closed once the runtime is closed.
UiAudience says who receives a value or message: All, Watching(key)
(every viewer whose watch set holds the key) or Viewer(id).
Values live in two separate namespaces, and the audience picks which one:
| Namespace | Audience | Provider side | Page side | Native client |
|---|---|---|---|---|
| shared values | All or Viewer(id) | publish_value(UiAudience::All, key, &v) | onValue(key, value, {version}) | UiRuntimeClient::subscribe_values() |
| watched values | Watching(key) | publish_value(UiAudience::Watching(key.into()), key, &v) | runtime.watch(key, handler) and runtime.rows | UiRuntimeClient::subscribe_watched_values(), watch_key, RowsStore |
The same key string may hold a shared value and a watched value at once; they
never touch. A watched "state" (a directory or a terminal session literally
named state, say) does not collide with the shared "state", so a Provider
can use its own data as watch keys without reserving or escaping any name.
Versions are kept per namespace and key. Within the shared namespace a key
keeps one audience for the session’s life: publishing a key to Viewer after
All, or the other way round, is refused with ui_key_audience. A watched
value is published under the key it is watched by; Watching(a) with key b
is refused with the same code.
Which kind carries what
| What | Carried as |
|---|---|
| a click, a keypress, a submission, anything that happened once and needs an answer | request |
| something that happened once and needs none | message |
| viewport size, pointer position, scroll position, hovered item | viewer value (setValue) |
| which things I am showing | watch |
| the current value of a shown thing, or it changed | value with audience Watching |
| a session-wide fact unrelated to what is shown | value with audience All |
There is no ordering between a request and a viewer value. A flow that needs press, move, release strictly in order is not supported by values; send those as messages.
Current value: replace, never queue
Use publish_value(UiAudience::All, "state", &state) for the complete value a
newly connected page should see: a shared value, which the page reads with
onValue. AFUI retains exactly the newest value per key, assigns its version
and sends it before the connection becomes live. Publishing
never waits for a viewer, so a timer continues running when the page is
unopened or temporarily disconnected. A reconnect needs no Provider-owned
resumed flag and no overflow fallback.
These properties decide how a page has to be written:
- Republishing an equal value still reaches the page. Nothing compares one value to the last; the version advances and the frame is sent. A Provider whose page only needs to know that something changed may publish one unit-like value as an invalidation and let the page pull what it needs.
- Only the newest publication is guaranteed to arrive. A value carrying a delta — “three rows were appended” — is therefore wrong, and wrong only under load. Publish what is true, not what changed.
- An opening value is optional. A key nobody published sends nothing and
the page still becomes live. If your first screen is rendered by the server,
liveis your only opening signal. - A watched key nobody watches retains nothing; a viewer that starts watching a key with a retained watched value receives it at once.
Choosing value keys
A key is the unit of replacement: any change to it sends the whole value to everyone it reaches. The cost of a Provider is therefore decided by where its keys are drawn, not by the protocol.
- One rate, one set of consumers per key. Data that changes at the same rate and is read by the same viewers shares a key. A small fast-changing fact and a large slow-changing document go in separate keys, so the fast one does not resend the large one, and a consumer that needs only one subscribes to only one.
- Facts, not clock readings. A raw timestamp or counter that advances on its
own makes the value differ on every publish. Put the fact derived from it in
the state, such as
"working"or"idle", and publish when that fact changes. Where the page needs the elapsed time itself, publish the start time once and let the page count. - A publish follows its own inputs. Publish a key when the inputs that determine that value change, not as a side effect of an unrelated event that happens to touch the same object. The runtime does not compare values, so a Provider that recomputes a value should publish only when the result changed. Recomputing and sending a large value on every terminal line or every tick is the usual way a quiet Provider ends up using a core.
- Read the counters.
UiSessionRuntime::value_stats()returns, per key name, aUiValueStatswithpublished(publishes made) andbytes(their total payload size). A key with many publishes or many bytes is the one to split or slow down. A test can hold the runtime, drive the Provider, and assertruntime.value_stats().get("state").map_or(0, |stats| stats.published)equals the number of changes it expects, so a key drawn too coarsely fails before it ships.
Watching: what each viewer is showing
When a screen shows only part of your data — the expanded folders of a tree,
the selected one of several panels — send each viewer the values it shows and
no others. A page declares its keys with runtime.watch(key, handler), which
returns a function withdrawing that registration; the kernel merges every
registration into one set and sends it, replacing the connection’s whole
previous set.
Publish what each viewer shows with
publish_value(UiAudience::Watching(key.into()), key, &v): a watched value,
which reaches only the runtime.watch handlers for that key (natively,
subscribe_watched_values()), never onValue.
- A key is an opaque string your contract defines. The empty string is allowed.
- At most 1024 keys per viewer, each at most 4096 bytes. Beyond that the frame
is refused with
ui_limit_exceeded; the connection and the previous set stay. - You see the union of every viewer’s set, never who is watching:
subscribe_watched()yields it. Publish a key’s value once when it enters the union, and again every time its content changes. - The page remembers the last version handled per key; after a reconnect an unchanged key arrives with the same version, so nothing is fetched twice.
Viewers and instances
subscribe_viewers() yields every current viewer by identity, with whether it
is the host surface, whether it reached the session remotely, and the viewer
value it put in its hello (handlers.hello in the page kernel,
UiRuntimeClient::connect_with_hello natively), which AFUI does not
interpret. A page keeps its identity in its tab’s storage, so a reload is the same viewer; each connect call additionally
generates an instance id, so a reloaded page is told apart from a reconnect
of the same page. One viewer holds one connection: a newer connection replaces
the older, which is told closed with reason ui_viewer_replaced and does not
reconnect. All viewers of a session are one trust domain: a Provider that must
keep two people’s data apart needs two sessions.
A viewer without a connection stays listed for a grace period
(DEFAULT_UI_VIEWER_GRACE, 30 seconds, changed with set_viewer_grace); the
Provider sees it leave only when that runs out. A reconnect within it is
invisible. When a viewer comes back as a new instance, the Provider receives
UiIncoming::ViewerRestarted and the page onRestart(): it starts from
nothing. A native client whose route to the session changes, such as a new
local proxy in front of it, calls UiRuntimeClient::retarget(url): it reconnects
there as the same instance and keeps its place, so the endpoint resends only what
the client has not seen.
Starting a viewer: the gate
A viewer that joins must receive the full state and then every change after it,
with nothing lost between the two. Create the runtime with
UiRuntimeOptions { gated: true, .. }. While the gate is on, messages and
values addressed to a viewer are held until the Provider calls
start_viewer(id, &full). The rule: between preparing the full state and
handing it to start_viewer, no other send for that viewer may be interleaved.
Prepare and hand over under one lock or inside one task, and the gate opens
for exactly the changes that follow what you handed over.
Nothing is ordered across kinds
Values and messages are separate channels on one socket, and AFUI orders none of them against the others: a request’s result may arrive before or after a value that the same work changed. Messages and request frames share one ordered path, so among those order holds. Data that depends on each other belongs together: in one value, or in the reply, never half in each.
The working shapes for the page did something, and now what it shows is different:
- The value carries the data. The reply says only that the work finished, or why it did not — enough to stop the spinner.
- The value says only that something changed. The data arrives in the reply, or in a request the page makes when it sees the value.
Pick one channel for the data, let the other only say when, and make the refresh idempotent so that a later one simply wins.
Requests: one typed handle
recv yields UiIncoming: Request(UiRequest), Message(UiViewerMessage)
and ViewerRestarted. Read a request with request.payload::<Action>()
(a decoding failure is an error you may fail with, for example
ui_action_invalid) and answer only through the handle:
progress(&p)sends a non-terminal update;finish(&r)completes successfully;fail(UiRequestError)completes with a caller-safe code, message, optional hint and retryability;cancelled()lets long work stop when the page cancels it or the session ends;viewer_id()names who asked.
The page’s runtime.request(payload, {onProgress, signal}) returns one
promise. AFUI assigns the request id, resends an unacknowledged request after a
wire drop and does not hand an answered one to the Provider twice. Never add
request_id, reconnect tokens or acknowledgements to your payloads.
A Provider asks a viewer with request(viewer_id, &payload, timeout), which
returns a UiViewerRequest: recv_progress() yields progress, result().await
is the single answer, cancel() withdraws it. The page answers by returning
from handlers.onRequest(payload, {requestId, signal, progress}), or by
throwing, whose code property becomes the error code; a native client reads
ClientEvent::Request from subscribe_events() and answers with
progress_request and finish_request.
Failures: ui_request_unhandled (no onRequest), ui_request_timeout,
ui_request_cancelled, ui_viewer_unknown, ui_viewer_left (the grace period
ran out), ui_requests_full (retryable: too many open) and
ui_runtime_closed.
Bytes
Bytes that do not belong in JSON — an image, a file, a long log — are offered,
not embedded. Declare a UiBytesPolicy (maximum size, admitted media types; by
default nothing is admitted) in UiRuntimeOptions::bytes_policy.
offer_bytes and offer_file return a UiBytesOffer; dropping it, or calling
revoke_on_release() and letting the page release it, withdraws the
reference. A Provider that keeps offers in a table learns when one is no
longer readable from offer.is_revoked() or offer.revoked().await, and
drops it then; there is no need to cap the table. Put offer.reference() (a
UiBytesRef) in a reply. The page reads
it with runtime.read(ref, {signal}) or runtime.readRange(ref, offset, length, {signal}),
uses runtime.bytesUrl(ref) for an <img> (the page policy needs
allow_images() or allow_media()), and calls runtime.release(ref) when done.
The options are optional. An abort rejects with ui_request_cancelled even
while the byte connection is opening. Aborting an outstanding read also
cancels it on that connection. Closing the runtime terminates an in-progress
byte handshake and rejects waiting reads with ui_runtime_closed.
A zero-byte chunk marks EOF only when its end flag is set. A read that
encounters a zero-byte chunk before EOF fails with ui_bytes_source_gone.
A page offers bytes to the Provider the same way with
runtime.offerBytes(source, {mediaType, revokeOnRelease}): mediaType
defaults to the blob’s own type, revoke() withdraws the offer, and
revokeOnRelease is the page’s revoke_on_release() — the
offer goes when the Provider releases it, and without it a release leaves the
offer readable. The Provider reads them with read_bytes and release_bytes.
Either side serves at most max_concurrent_reads of the other’s reads at once;
one more, or a read id already in progress, fails with ui_limit_exceeded,
and a cancelled read frees its slot at once and is not answered.
A release is never answered and returns nothing; once the page’s runtime or
the native client is closed it does nothing. How surely it arrives depends on
the side that sends it. A viewer (the page’s runtime.release, a native client’s
release) delivers it reliably: the call returns at once and the release
goes out in the background, over a bytes connection opened for it when none
is open, so an offer made with revoke_on_release() does not outlive its
reader. The Provider’s release_bytes is delivered only when that viewer
already has a bytes connection open, and is dropped otherwise, because a
Provider is the serving end and cannot open one; a page offer is still
withdrawn by the page’s revoke() or when the session ends.
A read of a
reference that was never offered or has been revoked fails with
ui_bytes_not_found; one whose offering viewer instance is gone fails with
ui_bytes_source_gone. Bytes travel on a separate connection (up to four per
viewer) so a large transfer never delays a request, and a reader resumes
after a drop.
Limits
The baseline every session guarantees, which a session may raise and never
lower (UiRuntimeOptions::limits, validated at creation):
| Limit | Baseline |
|---|---|
| one WebSocket message | 1 MiB |
| watched keys per viewer; bytes per key | 1024; 4096 |
| viewer values per viewer; bytes per value | 16; 4096 |
| open requests per direction | 32 |
| ordered-path backlog per direction | 128 frames |
| bytes connections per viewer | 4 |
| concurrent reads; bytes per read | 16; 256 KiB |
| keepalive interval; deadline | 15 s; 45 s |
| local coalescing | 16 ms |
| grace period | 30 s |
A full backlog or request table produces a caller-safe, retryable
ui_backlog_full or ui_requests_full instead of blocking the transport.
Build the page policy with allow_runtime(); why a page without it is
refused at mount is under What your page may load.
Compression
The runtime socket negotiates permessage-deflate with context takeover, which
costs a few tens of KiB of memory per connection and lets an attacker who can
inject chosen text next to a secret in the same stream learn the secret by
observing compressed sizes (the CRIME/BREACH family). Do not put a secret and
attacker-influenced text in one session’s traffic, or switch compression off
with UiRuntimeOptions { compress: false, .. }. The control connection never
compresses.
Operations: one table, dispatched by name
A viewer calls a Provider operation with an ordinary runtime request such as
{"operation":"echo_text","input":{"text":"hello"}}. The input is a JSON
object. A successful reply is the handler’s JSON return value. Failures use
UiRequestError. AFUI supplies three operation error codes.
operation_unknowngives the same answer for unregistered operations and operations the session did not expose.operation_input_invalidmeans the request has the wrong shape or the input failed to decode. Unknown input fields are ignored.operation_output_invalidmeans a handler ran and its return value could not be encoded as JSON. The error message includes the operation name and encoding error, the hint is empty, and the error is non-retryable because the handler may already have had side effects.
Use register(name, about, handler) to add typed handlers to a table. Give
each operation a nonempty English sentence for about. The OpenAPI document
uses it as the operation summary. Derive JsonSchema for custom input and
output types. Inputs also implement DeserializeOwned, and outputs implement
Serialize. Dispatch uses the existing input decoder.
Use expose to select the operations available in a session. Call handle
as requests arrive in the
Provider’s receive loop. It invokes handlers synchronously in arrival order.
Put work that needs to wait in Pending and drive those futures separately
so the receive loop can keep handling requests. The Provider calls send
when it is ready to answer.
Use register_session for an interaction that needs a session. It supplies a
progress handle for reporting progress and observing cancellation. Only a
session that exposes the operation can dispatch it. HTTP neither routes nor
advertises it. Keep continuous streams and attachment management on their
own routes when they have different lifetimes or authorization rules.
A viewer that sends "caller": "program" in its hello is treated as a program.
All other viewers are treated as people. This field is self-reported and
provides no authentication.
use agent_first_ui::operations::{UiOperationReply, UiOperationStep, UiOperations};
use agent_first_ui::{Result, UiIncoming, UiSessionRuntime};
use schemars::JsonSchema;
use serde::Deserialize;
#[derive(Deserialize, JsonSchema)]
struct EchoInput {
text: String,
}
async fn run_inspector(runtime: &UiSessionRuntime) -> Result<()> {
let mut operations = UiOperations::new();
operations.register("echo_text", "Echo the supplied text.", |_: &(), _, input: EchoInput| {
UiOperationReply::Ready(Ok(input.text))
})?;
let exposed = operations.expose(&["echo_text"])?;
let viewers = runtime.subscribe_viewers();
let mut pending = tokio::task::JoinSet::new();
loop {
tokio::select! {
incoming = runtime.recv() => {
match incoming? {
Some(UiIncoming::Request(request)) => {
let roster = viewers.borrow().clone();
match exposed.handle(&(), runtime, &roster, request) {
UiOperationStep::Done(answer) => answer.send()?,
UiOperationStep::Pending(answer) => {
pending.spawn(answer);
}
}
}
Some(_) => {}
None => return Ok(()),
}
}
completed = pending.join_next(), if !pending.is_empty() => {
if let Some(Ok(answer)) = completed {
answer.send()?;
}
}
}
}
}
Session content contracts
Register payload types on the operation table with
register_session_content::<T>(channel, name). Use ProviderValue for
retained values, ProviderMessage for messages sent to viewers, ViewerValue
for values set by viewers, and ViewerRequest for requests sent to viewers.
Use the runtime key or message name. For a dynamic key, describe the variable
part with a placeholder such as row/{id}.
Serve session_document() from the exposed operation table on a
session-relative route and put that route in the declaration’s schemas map.
The catalog contains the exposed operations and the registered content, with
local references to shared type definitions. HTTP discovery includes the HTTP
operations and has no routes for the registered session content. Registration
describes the contract. The Provider still publishes values, decodes incoming
payloads, and applies its own domain validation.
Idempotency keys
Use register_idempotent for a mutation that requires a domain idempotency
key. HTTP clients send Idempotency-Key. A page sends idempotency_key
alongside operation and input in its runtime request. Rust clients can use
call_operation_with_key. Both carriers deliver the key to the handler as
UiCaller.idempotency_key.
Reuse the same key when retrying the same mutation across carriers. AFUI’s session request deduplication covers transport replay within one session.
Operations that return a file
Use register_file to hand an open file and its media type to AFUI. The
Provider must make all path, exclusion, and symlink decisions before opening
the file. A session request returns a byte reference. The runtime keeps it
available until the page calls release or the session ends. The session’s
byte policy controls the allowed media types and sizes.
HTTP returns the file as a streamed attachment. A single Range selects a
byte interval and returns 206. The HTTP carrier serves files independently of
the session’s byte policy.
use std::fs::File;
use std::path::PathBuf;
use agent_first_ui::{Result, UiFileResult, UiRequestError};
use agent_first_ui::operations::{UiOperationReply, UiOperations};
use schemars::JsonSchema;
use serde::Deserialize;
#[derive(Deserialize, JsonSchema)]
struct DownloadInput {}
fn operations() -> Result<UiOperations<PathBuf>> {
let mut table = UiOperations::new();
// State contains the trusted path of the only file this operation serves.
table.register_file("download_report", "Download the report.", |path: &PathBuf, _, _: DownloadInput| {
UiOperationReply::Ready(
File::open(path)
.map(|file| UiFileResult { file, media_type: "application/pdf".into() })
.map_err(|_| UiRequestError::new("report_unavailable", "the report could not be opened"))
)
})?;
Ok(table)
}
Operations over HTTP
Enable the api feature to serve operations on an Axum router. Registration
alone does not expose any HTTP endpoints. The Provider selects an exposed
table and constructs the carrier with
UiApi::new(openapi, operations, state, access_token_secret). Use
expose_all() to offer the full table or expose() to offer a subset.
The api feature works without session.
Set UiApiInfo to the contract title, version, and description. Use the
session declaration’s contract version when the same operations are available
over a session. operations.openapi(&info) generates a deterministic OpenAPI
3.2 document for the exposed subset. It describes the two public discovery
routes and the registered operation routes. The router serves the supplied
document as raw JSON on GET /openapi.json.
| Route | Authentication | Response |
|---|---|---|
GET /health | Public | 200, with {"status":"ok"} as the result |
GET /openapi.json | Public | 200, with the OpenAPI document as the JSON body |
POST /operations/{name} | Bearer | The operation result or error |
Routes passed to protected_routes | Bearer | The Provider’s response |
| Unmatched path | Public | 404, api_route_not_found |
| Unsupported method on a matched path | Same as the path | 405, api_method_not_allowed |
Send the operation input directly as a JSON object. An empty body supplies
{}. The default body limit is 1 MiB, configurable with max_body_bytes.
Invalid JSON or input returns operation_input_invalid. A body over the limit
returns 413 with api_request_too_large.
Send the credential as Authorization: Bearer <credential>. An absent or
invalid credential returns 401 with authentication_required and
WWW-Authenticate: Bearer. Query parameters cannot authenticate a request,
and an authenticated request that also carries a credential-like query key
(token, authorization, api_key, or a name ending in _token or
_secret) is refused with 400 credential_location_invalid.
An empty configured credential denies all protected requests. Authorization
precedes operation lookup. The caller passed to every HTTP handler has kind
Program and id http.
AFUI returns an AFDATA result envelope on success and an error envelope on
failure. Both carry trace.duration_ms. An error includes code, message,
retryable, and optional hint, details and retry_after_ms
(UiRequestError::with_details, with_retry_after_ms). AFUI redacts its envelopes before
serializing them. Providers own serialization and redaction on their custom
routes. The router adds Cache-Control: no-store and
X-Content-Type-Options: nosniff to responses and sends no CORS headers.
UiRequestErrorClass | HTTP status |
|---|---|
Invalid | 400 |
Denied | 403 |
NotFound | 404 |
Conflict | 409 |
TooLarge | 413 |
Unprocessable | 422 |
Internal | 500 |
Unsupported | 501 |
Unavailable | 503 |
Use UiRequestError::class to classify a handler error. Errors with no explicit
class return 500. AFUI classifies operation_unknown as NotFound,
operation_input_invalid as Invalid, and operation_output_invalid as
Internal. The error class stays in process and does not travel over sessions.
use std::sync::Arc;
use agent_first_ui::{
UiApiInfo,
api::UiApi,
operations::{UiOperationReply, UiOperations},
};
use schemars::JsonSchema;
use serde::Deserialize;
#[derive(Deserialize, JsonSchema)]
struct EchoInput {
text: String,
}
async fn serve_inspector(access_token_secret: String) -> Result<(), Box<dyn std::error::Error>> {
let mut operations = UiOperations::new();
operations.register("echo_text", "Echo the supplied text.", |_: &(), _, input: EchoInput| {
UiOperationReply::Ready(Ok(input.text))
})?;
let info = UiApiInfo {
title: "Inspector".into(),
version: "1".into(),
description: "Inspect recorded values.".into(),
};
let exposed = operations.expose_all();
let openapi = exposed.openapi(&info);
let router = UiApi::new(openapi, exposed, Arc::new(()), access_token_secret).router();
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
axum::serve(listener, router).await?;
Ok(())
}
The api command group
Import api_commands(default_port) from agent_first_ui::api and add each
returned command to your CliSpec. Run them from the program’s own
CliMain entry: run_api_serve and run_api_export take the emitter the entry
hands to its executor and return Result<u8, CliStop>. run_api_serve builds
the Provider router with the supplied URL and bearer credential;
run_api_export takes the finalized OpenAPI document. If the Provider adds
protected routes, add their descriptions to paths and any schemas they
reference to components.schemas before handing the document to the carrier
and exporter. Supply the same document value to UiApi::new and
run_api_export.
| Command | Argument | Behavior |
|---|---|---|
api serve | --port <PORT> | Uses the Provider’s default port. Pass 0 to let the operating system choose. |
api serve | --listen <IP> | Defaults to 127.0.0.1. |
api serve | --advertise <HOST[:PORT]> | Publishes this host with the bound port or an explicit override. The default is the listen address. With 0.0.0.0 it is the machine’s LAN IPv4 address. |
api serve | --access-token-secret <SOURCE> | Required. Accepts an AFDATA literal, environment, or file source. |
api export | --directory <PATH> | Defaults to openapi. |
api export | --force | Allows replacement of a file at the destination. |
The resolved bearer credential must be 32 to 512 ASCII characters from
A–Z, a–z, 0–9, or -._~+/=. An absent, unreadable, or invalid
credential produces api_access_token_invalid. Error and readiness events
keep the credential private.
After binding and successfully building the router, api serve emits an
AFDATA progress event. Its payload contains phase set to api_ready,
message, api_url, openapi_url, listen, and the actual bound
port. The envelope includes trace.duration_ms. The command handles
SIGINT and SIGTERM, drains active requests, and returns to the Provider for
cleanup. Both commands use the resolved AFDATA output format and destination.
api export creates the destination directory and writes indented JSON with
a trailing newline to <directory>/openapi.json. It installs the completed
file from a temporary file in the same directory. An existing destination
requires --force. A symbolic link at the destination always causes
openapi_export_failed. The result includes openapi_path. Commit the
exported openapi.json to your repository and have the Provider’s fixed test
script regenerate and compare it against the committed file.
The runnable inspector example wires both actions to one operation table.
use std::{process::ExitCode, sync::Arc};
use agent_first_data::{
CliHandler, CliMain, CliSpec, CliStop, CommandSpec, ProcessEmitter, ResolvedInvocation,
build_afdata_cli, cli_invocation_invalid_event, json_error,
};
use agent_first_ui::{
UiApiInfo,
api::{
API_EXPORT_ACTION, API_SERVE_ACTION, UiApi, api_commands, run_api_export, run_api_serve,
},
operations::{UiExposedOperations, UiOperationReply, UiOperations},
};
use schemars::JsonSchema;
use serde::Deserialize;
#[derive(Deserialize, JsonSchema)]
struct EchoInput {
text: String,
}
fn operations() -> agent_first_ui::Result<UiExposedOperations<()>> {
let mut operations = UiOperations::new();
operations.register(
"echo_text",
"Echo the supplied text.",
|_: &(), _, input: EchoInput| UiOperationReply::Ready(Ok(input.text)),
)?;
Ok(operations.expose_all())
}
fn api_info() -> UiApiInfo {
UiApiInfo {
title: "Inspector".into(),
version: "1".into(),
description: "Inspect recorded values.".into(),
}
}
type Run = fn(&ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>;
fn serve(invocation: &ResolvedInvocation, emitter: &mut ProcessEmitter) -> Result<u8, CliStop> {
run_api_serve(invocation, emitter, |serving| {
let operations = operations().map_err(|error| error.to_string())?;
Ok(UiApi::new(
operations.openapi(&api_info()),
operations,
Arc::new(()),
serving.access_token_secret.clone(),
)
.router())
})
}
fn export(invocation: &ResolvedInvocation, emitter: &mut ProcessEmitter) -> Result<u8, CliStop> {
let operations = operations().map_err(|error| {
let event = json_error("operation_registration_failed", &error.to_string())
.build()
.unwrap_or_else(|error| cli_invocation_invalid_event(&error.to_string()));
CliStop::new(event, 1)
})?;
run_api_export(invocation, emitter, &operations.openapi(&api_info()))
}
fn main() -> ExitCode {
let mut spec = CliSpec::new("inspector", env!("CARGO_PKG_VERSION"))
.about("Inspect recorded values.")
.command(CommandSpec::root());
for command in api_commands(8080) {
spec = spec.command(command);
}
CliMain::new(build_afdata_cli(spec), |_| {
[
(API_SERVE_ACTION, (|_| Ok(serve as Run)) as CliHandler<Run>),
(API_EXPORT_ACTION, |_| Ok(export as Run)),
]
})
.run(std::env::args_os(), |run, invocation, emitter| {
run(invocation, emitter)
})
}
Provider responsibilities
The provider owns canonical state and migrations, authorization, domain validation, concurrency, transactions, audit, and recovery. Operation handlers and CLI commands call the same typed service and persistence code. Take the appropriate shared or exclusive lock at the operation boundary and check for unfinished transactions inside the write lock. Keep long-running listeners outside workspace locks.
Persist idempotency records for non-idempotent local writes across carriers and process restarts. Bind the key to the operation and its normalized input. Replay the original result for the same request and return a conflict if the key is reused with different input. Validate object-specific base hashes before applying edits. Define the meaning of missing, null, and empty values in the input contract, and give each batch item a stable reference.
Use separate operations for saving proposals, queuing effects, recording review feedback, and executing effects. For remote effects, plan locally and return the resolved inputs with a workspace-bound plan ID. Confirm performs the first remote call after validating the exact plan and its current inputs. Changes to the workspace, content, attachments, configuration, queue, or identity invalidate plans that depend on them.
Open human review as a scoped session with the minimum operation set. Its typed terminal outcome records the decision. Domain authorization and the explicit confirmation step still govern execution. Keep lifecycle completion in the session model.
view sessions: messages and actions
A Provider that serves view itself, instead of rendering a template, draws its
UiSession with a view::ViewRenderer where a page Provider gives a router.
What draws a session is the one thing that differs: its context, declaration
(panels, titles, focus keys), subject, delivery, expiry, whether it is waiting on
a person, and runtime limits are the UiSession’s and mean what they mean for a
page. The renderer owns the view parts: it checks every message against the catalog,
keeps the view of each panel for replay, parses what the viewers send back, and
serves the page. The Provider sends messages to a panel and answers what the
viewers do.
A session drawn with view declares the type VIEW_SURFACE_TYPE and nothing else is
fixed: panels and their focus keys are the Provider’s, as for a page, and
ViewRenderer::declaration writes that type for them. Its runtime is attached
with ViewRenderer::runtime_options(), which is gated so a viewer that starts over
is handed its panel’s view whole; raise limits on that value. The renderer serves its
own page, so a session drawn with it is refused under a security policy chosen for
a page, and under a declaration of another type. Focus is the runtime’s:
runtime.subscribe_focus() reads what the host routes to the session, and
runtime.request_panel_focus(panel, values) asks the host to set it.
use std::sync::Arc;
use agent_first_ui::view::{ViewEvent, ViewOptions, ViewRenderer, ViewSession};
use agent_first_ui::{UiDeliveryPlan, UiPanelDeclaration, UiSession};
use serde_json::{Value, json};
# async fn example() -> agent_first_ui::Result<()> {
let session = UiSession::<Value>::new("inspector", "review")?
.with_subject("Review")
.with_declaration(ViewRenderer::declaration(
"review",
vec![UiPanelDeclaration {
id: "review".into(),
title: "Review".into(),
reads_focus: Vec::new(),
requests_focus: Vec::new(),
}],
))?;
let (session, runtime) = session.with_runtime_options(ViewRenderer::runtime_options())?;
let runtime = Arc::new(runtime);
let renderer = ViewRenderer::new(&session, Arc::clone(&runtime), ViewOptions::default())?;
let delivery = UiDeliveryPlan::resolve(None)?
.start(session, renderer.clone())
.await?;
let session = ViewSession::new(renderer, delivery);
session.send("review", &[
json!({"updateComponents":{"components":[
{"id":"root","component":"Button","label":"Done","action":{"event":{"name":"done"}}}]}}),
])?;
while let Some(event) = session.recv().await? {
if let ViewEvent::Action(action) = event {
session.decide(action, json!({"done": true})).await?;
let outcome = session.wait().await?;
# let _ = outcome;
break;
}
}
# Ok(())
# }
Panels. Each panel of the declaration has a view of its own: its component tree
and its data model, apart from every other panel’s. A viewer mounts one panel. It
names it as panel in the hello it connects with (a page takes it from the
?panel= of its address, as page code reads it with afui.panel()), or gets the
declaration’s default_panel when it names none. A connection that names a
panel the declaration does not list is declined before it is listed, under
view_panel_undeclared (see Versions and what a renderer implements).
The runtime does not know panels. The session reads the hello the runtime hands over
unread, and sends each panel’s messages to the viewers that mounted it, each addressed
by its identity. A message names no
view: it goes to the panel send is given.
Versions and what a renderer implements
A session is built with one version of the
catalog, major.minor, and the extensions it uses (none today). That set is what a
renderer has to implement to draw it. It is written once, as requires in the session’s
metadata, which the registry listing carries too, so a host can read it before it
connects. A renderer that draws says what it implements in the viewer payload of its
hello, which the runtime hands over unread: {"implements": {"view": "1.0", "extensions": [{"name": "…", "version": "1.0"}]}, "panel": "…"}; the built-in page
sends exactly that, and the version it sends is the one of the catalog file it was built
with. A connection that does not draw (a host that only answers focus requests, a
command line, a test client) says neither implements nor panel and is not judged; a
payload that draws has to carry implements, and one that names a panel without it is
declined as view_implements_invalid, because mounting a panel is drawing. The session decides before
the connection is listed, and all of it or nothing: a renderer implementing 1.3 draws
every session built with 1.0 to 1.3, a different major version shares nothing, and a
missing extension is a missing piece. A connection that is not satisfied is not in the
viewer list and holds no grace period; it ends with one closed frame under a code of
its own and is not retried:
reason | When |
|---|---|
view_major_unsupported | the major versions differ |
view_minor_unsupported | the major version agrees and the renderer’s minor is lower than the session’s |
view_extension_unsupported | an extension the session uses is missing, or too old |
view_panel_undeclared | the hello names a panel the declaration does not list, or names something that is not a panel’s name |
view_implements_invalid | implements is not a version with a list of extensions, or the hello names a panel without implements |
The frame’s structured detail says what the session required, what the renderer offered
and every item that is lacking: {"requires": {"view": "1.2"}, "offered": {"view": "1.0"}, "missing": [{"kind": "view", "requires": "1.2", "offered": "1.0"}]}; an extension is
{"kind": "extension", "name": "…", "requires": "1.0", "offered": null} and a panel is
{"kind": "panel", "name": "…", "declared": […]}. A page reads it as detail of the
closed state, a native client as ClientError::detail and ConnectionState::Closed { detail }, and says which side has to update from the code and the detail, never from the
frame’s message. The Provider hears it as ViewEvent::ViewerRefused, once for each
refused connection; a script Provider hears {"event":"viewer_refused","viewer_id","code", "message","detail"}. A native host that cannot draw a session reads requires before it
mounts and opens the session’s web page instead, which always draws it.
Sending. Each message of send(panel, &messages) is one ordered runtime message
to the viewers of panel, and a renderer applies it on its own to what it shows.
A view starts empty; updateComponents adds components and updateDataModel
writes a value at a path (the root path replaces the model). updateView sets
the view’s own actions, {"primaryAction": "<Button id>", "actions": ["<id>", ...]},
which the panel shows in its toolbar beside the content tree under root; one
message sets both slots, and a slot it does not name is emptied. AFUI checks every
message against the catalog, and checks the tree each message leaves before sending,
so a view is built with a root and the components it names in the one message. The
tree has a root, every reference lands, nothing circles, and a component is
mounted once: from one place in the content tree or from one action slot, never two.
What a reference may name is checked too, each refusal under its own code and at the
property that breaks it: primaryAction and rowPrimaryAction name a Button
(primary_action_not_button); actions, rowActions and a Menu’s children are
Buttons, Dividers or Menus (action_member_invalid); Item.media is an Image or Icon
and Item.trailing a Badge or Text (item_media_invalid, item_trailing_invalid);
a List holds Items or Sections, and a Section in a List only Items
(list_member_invalid); an Item with a primaryAction and a Table with a
rowPrimaryAction hold no other such target anywhere inside (activatable_nested);
a Form is not inside a Form (form_nested); a component mounted twice is
component_mounted_twice. A focus action may only name keys the panel declares in
requests_focus (focus_key_undeclared). A panel the declaration
does not list is refused as view_panel_undeclared. Every message must fit
the runtime limit, which defaults to 1 MiB. Raise that limit or
the ordered backlog in the limits of the options the session’s runtime is
attached with.
ViewOptions::messages supplies, by panel, the opening state before delivery starts.
Images use asset:<name> URLs backed by ViewOptions::assets (PNG, JPEG, or WebP).
Replacing the whole view. A replacement is a message of the protocol:
{"replace": {"part": 0, "parts": 1, "messages": [...]}}, where messages are the
operations that build the view from an empty one; one with no messages empties it,
which is how a panel’s view is cleared. When it does not fit one message it goes in
parts, numbered from zero, each a message of its own; send takes the parts of a
replacement together, in order, and refuses one that is not whole. A renderer keeps
showing the old view until the last part is in, and then swaps in one step. The
other panels’ views are not touched.
Catching a viewer up. AFUI can replay unacknowledged messages to a reconnecting viewer. When a viewer needs a fresh start, AFUI hands it the current view of its panel as a replacement, in one message when it fits one and in parts when it does not. Individual components and indivisible data values must still fit one message. The renderer keeps showing the old view until the replacement is whole and keeps local UI state. The replacement is the panel’s view with that viewer’s own edits laid over it (What a person types). How it reads the parts, and what every renderer must keep, is the renderer contract. The built-in page and native renderers are checked against it with shared fixtures.
Viewer visibility. runtime.subscribe_viewers() includes each viewer’s reported
visibility. is_actively_visible() requires a connected viewer that reports
Visible. Disconnected viewers and clients that have yet to report visibility
appear as Unknown. Browser pages report document visibility automatically.
Native clients can call UiRuntimeClient::set_visibility. Visibility changes
leave the session’s attention deadline alone.
Receiving. recv() gives the next thing a viewer did, or None once the
session has ended. Each event names its viewer and is answered through its handle:
ViewEvent::Action— a component’s action.payload()is the action as the renderer reported it, which is the whole body of its request (name, source component, time, optional user message, resolved context), andpanel()is the panel the viewer had mounted. What an action is about, such as the row it was triggered on, is named in itscontext. What the person has entered is not:data_model()is the panel’s data model as that viewer has it, with every edit the viewer made before the action laid over what the Provider wrote (What a person types). Useprogress(&ViewActionProgress)andaccept_with(&ViewActionReply)to send progress and a reply to the triggering viewer.reject(UiRequestError)sends a directed failure. An action exposesis_cancelled(),subscribe_cancellation(), andcancelled(). For a session-ending action, usesession.decide(action, outcome)ordecide_with(action, outcome, &reply). The winner claims the outcome before sending its reply and gives the viewer a bounded chance to acknowledge it before the session closes. A competing request can receiveui_session_already_settled.ViewEvent::Edit— a person changed a value in a panel’s view. It carries theviewer_id, thepanel, thepathand thevalue, and nothing is asked of the Provider. Edits of one viewer arrive in the order it made them, and always ahead of the action that follows them. One that the Provider has not yet heard when the next one at the same path arrives is not told twice.ViewEvent::ViewerRefused(UiViewerRefusal)— a connection was declined before it was listed, because its renderer cannot draw the session or the panel it asked for is not declared. It carries theviewer_idthe connection offered, thecodeit was refused under, themessageand the structureddetail. Nothing is asked of the Provider. See Versions and what a renderer implements.ViewEvent::Fault(ViewFault)— a renderer reported a condition of its own.viewer_id,panel,fatal,code,pathandmessagesay who, what the viewer had mounted, whether the viewer can still see the view, what kind, where in the message or replacement it was reading, and what went wrong. Nothing is asked of the Provider. See Faults.
A request a renderer sends that does not follow the view protocol never reaches the
Provider; the page is told view_renderer_message_invalid.
Actions
An action is a request of the session runtime and has that request’s whole life, with
no other message in either direction: it opens when the person triggers a component,
progress() may update it any number of times, and it ends with accept_with (or
accept), with reject, or with a cancellation, which the Provider sees as
is_cancelled() and the person as a failed action. A reject whose
UiRequestError is retryable says the same action may be tried again; either way
the control is ready for the person’s next trigger, and the page never sends an
action again by itself. An action the page cannot send because the road to the
Provider has no room for the edits before it ends as a retryable failure
(ui_backlog_full) without being sent.
Faults
A renderer reports a fault as one ordered message,
{"fault": {"fatal", "code", "path", "message"}}, on the road edits take: the Provider
hears it after every edit the person made before it and before every action the person
takes after it. It is no request and nothing answers it.
A fatal fault is one after which the viewer cannot see the view: the renderer
shows only a notice that the interface could not be displayed, ignores everything the
session sends, and reports nothing more. The codes are VALIDATION_FAILED for content
that is not valid or not recognised, which includes a control, property, value or
function the renderer does not have, and RENDERER_FAILURE for a failure of the
renderer’s own. A fault that is not fatal leaves the view as it is and only tells
the Provider. The web renderer reports EXPRESSION_ERROR for an expression that failed
and LINK_URL_REFUSED for a Link or a link in a Markdown whose address it does not follow,
FOCUS_VALUE_MISSING for a focus action with a value that is missing or null,
MARKDOWN_HEADING_CLAMPED for a heading deeper than the outline goes, TABS_SELECTED_UNKNOWN for a
Tabs.selected that names no tab and FILE_VALUE_INVALID for a FileInput value that is not a list
of entries with names, each once for each
component and expression; the value of a failed expression is missing in its place and the
view is drawn without it. path is a JSON Pointer into the message or replacement
the renderer was reading, counted from its first message, which for these two is the
component’s place, and is empty when the fault concerns no place; no value of the content is in a report. A report that does not
follow the protocol is heard as view_fault_invalid with the path of what was wrong,
and fatal only when it said so legibly. A viewer that is not mounted reports
nothing the Provider hears.
A Provider that does not listen holds every fatal fault and the latest 256 that were not fatal. What a Provider does about a fatal fault, such as the host opening the session’s own page, is the Provider’s or the host’s to decide; the event only says that it happened and how bad it was.
What a person types
What a person enters in a control that is bound to the data model reaches the Provider
by one road, and the protocol guarantees it: when an action arrives, the data model the
Provider is handed (ViewAction::data_model()) already holds every edit that person
made before the action. It is not an option, and nothing a renderer does can leave an
edit out of it: an action that could not honour it is turned away instead.
A renderer reports each edit as an ordered message on the road its actions travel, so
nothing the person does later can overtake it. The session keeps, for each panel, the
view the Provider wrote and, for each viewer, an overlay of that viewer’s edits that the
Provider has not yet written back. The view is shared. The overlay is not: what one
person types is never shown to another, and a viewer that starts over (a reload, a
reconnect that had to restart) is handed the view with its own overlay laid over it.
Whether anything one viewer typed becomes everyone’s is the Provider’s decision, made
by writing it into the view. The viewer’s overlay is dropped when the viewer leaves the
session, and replace empties the panel’s overlays.
The Provider hears each edit as ViewEvent::Edit { viewer_id, panel, path, value }; a
script Provider hears {"event":"edit","viewer_id","panel","path","value"}, and its
action event carries the data_model as well.
What a write of the Provider’s does to edits. The Provider’s writes are numbered, a
replacement counting as one, and the number goes with each updateDataModel and
replace as revision; every edit says which revision it was made after. A write
meets an edit by one rule, which the session and every renderer apply alike:
- a write at the edit’s path, or above it, takes the edit whole;
- a write below the edit’s path takes that part of the edit’s value and leaves the rest, as one edit for each piece the write did not reach (an array is not taken apart: a write inside it takes the whole array);
- a write anywhere else leaves the edit alone.
So a Provider that writes back what a person typed loses nothing, a Provider that
overrides a field is not undone by an edit that was already on its way, and a
write below an object a person replaced does not discard the rest of what they put in
it. The session keeps the last 1024 writes to judge edits made before them; an edit
made before all of those is refused as view_edit_stale.
Edits that cannot be kept. The overlay of one viewer holds at most 1024 edits and
1 MiB. An edit that does not fit it, that cannot be put in the data model, or that is
not made as the protocol says, is refused, and the viewer is told which: a downstream
message {"editsRefused": {"refused": [{"path", "code", "message"}]}} lists every
edit of that viewer that is refused, and the page shows that a change was not kept.
The codes are view_overlay_full, view_edit_invalid and view_edit_stale. While
any edit of a viewer is refused, the session answers its actions with
view_edits_unsynced without handing them to the Provider, because the Provider would
be handed a data model without what the person entered. The refusal ends when the
Provider writes the path (or above it) or the person makes the edit again and it fits.
The renderer’s part. A page sends each edit by path, a quiet 300 ms after the last change and at most 1000 ms after the first it has not sent, at once when focus leaves a control and before an action, and holds nothing but the tail the session may not have taken. An input method’s intermediate text is not an edit. The action waits for its edits: when the runtime has no room for them it fails with a retryable error and is not sent. The viewer’s identity is kept in the tab’s session storage, so a reload is the same viewer; where that storage is unavailable a reload is a new viewer and the old overlay is dropped with the old viewer. The full rules are in the renderer contract.
Functions. The catalog’s functions are pure and run in the page, over the
data model and the current time. There is no function the Provider answers and none it
calls on a page: what a person enters and what a person triggers reach the Provider as
edits and actions, and what the Provider knows reaches the page as writes to the data
model. A call to a function the catalog does not have is invalid content. formatDate
with style: "relative" and formatElapsed without until follow the page’s clock,
which ticks while something is following it.
Viewers. viewers() is a watch on everyone looking, with the hello each sent:
a page says the panel it mounts, a native
renderer says what its host wants known. See the runtime’s viewer list above for
identity, grace and replacement.
Ending. ViewSession pairs the renderer with the delivery that put it in front
of a person. finish(result) completes the session with result for whoever waits
on it and returns the outcome; decide(action, result) does so when the action
wins the race to settle; wait() waits for a person to close it or for it to
expire. Dropping the handle ends the session. The outcome type is the
UiSession’s. afui show is this API with a template deciding which action is the
answer.
Built-in renderer frontend
An ViewRenderer resolves a frontend using the session’s provider_id,
ViewOptions::frontend_kind (or the session’s ui_kind when unset), and
ui_api_version. The API version defaults to 1. It reads workspace overrides
from workspace_root or the current directory, and the global configuration from
the launch file or the machine default; a host that serves sessions of several
owners names each one’s in config_directory. Both honor safe_mode and
AFUI_SAFE_MODE=1. The renderer pins the resolved frontend snapshot for its
lifetime. frontend_kind only changes frontend lookup, so the session’s
ui_kind stays available for host routing.
afui show looks up afui / show with API version 1 for every
template contract. Initialize a replacement with
afui frontend init afui show --frontend-id custom --ui-api-version 1.
Enable the workspace fingerprint after editing. Pass --safe-mode to
afui show to use its built-in frontend.
Overlay templates/page.html.j2, style.css, or assets/app-icon.svg
independently. An icon file overrides ViewOptions::app_icon_svg and also
works on its own. The shell must include an element with id="app" and
exactly one <!-- afui:trusted-runtime --> marker. Its
afui.document contains title, provider_id, ui_kind,
labels, has_app_icon, and has_style_override. Use
{{ afui.base_style_path }} for the baseline stylesheet and
{{ afui.app_icon_path }} for the favicon when has_app_icon is true.
The built-in shell layers style.css over the built-in renderer stylesheet
when CSS is overridden. A custom shell can link renderer.css for the same
renderer styles or link its own stylesheet. Adjust
--view-surface-max-width, --view-surface-padding,
--view-surface-radius, and --view-surface-shadow on :root to change
the surface geometry.
Catalogs
A session has one catalog: the AFUI catalog, a single file this crate maintains, extended with the functions the Provider answers when it declares any. No message names a catalog or a version, and a component or a function call that tries to is refused as a property the catalog does not have.
Conditional visibility and input descriptions
The AFUI property visible controls whether a component and its descendants
are shown. It changes presentation only; what an unusual value or a failed
expression does is in the renderer contract. Each
action still uses its own checks.
eq compares JSON values deeply. contains looks for a deeply equal element
in an array and returns false for other inputs. if evaluates its condition
and then evaluates only the selected branch.
description adds visible helper text to a text field, checkbox, choice
picker, slider, or date and time input. The renderer links it to the control
with aria-describedby. Use @accessibility.description for an accessibility
description.
Place @checks on the field its rules describe. Each failed rule displays a separate message below that field and adds to its accessible description. As a rule passes, its message clears. Checks on a button describe that button and disable its action while a rule fails.
Structured components
Tablerenders semantic headers and cells from literal rows or a data binding. Columns specify a key, label, alignment, and optional monospace styling. Cells exposedata-cell-statefor null values, empty strings, missing keys, and ordinary values. UsecaptionandemptyTextto describe the table and customize its empty state.CodeBlockdisplays literalcodetext, with optionallanguage,label, andwrap.Disclosurewraps one child in a native details element with a title and optionaldescription. Bindopento a data path to synchronize expansion with the surface model; unbound, the expansion is local to the page.Badgeshows required dynamictextwith a glyph and a coloured capsule. Its dynamiclevelacceptsneutral(default),info,success,warning, ordanger.Calloutannounces required dynamictextand an optional dynamictitle. Itsleveluses the same values and glyphs asBadge. Warning and danger announce an alert. Other levels announce a status.Progressis a read-only native progress bar.valueruns from 0 tomax(default 1), and both can be bound, so a step count or a_percentfield withmax: 100work as they are. Without a number it shows work whose extent is unknown; an optionallabelnames what progresses. Pair it withvisibleto show it only while something runs.
How a renderer orders table rows, keeps expansion and shows an unknown extent is part of the renderer contract.
Panels, containers and entries
The component under root says what kind of panel this is, and the renderer
draws it as that kind. A panel has one vertical scroll, whatever the tree is.
root | The panel is | Draws |
|---|---|---|
List or Table | a collection | runs to the edges of the panel, its header stays in view |
Form or Section | grouped fields | room around the fields, labels beside the controls when wide and above them when narrow |
Tabs | tabs | each tab is the kind its own child is |
Column | segments | each child a section of the panel; a List or Table in one is as tall as its content and scrolls with the panel |
The panel’s own actions go in the toolbar with updateView
({"primaryAction": "new", "actions": ["import", "export"]}), not in the tree. In a
Column panel do not put a Divider or a Text that is a title between the
segments: give a segment a title by wrapping it in a Section.
Each container has one job, and nesting them to get a look is what to avoid:
| Component | It is | Put in it |
|---|---|---|
List | a collection of the same kind of entry, as rows or a grid | Item, or Section of Item |
Item | one entry: draws no border or background of its own | its content in named slots |
Section | a titled group: a group of fields in a Form, a header of entries in a List, a titled area elsewhere | anything the place allows |
Form | one submission: the fields and Sections that go together | fields, Section, and no other Form |
Card | one summary block that stands on its own | one child; never an entry of a List |
Disclosure | content the person may fold away | one child |
A Button is the one carrier of an action. The thing that owns the action
names it: a view, Section, Item, table row, Form or Modal each has a
primaryAction (the one a person does with it) and actions (the others), and
a Button is mounted in one place only. How an action’s label, icon and variant
are drawn depends on where it is mounted; the renderer contract
says how.
Selection or focus. Three things look alike and are different:
| You want | Use | Because |
|---|---|---|
| the person to pick a row for a later action, and you read the pick | Table.selection, bound to a path | it is data of this panel; clicking only picks |
| to go to something that another panel shows, such as the detail of an entry | a focus action ({"focus": {"values": {"inspector:item": {"@path": "id"}}}}) | it is navigation the host performs, the host decides how it opens (here, elsewhere, in the background), and you hear nothing |
| to do something in the Provider | an event action | it is a request you answer |
Use focus when the answer to “what happens next” is “something else is shown”, and
event when it is “the Provider does work”. Use selection only to hold a choice; it
sends nothing. A panel that reads a focus key (reads_focus) marks the entry whose
primary action is the focus request for the current focus, with no property to write.
An Item has four slots and room for the rest:
{"id": "entry", "component": "Item",
"media": "entry_thumb",
"title": {"@path": "name"},
"description": {"@path": "summary"},
"trailing": "entry_state",
"child": "entry_progress",
"primaryAction": "entry_open",
"actions": ["entry_rename", "entry_sep", "entry_delete"]}
media is an Image or Icon, trailing a Badge or Text, and child is for
what is none of those (progress, an error line). Give the same entries to a List as
rows or as a grid by changing variant alone. Entries in different states still
line up: a tile with no image keeps the place of one. The primaryAction makes the
whole entry one target, and actions are its menu; a control in child does its
own work. Do not nest one activatable entry in another.
A Form is one submission:
{"id": "settings", "component": "Form", "primaryAction": "save", "actions": ["reset"],
"children": ["source", "output"]}
Its children are fields and Sections; its buttons go in a footer, not between
the fields, and Form does not nest. The primary action runs when the person
presses the button, and when they press Enter in a single-line field of any
section: the edit reaches you first, then the action, once. It carries the
@checks of every field of the form that is shown, so write each rule once, on
its field: when one fails the message is at the field and nothing is sent. A search
field outside the form does not run the form’s action.
Text, files and dialogs
Markdownshows itstextas a subset of CommonMark: paragraphs, emphasis, inline code, links, lists, quotes, code blocks and headings. Nothing else is interpreted. Raw HTML, images, tables, strikethrough and bare addresses stay in the text as written, and no text makes an element beyond the subset, so what arrives from a person or a model is safe to bind.Textis for a line that must be shown exactly as given. Headings in aMarkdownstart under the heading that holds it: theTextheading before it, or the title of theSectionit is in, or the panel’s own title. A#in the text is one level below that, and none goes deeper than level 6. A link is followed only to anhttp,httpsormailtoaddress.FileInputchooses files. Itsvalueis always a list (empty when nothing is chosen, even withmultiplefalse) of{ref, name, mediaType, size}.refis aUiBytesRef: read the bytes of an entry withread_bytes, orread_all, and release them when done, as for any bytes a page offers (see Bytes).acceptlists media types (image/*) and extensions (.pdf); a file that does not match is not taken. Put@checkswithrequiredon it as on any field.TextField.contentType(search,email,url,phone) tells the person’s device what the text is, for the keyboard, autofill and, forsearch, the look of a search field with a button that empties it. It checks nothing: say what is valid with@checks. It goes with anyvariant.Modalis a dialog. Bindopento a data path and the Provider opens and closes it by writing the path, and the person closing it writesfalseback; give it atriggeras well, or only, and the person opens it. ItsprimaryActionandactionsare the buttons of the dialog, and Enter in a single-line field of it runs the primary action once, with the checks of its fields, as in aForm. Activating the primary action does not close the dialog: writeopenwhen the work is done.Tabs.selectedbinds the selected tab to a data path whose value is thechildid of that tab. Choosing a tab writes it; a value that names no tab of the component selects the first tab and is reported.- A
ChoicePickerwith nodisplayStyleis drawn by its options: a few short ones as segments, many to choose one of as a popup, the rest as a list. SaydisplayStylewhen the shape matters.
Values, units, and sorting
Send numbers, booleans, ISO 8601 timestamps, and null in the data model.
Use AFDATA suffixes for quantities with units, such as total_bytes or
elapsed_ms. Send counts as JSON numbers. AFUI checks the initial model and
each update before sending. A value that contradicts its field suffix fails
validation. A scalar update uses the last segment of its data-model path as
the field name. Provider tests can apply the same contracts with
test_support::assert_clean_view_data_models(&messages). Use afdata lint
on serialized data to see optional naming and representation suggestions.
Use a column’s text expression for presentation. Relative paths in the
expression resolve against the current row, including when rows is literal.
An absolute path still resolves against the surface model.
{"component":"Table","id":"inventory","rows":{"@path":"/inventory"},"rowKey":"id",
"sort":{"@path":"/sort"},"columns":[
{"key":"total_bytes","label":"Size","align":"end",
"text":{"@call":"formatQuantity","args":{"value":{"@path":"total_bytes"},"unit":"byte"}}},
{"key":"summary","label":"Summary","sortable":false,
"text":{"@call":"formatString","args":{"value":"${name} · ${category}"}}}
]}
Headers cycle through ascending, descending, and original order. Sorting uses
the column key’s raw value. Numbers compare numerically, timestamps compare
as instants including fractional seconds, strings use the viewer’s locale with
numeric collation, and booleans put false first in ascending order. For mixed
types, ascending order groups numbers, timestamps, strings, then booleans.
Null and missing values come last in either direction. Equal values keep their
provider order. Selection follows rowKey, or the original index when
rowKey is absent. A sort binding holds null or an object with a sortable
column key and direction of ascending or descending. A viewer’s change of
either is an edit like any other (What a person types).
formatQuantity uses the AFUI catalog’s unit enum and accepts style
(short, long, or narrow) and maximumFractionDigits. The renderer
chooses unit scaling and the viewer’s preferred units. percent is in
percentage units, so 38 means 38%. formatNumber supports compact notation.
formatDate accepts dateStyle, timeStyle, or style: "relative", which says
how far the timestamp is from the current time and keeps up with it; use
the legacy format pattern on its own. formatElapsed(since, until) gives the
whole seconds from since to until, or to the current time when there is no
until, in the two largest units. Missing and null formatter inputs
return null. String interpolation renders null as empty and a table cell with
a null display uses table_null. A renderer supplies the exact value on hover
when abbreviated or rounded display hides it.
Use unit on a Slider or numeric TextField to display and edit in the
viewer’s preferred units. The model and validation retain the declared unit.
Input for data sizes, transfer rates, and durations stays in the declared unit.
A DateTimeInput with both date and time displays in the local time zone and
writes an ISO timestamp with the local offset.
Renderer labels and slots
Set data-afui-label-<key> on #app or the document element using hyphens
in place of underscores. The renderer reads #app, then the document
element, then ViewOptions::labels, then the built-in English defaults.
Empty strings are valid overrides. Add [data-afui-slot="status"] to the
shell to place directed progress and success messages. The action element
exposes data-action-state and, when supplied, data-progress-code or
data-error-code.
| Keys | Used for |
|---|---|
renderer_failure | Fatal renderer copy |
action_error, action_rejected, action_cancelled, action_already_settled | Action failures and arbitration |
level_neutral, level_info, level_success, level_warning, level_danger | Spoken status levels |
table_null, table_missing, table_empty | Table placeholders |
table_sort, table_sort_original, table_sort_ascending, table_sort_descending | Narrow-table sort menu labels |
modal_close | Dialog close button |
focus_refused | Shown when the host answers a focus action with a refusal |
focus_open_new, focus_open_background | Menu items that open a focus target another way |
menu_more, menu_copy, toolbar | The “more” button, the standard copy item and the name of the toolbar |
link_copy, media_copy, media_save | The standard entries of a link, an image and a video |
search_clear | The button that empties a search field |
file_choose, file_choose_many, file_replace, file_drop, file_remove, file_not_accepted | The file input: its button, its hint, the remove button of a file ({name} is its name) and the refusal of a file that is not accepted |
filter_aria_label, filter_placeholder | Choice picker search |
date_aria_label, time_aria_label | Date and time inputs |
video_unsupported, audio_unsupported | Media fallback |
An outer shell can place optional regions with data-afui-slot="notice",
data-afui-slot="error", and data-afui-slot="fatal". Give notice
and error regions accessible live roles such as status and alert.
On action failure, the renderer sets data-error-code on the error region
and the originating button component. The next attempt clears its error.
Fatal errors set data-afui-state="failed" on #app and
data-error-code on the fatal region or #app when there is no fatal slot.
The view of the one panel a page mounts is drawn inside #app. Component hooks include
data-variant on buttons, text fields and choice pickers, data-axis on
dividers, and data-display-style on choice pickers. Standard icon SVGs
expose data-view-icon with the catalog name. A Button with iconOnly: true
requires icon and uses its label for the accessible name and hover tooltip.
iconOnly defaults to false, which displays the label.
JSON templates and view projections
With the page feature, use UiPage::json_builder to render structured
data without opening a session. It shares the frontend’s per-file overlay,
supports named partials, and renders the document under afui.document.
The afui global also contains provider_id, ui_kind and
frontend_id. Each interpolation emits a complete JSON literal. Write
{"title": {{ afui.document.title }}} with no quotes around the expression.
let projection: serde_json::Value = UiPage::json_builder(&frontend)
.entry("templates/surface.json.j2")
.fallback(r#"{"title": {{ afui.document.title }}}"#)
.override_templates_under("templates", ".json.j2")?
.render(&document)?;
render_as::<T> deserializes into a Provider type. A missing template,
undefined value, or invalid JSON produces Error::PageRender. If a
frontend override is active, the error includes safe-mode guidance.
extend_environment accepts the same restricted filters and globals as an
HTML page.
For the first render, put one or more ViewProjection values in
ViewOptions::initial_projections. Each contains the panel whose view it opens, its entry path, fallback
source and serialized document. The session resolves the frontend once and
renders both the opening messages and the shell from it before starting
delivery. A view whose current state cannot be split into messages that fit the
runtime limit is rejected before the opening delivery or update.
Pass a JSON template that projects to an array of view messages to
session.send_rendered("review", "templates/surface.json.j2", FALLBACK, &document).
It uses the session’s frontend snapshot, discovers JSON template partials
under templates/ and runs the same catalog and message checks as
session.send. Providers can use session.frontend() with the JSON builder
directly when the projection needs a different set of partials.
Delivery: window, link, or session
A session reaches a person as a window, a link, or a session.
UiDeliveryPlan resolves each of them through one plan. What draws the session is
the argument after it: a Router for a page of your own, or a ViewRenderer. The
modes, expiry and everything else here are the session’s, and the same for both:
| Mode | Delivered as | Expires |
|---|---|---|
window | an isolated window this machine opens | never — the window is the bound |
link | an AFUI page that proxies exactly this loopback session | the global AFUI attention policy, with expiry disabled by default |
session | registered only, reached later through afui host open or afui host serve | the session never expires; each remote mount uses the same AFUI attention policy |
// `resolve` for a Provider that stays local; `resolve_allowing_link` for one
// that offers the LAN page as well.
let outcome = UiDeliveryPlan::resolve_allowing_link(explicit_mode)?
.deliver(session, router)
.await?;
When the caller must announce the AFUI-owned Link URL before it blocks, split the same plan at its handoff point:
let active = UiDeliveryPlan::resolve_allowing_link(explicit_mode)?
.start(session, router)
.await?;
if let Some(url) = active.link_url_secret() {
publish_secret_link(url)?;
}
let outcome = active.wait().await?;
link_url_secret() is available only for link. It is named as a secret on
purpose: the credential is part of the URL, so publish it only through the
intended private handoff. deliver remains the shorter start + wait form
for callers that do not need the URL in between.
Delivery resolution tries explicit --mode, then session delivery when
AFUI_LAUNCH_FILE supplies a registry, then window delivery. Leave the
flag’s parser default unset so the launch configuration can take effect.
link is opt-in per Provider: build the plan with resolve and an explicit
link is refused there (a launch file only ever selects session), naming the modes that are
on offer, and your own --mode flag should not list link as a legal value
either. The refusal lands at resolve rather than at deliver on purpose: a
Provider normally announces its resolved delivery before it blocks, and a
refusal that arrives after that announcement produces a readiness report that
was false when it was written.
The opt-in is only permission to bind a LAN listener. Lifetime is not part of
it: attention_policy() is report-only, and the intervals come from AFUI’s
global config.json under attention.idle_timeout_s and
attention.grace_period_s.
Reporting a ready delivery
Everything a readiness report needs is one call, on either kind of active delivery:
let facts = active.facts();
| Field | Meaning |
|---|---|
mode | the resolved delivery, spelled the way a person types it |
session_id | stable identity, shared with this delivery’s registry entry |
link_url_secret | the bearer URL; present for link and nothing else |
idle_timeout_s | how long this delivery may sit unattended; absent when nothing lapses |
grace_period_s | how long the warning runs; present exactly when there is an attention clock |
UiDeliveryFacts is facts and nothing else — no sentence to print, no notion
of which field matters more, no opinion on whether a field belongs in your
output at all. Those are yours. The names follow the conventions a structured
output layer reads (_s for seconds, _secret for a bearer capability), so
splicing the whole structure into an event gets correct handling by default;
a Provider that deliberately publishes the URL renames that one field itself.
Debug prints *** for link_url_secret, and UiSessionEntry’s Debug
does the same for both of its URLs, so {:?} in a log line never carries a
credential.
UiDeliveryPlan::mode() reads the same resolved word before anything is
served, for a Provider that has to name the delivery earlier still. Do not
resolve delivery a second time to learn it: two reads of one decision
are two chances to disagree. UiDeliveryMode::description() is one factual
sentence per delivery, for a Provider that wants one and does not want to
write its own three-armed match over the same three facts.
Outcome::ending() is the counterpart at the other end: completed,
closed, or expired. The completed case usually deserves a richer word of
your own — what the person actually decided — but the other two carry no
domain meaning, and every Provider spelling them for itself is how one tool’s
closed becomes another’s cancelled.
Window exit evidence
For UiDeliveryPlan window delivery and afui show, each launch adds a fresh
query ID to the window URL. The host records a successful request for that
page carrying the launch ID; loading it without JavaScript is sufficient.
Nonzero exits and signals are WindowWaitFailed; successful exits without
page arrival are WindowUnavailable; successful exits after arrival are
Closed, which supplies no decision. afui show preserves these kinds as
show_window_wait_failed and show_window_unavailable.
afui host open and upstream windows have no host request evidence for
that launch. They check exit status only; a successful exit remains Closed.
link puts a person’s data on the network unencrypted
link is the one delivery that reaches another device with no tunnel in the
way: plain HTTP on this machine’s own LAN-reachable address, with no
authentication beyond the credential already in the URL. Use it only on a
network you trust, and treat that URL the way you would treat a password —
give it to the person it is for, and nowhere else: not into a file, not into a
commit message, not into a chat transcript you do not control.
When the page is not this crate’s to serve
A Provider that already answers on a listener it bound itself hands AFUI no
Router. Name that private source with UiUpstream and give it to the same
plan:
let active = UiDeliveryPlan::resolve_allowing_link(explicit_mode)?
.start_upstream(
UiUpstream::new("inspector", "console", upstream_url_secret)?
.with_subject("running service"),
)
.await?;
if let Some(url) = active.link_url_secret() {
publish_secret_link(url)?;
}
let outcome = active.wait().await?;
The meanings do not change for an upstream. window opens its private URL
locally. link starts an AFUI-owned LAN listener and redirects to its sole provider page; the
upstream URL remains private behind the proxy, so its own listener may stay on
loopback. session only registers it and has no AFUI expiry. The Provider may
race active.wait() against its own shutdown signal; cancelling the wait drops
the announcement.
AFUI cannot mint or revoke a credential on a listener it does not own. The
upstream contract is therefore narrow: its owner keeps that private URL usable
for as long as the ActiveUiUpstreamDelivery exists and revokes it afterwards.
An internal crash-cleanup lease is fine; exposing that lease as the Link or
Session lifetime is not. The person-facing remote lifetime remains AFUI’s
attention policy alone.
window may open an HTTP or HTTPS upstream directly. link and session
require a private HTTP upstream: both may pass the page through AFUI’s
streaming proxy, which intentionally does not act as a TLS client or trust
arbitrary upstream certificates.
Registry, launch files and discovery
Every live session announces itself in a registry so that other processes can
list, open and end it. The announcer takes an exclusive lock on a sidecar file before publishing
the registry entry by atomic replacement. On Unix each file is 0600 under
a 0700 directory. Listing prunes a successfully parsed entry when its lock
file is missing or its lock can be acquired. Unreadable or malformed records
and lock checks that encounter an I/O error are left in place.
The launch file’s registry directory applies to list_sessions, find_session,
watch_sessions, and the CLI. Their explicit-directory variants and
SessionServer::with_sessions_directory can name a different registry.
The registering side creates the directory private to the user.
A host that serves sessions of several owners from one process cannot name the
directory with a process-wide variable, so UiSession::with_registry_directory
registers that one session (and records its input) in a directory of its own,
whatever the variable says.
A session remains registered while its announcement lock is held. Stopping service should drop the announcement handle, and process exit releases the lock automatically. The registry uses this rule on Unix and Windows. The upstream owner remains responsible for revoking its credential when the delivery ends.
Launch files
Set AFUI_LAUNCH_FILE to the startup file for a Provider process. Paths in
the document are relative to the file unless absolute. Every field is optional.
{
"sessions_directory_path": "/private/example/sessions",
"context": "review",
"config_directory_path": "/private/example/config",
"restore_file_path": "/private/example/restore.json"
}
An explicit delivery option takes precedence. A supplied registry selects
registered session delivery by default. A configured browser path belongs in
config.json under browser_binary_path.
The restore file contains from_session_id and optional Provider-defined
state. The relaunched process consumes that file once. Use
UiLaunchFile::for_session_children() when forwarding the registry and
context to child processes.
Launcher labels and discovery
The launch file’s context supplies a non-secret, opaque ownership label.
UiSession::new and UiUpstream::new read it when constructed.
A label must contain 1–256 Unicode characters with no controls. The SDK
preserves spaces, case and Unicode. Metadata, listings and Debug output carry
the label unchanged.
UiSession::with_context(value)? and UiUpstream::with_context(value)? can
replace an inherited label. The launch file’s registry selects session delivery
unless the caller explicitly chooses another mode.
list_sessions() returns the current live entries. watch_sessions(interval)
returns a stream of SessionChange::Announced(entry), Updated(entry), and
Ended { session_id }. Existing entries are announced immediately in listing
order; subsequent polls use the same liveness rules. Only subject, waits_for_decision or
last_input_epoch_ms changes produce Updated. The label is session identity,
so filter the opaque label yourself and remember matching ids for Ended.
Polling can miss a session that starts and ends between snapshots.
Polls use blocking workers; failed registry reads retain the last successful
snapshot and retry after the interval, without inventing endings. Zero interval
is clamped to 1 ms. Drop the stream to stop future polls; an already submitted
read may finish. The stream needs a Tokio runtime while polled.
afui host list --follow [--context <tag>] [--interval-ms <positive-ms>]
uses this stream, with a default interval of 500 ms. Changes are AFDATA progress
events named by progress.event: session_announced and session_updated
carry the safe list entry under progress.session; session_ended carries
progress.session_id. The safe entry contains session_id, provider_id,
ui_kind, owner_pid, waits_for_decision, announced_at_epoch_ms, and optional
subject, context, declaration and last_input_epoch_ms, with no credentials. Ctrl+C finishes with a
session_list_stopped result. Output is one ordered stream on stdout by default,
or stderr with --output-to stderr; split is refused.
Opening a registered session in your own window
A host that owns its windows supplies a registry and ownership label through
AFUI_LAUNCH_FILE. The host presents the registered sessions in its own windows.
The host discovers entries with list_sessions() or watch_sessions(interval)
and matches entry.context exactly. For each session it presents, load
window_url_secret when present, otherwise access_url_secret. Keep the full
URL, including its fragment: the local runtime’s window key lives there and
is what authorizes local external-link handoff. Neither URL belongs in logs or
ordinary listing output. For an announced upstream, the source owner still
keeps its credential valid during delivery and revokes it afterwards.
Each session gets its own WebView with a fresh non-persistent website data
store. Do not share cookies, storage, cache, or a persistent profile with the
system browser, other sessions, or any other page the host presents. Destroy
that view and its data store when its view ends. The host loads the Provider’s
page as supplied: do not rewrite its content, inject scripts, or replace its
behavior. It is the same content afui host open loads.
Closing the host’s window ends only that view. It must leave the registered
session running so another local or remote session can still use it. To end the
session itself, explicitly send POST <access_url_secret>__afui/end
(SESSION_END_PATH); the owner receives Closed, without a decision. For an
announced upstream use the source owner’s external-end contract at that same
reserved path. Do not manufacture a completion from window closure.
A local window and a remote mount may show the same session concurrently. Closing one view does not end the other; explicitly ending the underlying session ends access for both. Only the remote mount runs AFUI’s attention clock. A registered session and the host’s local window have no attention expiry, and local traffic must not be used to keep an unattended remote mount alive. The host’s remote client follows the separate stable host HTTP contract.
Ending a session from outside it
Every session answers POST <access_url> + agent_first_ui::SESSION_END_PATH
under its own credential, on every delivery: afui session close <id> sends
it, so does a host’s end control, and so does afui.end() from inside the
page itself. Whoever created
the session gets Outcome::Closed back — the same outcome as a person closing
its window — never a manufactured Completed(T). However a session ends, its
credential stops working, and a Provider response still streaming under it —
an event stream, a long poll — ends with it. A WebSocket the Provider upgraded
itself is not ended this way.
The threshold for ending a session is the same as the threshold for seeing
it: whoever holds the URL already holds the whole credential, and can already
do worse from inside a Provider’s own page (a terminal’s exit, for one), so
refusing to let them end it from outside would be a boundary that only looks
like one.
The whole __afui/ prefix is reserved. SESSION_END_PATH and SESSION_SNAPSHOT_PATH are the
public external-control paths; live-runtime paths are deliberately not public API.
Do not route on any name under the prefix, proxy through it, or otherwise give
it a second meaning in your own Router — this crate’s dispatch answers for the
whole prefix before your router is ever reached, so a route of your own under
it is simply unreachable, not a conflict you would notice at runtime.
Reserving the prefix rather than only today’s paths lets AFUI add another later
without silently colliding with something you already routed there.
What an override may and may not do
An override supplies presentation. It may restructure freely — reorder, regroup, drop, rename, restyle — and that freedom is the point: an agent customises a Provider’s UI by writing files, not by editing the Provider.
A frontend override replaces individual files because the Provider still owns the page and supplies the remaining presentation. A show template is selected as a whole directory because its input and result schemas belong with the request template that uses them.
These limits hold regardless of what a template contains.
Runtime data may not choose or inject the UI code that runs. Data flows into a template. Data must never select which template executes. If a domain value can reach the page as markup rather than as text, that boundary is already broken — escape everything, including the values a provider returned to you.
The server stays authoritative. An override is subject to the same provider responsibilities as the stock page.
A frontend supplies no behaviour. AFUI refuses an override file whose name
says it is a script, and reject_frontend_script refuses one hidden inside a
template it does supply. The only JavaScript your page loads is yours.
The guard also refuses markup that runs no script but still sends the person, a
request, or the page’s credentialed address somewhere: <meta http-equiv> (a
refresh navigates without a click), <meta name=referrer> and referrerpolicy
attributes (either would undo the session’s no-referrer), the form request
attributes action, formaction, method and formmethod, and the frame,
frameset, applet and base elements beside script, iframe, object
and embed. A form your runtime reads is fine; a form that posts by itself
goes to whatever route it names, past the decision its button is labelled
with. In a rendered page javascript:, vbscript: and data: count only in
an attribute a browser loads or navigates to — href, src, srcset,
poster, ping, SVG animation values and the like — so a title or
aria-label that mentions one is text.
UiPage::builder (the page feature) assembles these limits for you: the
escaping policy, the render, the rendered-markup guard, and a check that every
element id your runtime binds to actually exists in the output — a page
missing one is reported by that id rather than opened as a window that does
nothing. It knows nothing about what your elements or your document mean; it
only checks that what you declared is there. A page missing several is
reported once, naming all of them: somebody writing a replacement cannot read
your contract from where they stand, and finding it one render at a time is
the same fix spread across as many sittings as there are ids.
The builder also covers template trees without weakening that boundary.
entry_at and template_at separate a stable logical template name from its
frontend-relative file path. UiFrontend::files_under plus
override_template registers open-ended partial directories owned by an
override. requires_element_map derives the runtime’s required ids from the
same serializable map exposed to templates, so a Provider need not maintain a
second list by hand.
Trusted Provider code may use extend_environment to add plain-value filters
and globals. The extension receives only UiPageEnvironment: it cannot add a
loader, change escaping or undefined-value behaviour, restore the reserved
safe or tojson filters, or replace the afui global, which carries the
page’s data as afui.document. tojson is
removed with safe because its output skips escaping and keeps a string’s own
quotes, which in an attribute is enough to write new attributes. Filter/global values also
cannot be raw MiniJinja Values, so an extension cannot smuggle the engine’s
“already safe” bit back to a frontend under another name. Those invariants
stay owned by UiPage, including when a page needs locale-aware formatting or
another domain-specific projection. A filter that needs to return a sequence
or map selected from its input can use UiPageSerializedValue; it rebuilds the
data through JSON and deliberately drops engine-only safety provenance.
Errors: what happened, and what to do about it
Error’s Display says what happened. It does not say what to do — that is
hint(), and keeping the two apart is what stops a caller with a hint field of
its own from printing the same sentence twice, once inside the message and once
beside it.
Err(error) => fail(
&format!("myprovider_{}", error.kind()),
&error.to_string(),
error.hint(),
),
A coarser code than that is yours to build, but build it out of named arms rather than a default. A fallback that names one cause — “the frontend could not be read” — reports a closed session runtime and a machine with no browser as a broken frontend, and sends somebody to look at a file that is fine. If you want a fallback at all, let it carry AFUI’s own word through.
kind() returns UiErrorKind, a closed enum with no domain in it, so your own
error code is a prefix rather than a match over every AFUI variant. It is an
enum rather than a string on purpose: translating a dependency’s failures into
your own vocabulary is your job, but you can only do it completely if
something tells you when you have missed one, and nothing exhaustively matches
a string. A &'static str would force every caller into a wildcard arm, which
is where a classification added later is mis-reported.
match error.kind() {
UiErrorKind::WindowUnavailable | UiErrorKind::WindowWaitFailed => ...,
// no wildcard: a classification added to AFUI stops this compiling
}
It is deliberately not #[non_exhaustive], for that reason. Display and
as_str() give the stable snake_case word when a prefix is all you want.
kind() | as_str() | Raised by |
|---|---|---|
InvalidArgument | invalid_argument | an identifier, URL, TTL, icon, or decision declaration, route or attribute AFUI cannot accept; an operation registration (a bad name or about text, a duplicate, an unregistered name); view input that fails validation (Error::ViewInvalid carries the specific code, such as asset_undeclared or function_name_taken) |
SessionContextInvalid | session_context_invalid | a launcher label is not Unicode, empty, longer than 256 characters, or contains controls |
DeliveryModeInvalid | delivery_mode_invalid | an unsupported explicit delivery word |
DeliveryModeNotOffered | delivery_mode_not_offered | the resolved delivery is one this Provider did not offer |
UpstreamNotProxyable | upstream_not_proxyable | an https:// upstream behind a delivery that proxies plain HTTP |
LinkAddressUnavailable | link_address_unavailable | no LAN-reachable address to advertise a link on |
RuntimeMisconfigured | runtime_misconfigured | a second runtime, a zero capacity, or a page that cannot reach its runtime |
RuntimeClosed | runtime_closed | the session or one of its calls has ended |
RuntimeBusy | runtime_busy | a bounded in-process runtime state lock was temporarily unavailable |
RuntimeViewerUnknown | runtime_viewer_unknown | a message, request or bytes read addressed to a viewer the session does not have |
RuntimeMessageTooLarge | runtime_message_too_large | one encoded runtime frame exceeded the fixed wire bound |
RuntimeBlob | runtime_blob | no bytes policy was set, or bytes violated their declared policy |
RuntimePayload | runtime_payload | a runtime payload could not be encoded or decoded |
FrontendUnreadable | frontend_unreadable | a frontend that exists and is trusted but could not be read |
FrontendIncompatible | frontend_incompatible | a frontend written against another ui_api_version |
FrontendUnsafe | frontend_unsafe | markup or a file name an override may not supply |
PageRender | page_render | a template failed to compile or render |
PageIncomplete | page_incomplete | a rendered page is missing an element id or its runtime marker |
ConfigUnreadable | config_unreadable | AFUI’s own configuration directory or attention config, or an invalid launch file |
WindowUnavailable | window_unavailable | no browser found, or one that would not launch |
WindowWaitFailed | window_wait_failed | waiting on an open window failed |
Io | io | anything else AFUI could not read, write, or generate |
The match behind kind() has no wildcard arm, so a new AFUI variant does not
compile until someone classifies it; tests/error_kinds.rs fails if that
classification invents a word missing from the test’s own list of kinds, and
again if a kind on that list is one no error can actually raise. Keep this
table in step with that list.
hint() returns a recovery action or None. Safe mode is suggested only for a
failure an override could have caused — a built-in page that will not render is
the Provider’s own bug, and sending a person to disable something they never
installed helps nobody.
When your own listener hands out access
The usual shape is one credential per session, minted when you hand AFUI a session and dropped when that session ends. Some Providers have the other shape: a long-lived listener with a domain API of its own that grants access to the same UI on request, and takes it away again.
Do not reimplement credential routing for that. It is the same dispatch, driven from outside:
let mount = UiMount::new("http://127.0.0.1:8080/ui/")?;
let app = provider_routes.nest_service("/ui", mount.router());
let access = mount.external_access(ui_routes, policy, Some(app_icon));
// From your own endpoint, when you decide a request deserves access:
let credential = access.issue(UiExpiry::Idle(Duration::from_secs(1800)))?;
credential.access_url_secret(); // the URL to hand back
access.renew(credential.secret()); // from your renew endpoint: true while still live
access.revoke(credential.secret());
If that mounted page is live, mint the credential and its runtime together:
let (credential, runtime) = access
.issue_with_runtime(UiExpiry::Idle(Duration::from_secs(1800)))?;
Use issue_with_runtime_options with a UiRuntimeOptions when requests also return offered bytes, or the
default limits, gate or compression are not the right ones. The runtime is scoped to exactly that credential;
revoking, ending, or reaping it closes the runtime and wakes recv, and also
ends any Provider response still streaming under it — an event stream, a long
poll — because removing the credential only stops new requests. A Provider
WebSocket upgrade is not covered by that, so do not combine issue with a
Provider WebSocket route; carry live traffic on the runtime instead.
Everything a session gets comes with it: the 404 that does not confirm a UI is
here, the Host check that stops a rebound name reaching the same socket, the
response headers, the Provider icon route, the reserved __afui/ prefix — and
__afui/end, which for these credentials revokes the one it arrived on, since
there is no session waiting on an outcome to wake. What stays yours is the part
that is genuinely yours: which request deserves a credential, what your endpoint
for asking looks like, and what you do with the URL afterwards.
The idle expiry is crash cleanup, not a lifetime a person sees. A process that revokes on its way out never reaches it; one that dies without revoking leaves a credential that stops working on its own. Do not present it to anyone as how long their UI lasts — the delivery decides that.
Holding a credential open from the other side
A process that was handed one of these URLs renews it while a person is still using it:
let lease = UiCredentialLease::new(idle_timeout);
tokio::select! {
outcome = delivery.wait() => { /* the person finished */ }
failure = lease.keep_alive(async || my_api.renew(&credential).await) => { /* it stopped */ }
}
keep_alive renews three times per idle window, so one lost renewal is not a
lapsed credential, and resolves only when a renewal fails. The call itself is
yours: the endpoint that renews a credential is your domain API, and AFUI
inventing a wire protocol for your service is not a trade worth making.
is_ui_credential answers whether a string is the shape AFUI issues, for a
caller reading one back out of a URL — that fact belongs here rather than as
“sixty-four hex digits” written down somewhere else.
The floor your page stands on
Every session serves one AFUI-owned stylesheet at BASE_STYLE_PATH. Link it
before your own, from the template:
<link rel="stylesheet" href="{{ afui.base_style_path }}">
<link rel="stylesheet" href="style.css">
In that order, because yours loads second and wins at equal specificity; most
selectors in the baseline are wrapped in :where() so overriding one is never
a specificity fight.
It carries only rules of these kinds: what AFUI’s own runtime decides —
what a control looks like while a call is in flight, what hidden does — and
what is wrong rather than plain when a page forgets it: a focus ring, a
[hidden] that beats an author display, a page inset that clears the edges
of the phone a link session was opened on, prefers-reduced-motion. There
are no components: no button variants, no grid, no utility classes.
The stylesheet’s only vocabulary is the connection state:
afui.connection(el) writes AFUI’s own connection word to
data-afui-connection, and reconnecting and closed are dressed here
because this page may be showing something that is already wrong is AFUI’s
fact and no page should have to answer it for itself. afui.status(el).set(text, state) is the other direction — that word is yours, it lands on data-state,
and what “busy” looks like is not AFUI’s to say.
Everything tunable is a custom property on :root, so a different palette is
a declaration in your own stylesheet rather than a fork:
| Surfaces | --afui-page --afui-panel --afui-panel-strong |
| Text | --afui-ink --afui-muted |
| Lines and focus | --afui-line --afui-line-strong --afui-focus |
| Color families | --afui-X --afui-on-X --afui-X-bg --afui-X-ink for accent, info, warn, danger, and ok |
| State overlays | --afui-fill --afui-fill-strong --afui-accent-fill --afui-accent-fill-strong |
| Type | --afui-font-ui --afui-font-mono --afui-text-ROLE-size --afui-text-ROLE-weight --afui-text-ROLE-line-height --afui-text-scale |
| Space and shape | --afui-space-page and the other --afui-space-*, --afui-radius-*, --afui-border-width, --afui-focus-width, --afui-elevation-N-* |
| Controls and layout | --afui-control-SIZE-*, --afui-collection-*, --afui-form-* |
The baseline supplies light and dark values. A CSS override changes the named value with ordinary cascade rules. The non-color variables are the CSS projection of the theme’s presentation parameters; themes lists every one with its baseline. Use the Rust resolver to recompute related color roles when a color identity changes.
Use X for solid fills, on-X for their foregrounds, X-bg for tinted
surfaces, and X-ink for text, icons, and borders on those surfaces.
The state overlays already include opacity. A shadow is composed from its
level’s parts, with ink as its color:
.raised {
box-shadow: 0 var(--afui-elevation-1-y) var(--afui-elevation-1-blur)
color-mix(in srgb, var(--afui-ink) var(--afui-elevation-1-opacity), transparent);
}
To generate the variables of a theme from the command line, extract the result’s CSS field and load that stylesheet after the baseline. See themes for the model, the parameters and the diagnostics.
afui theme css theme.json --output json | jq -r '.result.css'
--afui-space-page is how far your content sits from the edge of the
viewport: each edge takes the larger of it and the area the hardware
actually leaves reachable. A page that is edge-to-edge instead — a sticky
bar, a full-bleed deck — says so with body { padding: 0 } and places its
own insets, because a sticky bar pushed down by a body inset leaves content
scrolling past above it.
The floor is a route rather than bytes you serve yourself, because an override
replaces your stylesheet in full, and a baseline concatenated
into that file would go with it. Answered by the session, the floor survives
the replacement — which is what lets an override be one template and no CSS at
all and still open as an AFUI page. page_base_style_source() is
there for a build that assembles a page outside a session, such as a preview.
The routes a page serves
A page is at /, its stylesheet is a route rather than an inline block, and
the override’s assets/ tree is nested under a fixed name so a template can
refer to it relatively. Nothing about that shape varies between pages:
page_routes(page, stylesheet, &frontend).merge(my_domain_routes)
For a page rebuilt per request — a live panel, or one reread because the
workspace behind it can change while a person is looking at it — route /
yourself and merge page_asset_routes(stylesheet, &frontend) instead.
Bytes your page serves itself
A preview, a generated code, an attachment. UiBytesPolicy is a media-type
allowlist and a size bound; you supply both, because only you know what your
page is for.
let policy = UiBytesPolicy::new(max_bytes, ["image/png", "image/jpeg"]);
policy.respond(media_type, bytes) // bytes you already have
policy.respond_with_file(&root, relative, media_type) // one file under a root
policy.read(&root, relative) // just the bounded read
Every refusal is a 404, whatever the reason — too large, a type you never
listed, a symlink, a path that tried to leave the root. A page asking for
something it may not have learns only that it is not there.
respond_with_file opens the supplied root as a directory handle. relative
must contain only plain names; each component is opened without following a
symlink relative to the preceding handle, so swapping a path component cannot
redirect the walk. Type and length checks inspect the opened file, and the
bound is applied again to what was actually read. read is the same walk without the
response, for a page that serves one part of a container it read off disk.
There is no caching, no Range, and no upload here. A page’s own bytes are
small and generated per session, and each of those is a second thing to get
right in a response a session hands to a browser under a bearer credential.
What your page may load
A Provider page denies everything and then names a small set of exceptions. Say which with switches rather than a string:
let policy = UiPagePolicy::new(UiPageScript::Nonce(nonce.clone()))
.allow_images()
.allow_form_submission()
.into_security_policy();
The floor UiPagePolicy::new starts from is default-src 'none' plus a
stylesheet from this session’s own origin — no base URI, no framing, no plugin,
no form target, and no network destination. Everything else is an addition you
name:
| Switch | Adds |
|---|---|
UiPageScript::None | nothing; the page has no behaviour and cannot be given any |
UiPageScript::Nonce(nonce) | exactly one script, carrying this session’s nonce |
UiPageScript::SameOrigin | script files served from this session’s own origin |
allow_images() | images from this session’s own origin |
allow_fonts() | fonts from this session’s own origin |
allow_media() | audio and video from this session’s own origin |
allow_runtime() | the same-origin AFUI runtime connection |
allow_form_submission() | form posts back to this session |
allow_inline_styles() | inline style attributes and <style> blocks |
Assembling rather than formatting is the point. A hand-written policy is a
format! over every directive, where a typo produces a policy that is merely
different rather than invalid, and where the HeaderValue::from_str at the
end has a failure arm that is very tempting to answer by quietly serving some
other policy. That is the one outcome a security header must never have. Here
every part is fixed ASCII or a hex nonce, so there is no parse step and nothing
to fall back from.
Attaching a UiSessionRuntime to a page built without allow_runtime() is
refused when the session is mounted. It has to be caught there: the browser
refuses that connection, not AFUI, so nothing on this side would otherwise hear
about it and the page would simply sit there connected to nothing.
UiSecurityPolicy::with_content_security_policy remains the escape hatch for a
page these switches do not cover. Taking it has costs. The string is
yours, so a mistake in it is your error and must be reported as one — never
answered by falling back to a different policy, which turns a broken security
header into a page that looks like it worked. And AFUI can no longer tell
whether your page may reach its own session, so the runtime check above stops
applying to it.
What your page runtime is written in
Every page that talks to a live session has the same work to do: deriving the session root, reconnecting live state, keeping call identity straight, releasing temporary byte bodies, and small pieces of care that are only interesting when they are missing.
page_kernel_source() is that, as source to concatenate ahead of your own
runtime inside one function scope:
format!(
"<script nonce=\"{}\">(function(){{\n{}\n{}\n}})();</script>",
nonce.as_str(),
page_kernel_source(),
MY_RUNTIME,
)
It defines one lexical afui binding and writes nothing to window. That
scope also hides afui from an embedding host: a page that wants host theming
(afui.setTheme, see Stable host theme tokens)
loads the kernel as its own top-level <script>, as AFUI’s built-in pages do.
A live page is built out of these:
| Primitive | What it is |
|---|---|
afui.sessionRoot, afui.url | a Provider-owned static or navigation URL kept under this session’s credential |
afui.connect({onValue, onMessage, onRestart, onRequest, onConnectionState, onReady, onFocus, onRejected, hello}) | the complete typed session runtime (hello is handed to the Provider in its viewer list; onConnectionState receives {state, reason, detail}; onRejected receives a frame the runtime refused while the connection goes on); request sends actions and receives progress/result/error, setValue and sendMessage send the rest |
runtime.bytesUrl, runtime.read, runtime.readRange, runtime.release | AFUI-managed byte bodies without a Provider download protocol |
runtime.offerBytes(source, {mediaType, revokeOnRelease}) | offer a Blob, File or Uint8Array for the Provider to read; returns {ref, revoke()}, and revokeOnRelease withdraws the offer when the Provider releases it (see Bytes) |
runtime.openExternal(url) | a URL opened outside the page — the system browser for the local window, a new tab for remote access — instead of navigating the surface (see below) |
runtime.watch(key, handler) | register interest in a key and receive its watched values (published with UiAudience::Watching(key); shared values of the same key go to onValue instead); returns a function that withdraws this registration. The kernel merges every registration on the page into the one set sent to the runtime |
runtime.setValue(key, value) | send a droppable value; coalesced locally, null clears it; errors carry a code |
runtime.rows({fetch}) | a long sequence of which only a window is shown, kept in step with the provider (see below) |
afui.list({...}) | equal-height rows of which only the visible ones exist (see below) |
afui.status(element) | an aria-live region written as text, with data-state for the stylesheet |
afui.inFlight(elements) | controls disabled while a call is pending: begin() sets disabled and aria-disabled, end() restores their original values. For a non-native control your handler must still reject activation while pending; ARIA alone does not suppress events |
afui.connection(element, words) | the runtime’s own connection state, marked for the baseline and worded by you |
afui.guardUnload(isDirty) | warn before leaving, asked at the moment of leaving |
afui.place({at, show, hide, onFrame}) | a second screen inside one page: one history entry per place, popstate in both directions, Escape, and focus returned to whatever opened it |
afui.frame({onHead}) | what the window frame around your page should say about it — title, status — and whether it draws a head at all, so a framed page stops drawing a second one |
runtime.openExternal acknowledges handoff of an opening request. A remote
browser’s window.open with noopener,noreferrer returns no window handle even
when it succeeds, so a null return is not evidence of popup blocking. AFUI keeps
those isolation flags; remote handoff cannot confirm that a tab is visible. A
framed session’s sandbox allows popups and lets them escape it, so the tab
opens as an ordinary page of the person’s browser rather than failing inside
the frame.
See the HTML window-open steps.
These fit narrower shapes. Reach for one only when your page has that shape; each has a more common alternative that is usually the better fit.
| Primitive | What it is | When it applies |
|---|---|---|
afui.autosave({save, baseHash}) | debounce, one save on the wire at a time, base-hash writeback, and a 409 reported as a conflict rather than an error. A value typed while a save is in flight waits — only the newest waiting value is kept — and goes out against the hash that save’s reply returned, so the server never sees a second save made against a hash it has already moved past. On a 409 the waiting value is dropped and onConflict decides what happens to it. pending() is true while anything is unsaved: debounced, on the wire, or queued | a field that saves as somebody types. An explicit save control needs none of it |
afui.whileVisible(run, ms) | poll only while somebody is looking, and refresh at once on return; stop() is final, and a later tab switch does not undo it | a page that has to poll something AFUI does not carry. A page whose Provider can publish retained state should receive that instead |
afui.end() | end this session from inside its own page — the browser side of SESSION_END_PATH, so whoever created it sees the same Closed as a shut window | a page with its own “done” control. Otherwise the window, the host and afui session close are the ways out |
runtime.rows: a window onto a long sequence
Every page showing a long, changing sequence does the same work: register the
key first and fetch second, remember the revision, refetch only the visible
range when it changes, send the hashes of the rows already held, abandon a
request whose range has been scrolled past, and bound how many rows stay in
memory. rows does that, and nothing about the wire: you give it a fetch
that turns your contract’s action and reply into one shape.
const store = runtime.rows({
// knownHashes[i] is the hash of the row held at first + i, or 0.
fetch(key, first, count, knownHashes, {signal}) {
// resolve to {revision, count, rows: [{index, hash, value?}], next?}
// A row without `value` means its hash did not change.
},
chunk: 200, // most rows requested at once
keep: 2000, // most rows held per sequence
});
const seq = store.open('lines', {
watch: true, // register the key as a topic (the default)
onChange(info) {}, // rows or count changed; info.reset: everything was discarded
onTopic(payload) {}, // optional; the topic payload, unchanged
});
seq.need([[first, count]]); // what is shown now; replaces the previous declaration
seq.get(index); // the row's value, or undefined
seq.count; seq.revision; // null until the first reply
seq.close();
open registers the watch before anything is fetched; only need fetches.
The topic is the watched value of the key, published with
UiAudience::Watching(key); a shared value of the same key is not the topic. A
reply that ends early (a byte budget) says where to continue with next, and
the next request starts there. A reply with a different revision discards the
held rows and reports reset. A failed fetch is tried again after a second,
and a closed sequence is not. The cache is a bounded copy of remote rows; it is
not application state.
A complete small example: a list of 100000 lines the provider serves by range.
const runtime = afui.connect({});
const store = runtime.rows({
async fetch(key, first, count, knownHashes, {signal}) {
const reply = await runtime.request({type: 'lines', key, first, count, knownHashes}, {signal});
return {revision: reply.revision, count: reply.count, rows: reply.rows, next: reply.next};
},
});
const lines = store.open('log-1', {onChange: () => view.refresh()});
const view = afui.list({
viewport, content, rowHeight: 20,
create: () => document.createElement('div'),
render(element, index) { element.textContent = lines.get(index) ?? ''; },
onRange: (first, count) => lines.need([[first, count]]),
});
lines.need([[0, 50]]);
// once the first reply gives lines.count:
view.setCount(lines.count);
afui.list: only the rows that can be seen
afui.list({viewport, content, rowHeight, create, render, onRange}) windows a
large number of equal-height rows. You create the scrolling viewport and its
one child content; the kernel sets content’s height and each row’s
position, height and position: absolute, and leaves everything else to your
stylesheet. Rows are create()d on demand and reused as the page scrolls;
render(element, index) should write only textContent and attributes.
onRange(first, count) reports the visible rows plus a screen above and below,
after a short pause, whenever they change.
setCount(count, anchor) sets the number of rows; passing
anchor = {from, to} after rows were inserted above the view moves the scroll
position by the inserted height so what the person is reading does not jump.
refresh(), scrollTo(index), first() and destroy() do what they say.
A browser limits one element’s height: past 15,000,000px the count is cut to fit
and list.clamped is true; there is no coordinate scaling. Keyboard handling is
yours — call scrollTo from your own selection logic.
The kernel does not know trees, tables, files or terminals. A page whose data is a tree turns its own structure into row numbers.
There is deliberately no location.hash helper. Hash state differs from page
to page — repeated keys or not, which entry to evict — and a primitive that has
to be worked around is worse than none: the next person tries it first and
then writes theirs anyway.
afui.connection is the one primitive with a vocabulary of its own, so it is
worth a paragraph. The runtime’s connection state is connecting, live,
reconnecting or closed. Only three of those are ever handed to
onConnectionState: connecting is where every page starts, so there is
nothing to announce — afui.connection paints it when you call it, and
runtime.state reports it. A handler with an else if (state === 'connecting') arm has an arm that never runs. The word lands on data-afui-connection, which
the baseline stylesheet dresses; the wording stays yours, and a line that
also carries your own messages passes no wording at all and keeps its text.
onConnectionState({state, reason, detail}) gets reason with closed, and only
then: the error code of why the runtime will not reconnect, and detail with it when the
refusal came with structured detail. A native client’s
ConnectionState::Closed { reason, detail } carries the same values; its states are
Connecting, Live, Reconnecting and Closed.
reason | What happened |
|---|---|
ui_session_ended | the session is over |
ui_viewer_replaced | this viewer identity connected again elsewhere, such as the same page opened in another tab; reconnecting would only take it back |
ui_runtime_closed | the page called runtime.close() (a native client, close()) |
ui_protocol_unsupported | the hello named a protocol the runtime does not speak; the page’s Error carries supportedProtocol and offeredProtocol, a native client’s ClientError::protocols carries both, so the side that is out of date can be told |
view_major_unsupported, view_minor_unsupported, view_extension_unsupported, view_panel_undeclared, view_implements_invalid | the session declined the connection after reading its hello; detail says what it required and what is lacking |
a refusal’s code, such as ui_limit_exceeded or ui_protocol_invalid (a hello without a viewer or instance identity, or not a hello at all) | the runtime refused the connection |
The runtime says why it ends a connection in one closed frame: the
reason above and a message worded for a person. A refused connection gets
that frame and nothing else; onRejected is only for a single frame or
request the runtime refused while the connection goes on. A
ui_keepalive_timeout close is not final, so it is never handed over: the
runtime connects again. A bytes connection closes the same way, and also with
ui_instance_mismatch when it names another instance of its viewer, or
ui_viewer_left when its viewer’s grace period ran out.
A request still in flight when the runtime closes fails with the reason as its
code and the close’s message; a local close uses its own wording.
afui.connection(element, words) returns a function that takes the same
{state, reason, detail} object onConnectionState is given, and nothing else, so it
can be passed as onConnectionState itself.
The same object is dispatched on window as the event
afui:connection-state, whose detail is {state}, or {state, reason}
when closed, with the refusal’s detail as well when it came with one. It is for script in the same window that cannot reach the value
afui.connect returned, or its callbacks: a script a host injects into the
page is one.
This is not a framework and will not become one. There is no template here,
no DOM diff and no store for page state; every text write is textContent and every
element comes from you. A primitive that needed a third-party library would not
be collected — it would be declined.
The boundary is unchanged: a frontend still cannot supply JavaScript. This
source reaches a browser only because you spliced it into your own trusted
runtime. socketUrl, generic request wrappers, raw channels, and SSE helpers
are intentionally not exposed: they would recreate a second UI protocol beside
afui.connect().
A second screen inside your page is a place
The moment your page opens one record over its list, it has made a second screen — and at the width these sessions are opened at most often, that record covers the list completely. A person can then ask to leave it with the system’s own back gesture, the key that closes things, a control you drew, or the navigation control of a window frame your page may be running inside. They have to be one gesture with one result. A page that pushes no history entry loses the first outright: back leaves the whole page from under the record, which on a phone is the gesture people reach for first. A page that pushes one per disclosure loses it the other way, and leaving takes a dozen taps.
afui.place is that one entry and every one of those ways in and out of it. It renders
nothing: show and hide are yours, because whether a place is a pane beside
the list or a screen over it is a question about your width and your content.
Enter it after the place is on screen and before you write it into the
address — what is pushed is a duplicate of where the person already was, so the
entry below keeps your page as they left it and your own replaceState writes
the place into the new one.
at and show are a pair rather than one “you left” callback because a place
is somewhere a person can arrive: going forward again, or opening an address
that already names it. at is asked what the current address names; whatever
it returns is handed to show, and arriving that way pushes nothing.
Read what at returns off what your page has already been given, not off the
address as a name to fetch. An address is a person’s to edit, and a place
restored by handing a raw identifier to a typed call is a page asking for
something nobody listed.
Do not draw a second head inside a frame
A live page tends to draw a header: the program’s name, what the session is on, and a word about how it is going. A framed session then shows it twice — once in the frame’s own head, which already has the first two from the listener, and once again underneath in the page. On the width these sessions are opened at, the second one is a row of the screen spent on nothing.
afui.frame is the ask. onHead(true) means there is a head out there; a page
that hears it hides its own and sends up what a frame cannot know:
frame.title(text)— where the page is now.nullsays nothing and leaves the frame showing whatever the session itself is on. A place is the usual reason it changes: set it as you enter and clear it as you leave.frame.status(text, state)— one short line about what is being shown. The optionalstateis one of AFUI’s own connection words, and a frame that knows the vocabulary dresses the line exactly as your baseline would.
Identity is never sent. Whose program this is and what the session is on are the listener’s word, and a page repeating either into a head it does not own would be a page naming itself in somebody else’s chrome. That is also what makes the rest safe to hand over: a card cannot be made to introduce itself as something else.
afui.place uses the same channel for the one navigational fact — that your
page is somewhere with a way back — and a frame with navigation to offer draws
the control the person’s window already keeps in that corner, reaching you as
onFrame({navigation: true}).
Keep drawing your own head and your own way back. Your page is delivered in its own window and as a direct link as often as it is framed, and in those there is no head but yours. What these callbacks are for is dropping the second one, not having none.
Nothing else crosses. The frame cannot read your page and does not consume what it is showing; it takes a boolean and two lines of text, and the only thing it ever sends back is a request to leave the place you said you were in. Both lines are flattened and capped before they are shown, so they are words and never a lever on the frame’s own layout.
Decision controls: declaration is theirs, binding is yours
If your page returns an answer that moves money, runs a statement, or otherwise cannot be taken back, a replaced template controls the markup — and therefore controls which button is labelled “approve”. Do not solve that by restricting what a template may replace. Solve it by keeping the decision out of the template:
- The template declares what a control is for — a semantic attribute you
define, for example
data-yourprovider-decision="approve". - You decide what it does. The map from that declaration to the real route
lives in your own runtime, injected under a per-session
UiCspNoncewithscript-src 'nonce-…'in the policy. A frontend cannot supply that script, cannot hide it in a template, and could not run it if it did — it does not know the nonce.
These rules make that hold up:
- Match the declaration exactly, not by prefix.
approve-allstarting withapproveis how a page passes a completeness check and then opens with a control bound to nothing. - An unrecognised declaration binds to nothing — it does not fall back to something plausible.
- A page that declares no decision control refuses to open. Erroring is correct; a window whose buttons do nothing is worse than no window.
- Absence is refusal. Make the closed window, the lapsed credential and the refuse button all mean no, in a match with no wildcard arm — so that adding an outcome later cannot compile until someone decides what it means.
What remains is that a trusted template can mislabel a control it declared. That is the accepted model: the person enabled that exact fingerprint, and any later byte revokes it. Encryption of intent is not on offer; what is on offer is that the binding is never up for grabs.
You do not write those rules again
UiDecisionRuntime generates the script; you own the tag it goes in, because
only you know this session’s nonce.
let runtime = UiDecisionRuntime::new("data-myprovider-decision")?
.with_status_attribute("data-myprovider-decision-status")?
.with_decision("approve", "approve")?
.with_pending_text("approve", "Approving…")?
.with_decision("refuse", "refuse")?
.with_pending_text("refuse", "Refusing…")?;
let page = UiPage::builder(&frontend)
.entry("templates/page.html.j2")
.fallback(BUILTIN_PAGE)
// The same list, read back as the page's contract.
.requires_decisions(&runtime)
.runtime_marker("<!-- myprovider:trusted-runtime -->")
.runtime(Some(format!(
"<script nonce=\"{}\">{}</script>",
nonce.as_str(),
runtime.source()
)))
.render(&document)?;
The declaration vocabulary, the routes, and every word a person reads are yours. AFUI carries no default text and never will: “Approving…” and “Sending payment…” are the same moment in two domains, and a library that guessed between them would be writing your product copy.
requires_decisions is the reason the runtime and the page cannot drift: add a
decision to one and the other stops rendering until it catches up. Underneath
it are checks you can also use directly —
requires_attribute_values(attribute, values) for one attribute’s vocabulary,
and requires_attributes(names) for a contract whose vocabulary is the
attribute names themselves. Both match the same way requires_elements does:
the whole value, and only on an element a browser would actually render, so a
declaration surviving in a comment or inside <template> does not count as a
control anyone can press.
At least one carrier per value, not exactly one — a runtime binds every control it finds, so an approve button at the top of a long page and another at the bottom is a page that works.
Partials the Provider has never heard of
A frontend that restructures a page needs partials of its own, and every
template has to be registered before an {% include %} resolves:
UiPage::builder(&frontend)
.entry("templates/page.html.j2")
.fallback(BUILTIN_PAGE)
.template("templates/layout.html.j2", BUILTIN_LAYOUT)
// Everything else the frontend put under `templates/`.
.override_templates_under("templates", ".j2")?
Templates already named keep their own fallbacks; the rest are registered override-only, so a partial that disappears between discovery and render fails the page rather than silently resolving to a built-in of the same name.
What is shown must be what happens
If the answer commits to something resolved earlier — a payment plan, a quoted fee, a statement — carry that identity in your own code from the thing you stored, never from anything the page could influence. The template renders the plan; it does not get to say which plan.
A link inside a window opens outside it
A window is a bare web view: no address bar, no tabs, nothing to navigate
away to. That is what makes it a window rather than a browser, and it is also
why a page must never let a link navigate inside it. A person who followed
one would be on a site whose address they cannot see, in a surface that has
just lost the session it existed for — and the content that put the link
there was usually not the Provider’s own. A page that shows remote content
therefore renders links as text with a visible destination, and when a person
asks for the page itself, calls runtime.openExternal(url).
What happens then depends on where the person is. In the local window the
host opens the URL in the system default browser, where the address bar and
the browser’s own protections apply. In remote access — the person’s own
browser, reached through afui host serve or a link — a new tab is
opened right there; the host never opens anything on the machine the runtime
runs on for someone who is not sitting at it. The runtime tells the page which
case it is (remote on the ready frame), and the host enforces the
distinction again on its side, refusing open_external from remote access
with ui_open_external_remote.
A surface is remote unless it proves it is local. Arriving without AFUI’s
proxy proves nothing: your own listener behind a UiMount, a tunnel, or a
mapped container port reaches the runtime straight from another machine. So
when AFUI opens its own window — through UiDeliveryPlan, open_window, or
afui host open — it puts a per-session key in the URL’s fragment, which
never reaches a server or a log, and the page kernel hands it back in the
runtime hello. Only that key makes a surface local, and a connection through
AFUI’s proxy, which marks every request it forwards, is remote even with it.
A window you launch yourself with UiWindow::launch on a bare access URL has
no key, so its links open as remote access would.
The host, not the page, decides what is eligible: a plain http or https
URL of readable length, nothing else. javascript:, data:, file: and
mailto: are refused as ui_open_external_url_invalid before any opener
runs, and the URL is handed to the platform opener as one argument, never
through a shell. A request is not a call: nothing is resent after a wire drop,
because a link a person clicked once must not open twice. The promise resolves
to {opened, via} or rejects with a code.
If your UI reads browser storage
afui host serve either puts every session on a path of its own origin or
gives each session an origin of its own, and only the second lets a framed UI
touch localStorage.
By default every session is a path on the listener’s own origin and the frames
are sandboxed without allow-same-origin. That gives each one an opaque origin,
which is what keeps them from reading each other — and what leaves them with no
browser storage at all. A third-party client that reaches for storage unguarded
refuses to load there.
afui host serve --session-origin-host <HOST> gives every session an origin
of its own, s-<credential>.<HOST>. Isolation is then the browser’s own origin
boundary, the frame is same-origin with itself, and storage works. It asks
something of whoever runs the listener rather than of you: *.<HOST> has to
resolve to that machine, and behind TLS the certificate has to cover it.
(localhost needs neither — browsers resolve *.localhost themselves.)
So: your UI is not required to avoid browser storage, but a UI that depends on
it is one that only works when the person serving it arranged that. Say so in
your own documentation, and remember the deliveries that never had the problem —
its own window and afui host open. A direct link redirects to a path-isolated mount, so it has no storage either.
Your page must rebuild itself from its own URL
A host may embed a session in a frame or WebView. Reopening a lapsed view replaces its credential and renderer instance. Any UI-local state disappears; the runtime restores the provider’s retained state but cannot infer that an expanded disclosure or half-filled local form is domain state. Persist anything that must survive through an explicit typed action.
The host does not consume provider DOM state. It must preserve origin and storage isolation rather than reaching into other surfaces to copy their contents. If view state must survive, make it provider-owned state with the same typed validation as any other write.
So the requirement is on you: your page has to be able to reconstruct what it is showing from its own URL alone, the same way a browser tab already has to survive a reload. AFUI’s own contract is that the address does not change underneath a session that is still being watched: a session’s mount stays the same while its view is live or merely warning. Endings that come from outside your code are the ones listed in Ending a session from outside it. The one moment your page has to answer for is being loaded fresh at a new address after its own view lapsed and someone asked for it back.
One page, handed over, waited on
Everything above composes, and for a page that is handed over and waited on the
composition is always the same sequence. UiSurface is that sequence:
let active = UiSurface::<Decision>::new("myprovider", "confirm")?
.with_subject(subject)
.with_app_icon(app_icon)
.with_page_policy(policy)
.on("approve", |_fields| Decision::Approve)
.on("refuse", |_fields| Decision::Refuse)
.with_answer_page(|decision, recorded| decided_page(decision, recorded))
.merge(my_domain_routes)
.start(plan, page, stylesheet, &frontend)
.await?;
let facts = active.facts();
let outcome = active.wait().await?;
A submission arrives as BTreeMap<String, String> and is parsed by a function
you wrote. AFUI does not learn what a field means, and this layer will never
gain validation, field types, conditional display, layout, or grouping.
Anyone who needs those needs a Router, which they have always had. with_answer_page
is called with what was answered and whether that answer was the one that
counted — false for a click that arrived after the decision, which is the
only honest thing to show the person who made it.
This is deliberately the last layer, not the first. Everything it does is reachable directly, and a page that does not fit this shape should use the pieces rather than bend to it.
Reserved names
In any namespace shared with a Provider page, names starting with afui belong
to AFUI and everything else belongs to the Provider. AFUI never takes a name
outside that prefix, and a Provider never needs to avoid anything else.
| Namespace | Reserved |
|---|---|
| Routes | the __afui/ prefix |
| Fragment | afui-window=, one-shot and erased on load; the fragment is otherwise entirely the page’s |
| Query | afui_launch_id |
| Tab storage | keys starting afui- (window key, viewer identity) |
| Attributes | data-afui-connection; data-state is the Provider’s own |
window events | afui:connection-state (see afui.connection) |
| CSS | custom properties --afui-* |
| Proxy header | afui-remote-view |
| Template | the single global afui (the page’s data is afui.document), and the MiniJinja built-ins safe and tojson, which the engine’s safety boundary removes and which cannot be registered |
| Shared and watched value keys | nothing |
AFUI’s own routes, from inside your page
Every session reserves the whole __afui/ prefix under its own credential.
AFUI uses it for the resolved application icon, the base stylesheet, ending,
snapshots, the typed runtime, and offered bytes. Provider routers must not claim anything below that prefix.
A UiPage render carries the paths a template may render directly as a
reserved afui global:
<link rel="icon" href="{{ afui.app_icon_path }}" type="image/svg+xml">
app_icon_path, base_style_path and end_path are relative to the session
root, which makes them resolve under the session’s own credential in every
delivery. afui is
reserved: an extension that registered that name is refused, because a replaceable layer may not redirect AFUI-owned behavior.
From Rust they are APP_ICON_PATH, BASE_STYLE_PATH and SESSION_END_PATH,
available without the session feature.
The runtime and bytes paths are deliberately absent from the template global.
Trusted JavaScript uses afui.connect() and its bytes methods; Provider code
uses UiBytesRef. Neither side names transport paths or builds their URLs.
Your surface will live in someone else’s pane
A surface does one job. Publish a list, a selected item’s details, or an editor as separate surfaces when each can be useful in its own pane. The host owns splits, tabs, navigation between panes, and layout persistence. Do not draw a second window manager inside your page.
Focus identifies what is selected; it does not carry the selected item’s data. Fetch that data in the provider. Publish complete state so a native renderer can present the same surface without scraping the page. A one-shot decision surface still ends after submission and returns its result to its caller; a list can remain open for repeated actions.
Stable host theme tokens
An embedding host injects its theme by evaluating afui.setTheme(tokens) in
the surface’s own page after the kernel loads. The object maps CSS custom
property names to string values: the CSS projection of the host’s resolved
theme, ResolvedTheme::css_tokens(). Each call replaces the whole host theme:
a known name the call does not carry is removed from the root element, so the
page falls back to its baseline for it, and switching from a full theme to an
empty one leaves nothing behind. The kernel validates every name and value
before it changes anything: the argument must be an object of strings whose
names match --afui-[a-z0-9-]+. A well-formed name the kernel does not know
is from a newer theme and is ignored. Inline custom properties take
precedence over both light and dark floor defaults. The host draws its native
renderers from the same resolved theme.
Rust hosts resolve a theme with theme::resolve_theme for the active scheme,
after stacking any themes with theme::overlay. Check the returned
diagnostics; they never stop resolution. Call theme::derive_color_family
for a color supplied by application data.
The allowed names are the variables listed in The floor your page stands on.
The runtime exposes afui.themeVersion as 4. A page without the AFUI
runtime can declare the same contract on its root element with
data-afui-theme="4".
Pages reference these names with var(...); they need no host-specific CSS.
Token values are trusted host presentation settings, never provider actions or
focus data. This API does not accept selectors, stylesheets, or layout hints.
Surface declarations and focus delivery
Attach a UiSurfaceDeclaration with UiSession::with_declaration before
mounting a typed surface. It carries the provider’s type name and version,
state/action/reply schema references, a cardinality, and the panels a host
may mount:
{
"type_name": "inspector.inventory",
"version": "1",
"cardinality": "multiple",
"schemas": {"state": "schemas/state.json"},
"default_panel": "inventory",
"panels": [
{"id": "inventory", "title": "Inventory",
"reads_focus": ["inspector:item"], "requests_focus": ["inspector:item"]},
{"id": "detail", "title": "Detail", "reads_focus": ["inspector:item"]}
]
}
- A panel is one independently mountable view of the same session. Its
idis ASCII letters, digits,-and_, unique within the declaration;default_panelmust name one of them. A host opens a panel by adding?panel=<id>to the session URL; page code reads it asafui.panel(). - Each panel declares the focus keys it reads and the keys it may request.
Focus keys have the form
provider:key. cardinalitytells the host how to address instances of the type:multiple(the default when absent) addresses each session by its own surface ID;singletonmeans one live session per type in a host context, addressed by type and panel. AFUI publishes it; enforcing it is the host’s job.
AFUI validates bounded references and names; it does not fetch or interpret
schemas. The declaration is published in the registry and in afui host list;
runtime ready.metadata carries the same session identity, declaration and
ownership context. Page clients can observe that handshake through
afui.connect({onReady(metadata) { ... }}).
Host focus uses a separate runtime frame:
{"kind":"focus","focus":{"values":{"inspector:item":"item-42"}}}
Each push replaces the entire selection map for that surface, so omitted keys
are cleared. The host sends only keys some panel declares in reads_focus.
AFUI rejects pushes with any other key, retains the newest map, and restores it
on reconnect.
Providers observe it through runtime.subscribe_focus(); pages receive
onFocus(values) from afui.connect(). Focus is independent of state and
ordered events: no revision or event sequence establishes an ordering between
them. The host owns the tab’s full selection map and inter-surface routing.
Native runtime consumers
runtime-client is independent of session: use it with default features
disabled in a host that consumes surfaces without serving them.
runtime_client::UiRuntimeClient::connect(access_url, client_id, host) starts
one reconnecting task on the caller’s Tokio runtime. Give each client lifetime
a unique identity; clones share that identity and one wire.
subscribe_values()(shared values),subscribe_watched_values()(watched values, for the keys this client watches) andsubscribe_focus()retain only the latest value per key.watch_key(key)registers interest in a key and returns aWatchHandle; dropping the handle withdraws that registration. Registrations of one key add up, so a host showing several folders of a tree, or several panels, never has one part cancel another’s. The client sends its watch set again after a reconnect; a key whose last registration is dropped also leaves the watched value table.set_value(key, payload)sets a droppable viewer value andclear_value(key)clears it, the page’sruntime.setValuewith the same rules. Both return at once and are checked where they are called: an empty key fails withui_value_key_invalid, and a payload over the per-value limit or a new key beyond the per-viewer count withui_limit_exceeded(updating a key that holds a value takes no new slot; clearing one that holds none does nothing). The limits are the baseline until the session’s own arrive with the first connection. After the client closed, both fail withui_runtime_closed. Writes are coalesced for the session’s local coalescing interval: the Provider receives the latest value of each key once per interval, and every value again after a reconnect.rows::RowsStoreis the page kernel’sruntime.rowsfor native hosts, with the same flow and the same rules:RowsStore::new(&client, fetch, options), thenopen(key, watch)registers the key before anything is fetched andSequence::need(ranges)is what fetches.fetchturns your contract into aRowsPage(revision,count, rows withvalue: Nonefor an unchanged hash, andnext).Sequenceexposescount(),revision(),get(index),topic()andchanges(), and dropping it cancels its request and withdraws its watch. There is no list here: a native host draws rows with its own list control.subscribe_metadata()receives thereadyhandshake.subscribe_connection()reportsConnecting,Live,ReconnectingorClosed { reason }, with the page’s reasons (seeafui.connection); a request in flight fails as it does on a page.subscribe_events()carries messages, restarts, requests from the Provider and their cancellation. A slow receiver gets an explicit broadcast lag error; it must rebuild its domain projection or reconnect rather than pretending no events were missed.send_message(payload)sends a message to the Provider.request(payload)returns a request handle;result()gives the raw payload,json::<Reply>()decodes it, andcancel()cancels it.request_value(value)serializes the request for you, andcall_operation(name, input)calls one of the Provider’s operations. Pending requests keep their identity across reconnects.request_focus(values)is an ordinary correlated request from the default panel;request_panel_focus(panel, values)names the panel that asks. It admits only that panel’srequests_focuskeys, bypasses the provider’s action inbox, and waits for the host’s answer.request_panel_focus(panel, values, disposition)also says how to open the request:UiFocusDisposition::Default,NeworBackground(see Opening a focus request).request_focus(values)asks withDefault.- Hosts read
subscribe_focus_requests(), a latest snapshot of outstanding calls, each carrying thepanelthat asked and thedispositionit asked with, and answer withanswer_focus(client_id, request_id, accepted). Cancelled calls leave that snapshot. The host routes selected values throughpush_focus()to surfaces that declare the corresponding read keys. read_bytes(reference, offset, len)andread_all(reference, max_bytes)read offered bytes with bounded memory over a bytes connection;release(reference)releases it (returning nothing, at once, and doing nothing after the client closed; see Bytes for how a release is delivered), andoffer_bytesoffers bytes to the Provider. A host that fronts a session server names the panes actually visible withUiControlClient::attend.
Page code uses runtime.requestFocus(values, {signal, panel, disposition}); panel
defaults to the page’s own ?panel= and then to the declaration’s default. The
returned promise resolves to {accepted: true} or {accepted: false}. Cancellation, terminal
errors and reconnect deduplication are the ordinary request contract.
Opening a focus request
A focus request says how the host should open what it selects:
disposition | Meaning |
|---|---|
default | The host’s ordinary way, which may reuse a temporary place. Omitted means this. |
new | Open in a place of its own that is kept, and go there. |
background | Open in a place of its own that is kept, and leave the current focus where it is. |
On the wire it is a string. A value the runtime does not know is read as
default and the request is answered as usual.
Only a renderer asks for anything but default, from a person’s gesture: the
Provider’s own focus requests (UiSessionRuntime::request_panel_focus, a
script’s focus_request) are always default, and the runtime sets that itself
rather than trusting the sender.
A host says what it can distinguish in its hello, per focus key, as a map of
the dispositions beyond default (which is implicit):
UiRuntimeClient::connect_host(access_url, id, dispositions, viewer) with
UiFocusDispositions::default().with("inspector:item", [New, Background]), or
focus_dispositions_json of the wire Hello: {"inspector:item": ["new", "background"]}. The runtime gives the union over its connected hosts to every
viewer, in its welcome and again whenever it changes. A native renderer reads it
with subscribe_focus_dispositions(); a page reads
runtime.focusDispositions(keys), which answers default plus each value every
one of keys offers, so an action that names several keys is offered only what
all of them can open. A key no host declared has only default, and a request
that asks for more than its keys offer is delivered to the host as default.
Native consumers use HTTP session URLs. A host doing encrypted remote access supplies its authenticated loopback proxy URL to both the native renderer and the page renderer. This tier does not select the host’s TLS trust policy or open a listener of its own. URL credentials are withheld from transport errors.
Run scripts/test.sh native-client for the three-surface fixture through
both direct sessions and real per-origin proxies. It drives both the native
client and the actual page kernel over real WebSockets (Node 22 or later),
including call reconnect deduplication, cancellation, state coalescing, focus
and byte bodies. This proves transport behavior, not browser layout or visual
quality. The fixture is also part of unit and all.
Snapshot and restore
Before tearing down or shelving an active surface, a host asks the provider for a snapshot:
POST <access_url>__afui/snapshot. Register the callback with
UiSession::on_snapshot; it returns a ProviderSnapshot.
The response envelope is UiSnapshot:
{
"taken_epoch_ms": 0,
"declaration": { "type_name": "afui.view", "version": "1", "default_panel": "inventory", "panels": [{ "id": "inventory", "title": "Inventory" }] },
"requires": { "view": "1.0" },
"data": { "views": { "inventory": [] } },
"view": { "media_type": "text/html", "content": "..." },
"restore": {
"state": {},
"relaunch": { "argv": ["program", "arg"], "cwd": "/dir" }
}
}
Every field except taken_epoch_ms may be absent.
- Declaration: the session’s
UiSurfaceDeclaration, when it has one, so a host can file the snapshot under the right type and panels without a separate lookup. - The live session’s view requirements are carried in
requires. Hosts use them to judge whether they can render the saved declarative data. If the renderer is incompatible, the host can show the staticviewwhen supplied. - Data: structured, provider-owned JSON a host can render natively or use
to reconnect.
ProviderSnapshot::datasupplies it; without it AFUI fills in the session’s latest JSON values by key. Binary values are left out. - View: a human-readable static document, present only when the provider
supplies
body_html. AFUI wraps the fragment into a complete document withmedia_typetext/html: no scripts, no external resources, theme variables with standard fallbacks. The host renders it read-only without script execution. AFUI does not synthesise a view on its own. - Restore: two optional sections.
stateis opaque JSON defined by the provider; the host preserves it untouched and hands it back when restoring.relaunchcontains the command line arguments (argv) and working directory (cwd) required to restart the provider process. Withoutrelaunchthe provider declares that the host cannot restart it. - Handoff upon restart: the host sets
AFUI_LAUNCH_FILEwith a private single-use restore file containing the previous session ID and saved state. The Provider reads its state throughsnapshot::restore_state()and registers withrestored_fromso the host can place the restored surface. - No callback: a provider that registers no snapshot callback still answers
with its declaration and the default
data, and novieworrestore. Hosts that possess independent launch information may still relaunch the provider without restored state.
Testing your UI through AFUI
Add AFUI to your [dev-dependencies] with features = ["test-support"]. It is
not in the default set and never reaches a release binary.
use agent_first_ui::test_support::{InstalledFrontend, stub_browser, write_attention_config};
InstalledFrontend::new(&workspace, "myprovider", "console", "1")
.with_frontend_id("custom")
.with_file("templates/page.html.j2", MY_TEST_PAGE)
.install()?
.trust()?;
trust() computes the fingerprint with AFUI’s own code, through the same
function AFUI trusts against. That is the whole point: a fingerprint
reimplemented in a Provider’s tests agrees with AFUI today and goes on agreeing
right up until AFUI’s algorithm changes, at which point that suite fails for a
reason it is not about. Keeping AFUI honest about not drifting
is AFUI’s job; yours is to prove your UI works.
Drive a live session through AFUI’s real wire with RuntimeClient:
use agent_first_ui::test_support::RuntimeClient;
let mut page = RuntimeClient::connect(&access_url, "integration-page").await?;
let state: Option<MyState> = page.opening_state().await?;
let reply: MyReply = page.request(&MyAction::Refresh).await?;
page.close().await?;
The test supplies only domain payloads. RuntimeClient owns the reserved path,
protocol hello, request identity, acknowledgements, JSON envelope, and
WebSocket framing. Do not reproduce those details in a Provider test any more
than you would reproduce the fingerprint algorithm. Both clients expose
request_with_progress; a synchronous process test uses BlockingRuntimeClient
so that callback can drive child stdin/stdout between typed progress and the
final reply without exposing transport identity.
The rest is arranging any suite would otherwise write for itself:
stub_browser records the URL instead of opening one, so window delivery is
testable on a machine with no screen. AFUI does not pass a Chromium binary the
session URL: it launches --app= on a private launch.html (0600) in the
window’s temporary directory, which moves on to the session URL with
location.replace, so the credential never appears in the browser’s process
arguments. A browser confined to a snap or Flatpak cannot read this machine’s
temporary directory, so it alone is still given the URL directly. stub_browser reads that page and records --app=<session URL> in
its place; a stub browser of your own behind browser_binary_path has to read
the launch page the same way to learn the URL; write_attention_config writes the idle
and grace periods you pass to where AFUI reads them, so a test can let a Link
lapse in a second instead of waiting fifteen minutes for the default; and
wait_for_session / wait_for_no_session poll the registry for a session this
process is not the one announcing.
Those last two are for a test that drives a Provider as a child process. In
a test that holds the session itself they buy nothing: announcing happens
inside attach, before the active session is handed back, so the entry is
already there on the line after start. Withdrawal is the direction that is
genuinely late — the entry goes when the handle drops — and both helpers block
the thread they are called on, so an async test reaches for them through
spawn_blocking rather than from inside a single-threaded runtime that the
session it is waiting for also needs.
Keep your own end-to-end tests driving the real library. RuntimeClient also
drives a real socket; what this removes is the arranging, not the proving.
AFUI’s own test gate
This is for changing AFUI itself rather than testing a Provider through it.
scripts/test.sh all runs the portable checks and binary smokes.
scripts/test.sh kernel runs only the JavaScript kernel regression checks,
which are also included in unit and all. scripts/test.sh browser runs one
optional real Chrome/Chromium smoke at a 360 × 640 viewport, checking iframe removal after attention expiry and
enforced CSP. The fixture uses the stock polling cadence with a 1-second idle
window and 3-second warning period. If no browser is available it reports a
visible skip. Set browser_binary_path in the launch file’s AFUI configuration
to choose an explicit executable.
scripts/test.sh release adds that browser check to the portable gate, and the
release workflow runs it on its Linux x86_64 leg.
scripts/test.sh webkit checks text reads and sibling/parent isolation through
the real mount listener plus a disposable local fixture. The fixed entrypoint
installs the driver from tests/package-lock.json and its matching WebKit. To
audit another engine, set AFUI_TEST_PLAYWRIGHT_MODULE to the installed
package’s ESM entry URL when it is outside the normal module search path. This
engine check supplements the Chromium gate; it does not claim validation on a
physical iPhone or iPad.
scripts/test.sh window-shortcuts checks native window closure: Command+W on
macOS, Ctrl+W and Alt+F4 on Windows/Linux, including process exit after closure.
It requires a desktop; Linux needs an X11 display, a window manager and
xdotool, and Windows needs an interactive desktop session rather than SSH
Session 0. Windows and Linux use Chrome or Chromium. The macOS fixture queues AppKit events
inside its own applet and does not require Accessibility permission.
Discoverable command-line providers
A provider executable may implement ui describe. Run it from the directory
whose availability is being checked, with any provider-wide arguments before
ui describe. On success it writes one UTF-8 JSON document to stdout and
returns zero. The command should complete promptly, including when the directory
is uninitialized. A host can treat an unsupported command, a timeout, or invalid
output as a CLI-only provider.
{
"schema_version": 1,
"available": true,
"surfaces": [{
"id": "review",
"title": "Review",
"icon": "checkmark.circle",
"shape": "watch",
"arguments": ["ui", "review"],
"declaration": {
"type_name": "afui.view",
"version": "1",
"cardinality": "singleton",
"default_panel": "queue",
"panels": [
{"id": "queue", "title": "Queue"},
{"id": "detail", "title": "Detail", "reads_focus": ["review:item"]}
]
}
}]
}
ToolManifest::write_stdout validates and writes this document. Surface IDs
must be unique within a manifest. available defaults to true. Use false
with unavailable_reason to explain a directory-local prerequisite while
keeping the surface descriptions visible. The optional tool_version
identifies the executable version. Unknown fields are ignored. An omitted or
unrecognized shape is treated as watch. A decide surface waits for a
person’s decision.
A host invokes the executable directly, appending the selected surface’s
arguments and any rendered form arguments to the provider-wide arguments.
The optional parameters object maps parameter names to LaunchParameter
descriptions. Each description has a label and may supply a default,
placeholder, choices, allow_custom, and a flag template. Choices
carry a label and value. A boolean value can turn a bare flag on or off.
Templates use {value} for substitution within an argument. Launch with
the host’s existing AFUI launch file and announce the declared surface.
Each declared panel can be mounted independently. A singleton shares one
provider instance across those mounts in the host context.
A host can use describe_tool for this probe: it appends ui describe to a
command the host built, runs it in its own process group without stdin or a
launch file, and kills the group after the timeout or 1 MiB of output. It
returns the validated manifest, or nothing for a CLI-only tool. Hosts do not
search the machine for tools; a person adds one or a workspace names it.