NE.Standard

Controllers

A controller is a UIControllerBase subclass — an observable object graph that a view's components bind to, and the surface a command runs against. Registering a route with application.Route<TView, TController> pairs the two; a route with no controller (application.Route<TView>) has nothing to bind and no commands.

Observable state

UIControllerBase derives from RecursiveObservable. A [RecursiveMember] partial property generates the notifying setter and the path segment a binding resolves against:

internal sealed partial class CounterController : UIControllerBase
{
    [RecursiveMember]
    public partial int Count { get; set; }
}

A property can hold a nested observable object instead of a scalar — also [RecursiveMember], also partial, so a binding path can walk into it ("TableGroup.Striped"):

internal sealed partial class TableGroupContext : DemoGroupContext
{
    [RecursiveMember]
    public partial bool Striped { get; set; }
}

internal sealed partial class TableMainController() : DemoStandardController
{
    [RecursiveMember]
    public partial TableGroupContext TableGroup { get; set; } = new();
}

A collection of items is a RecursiveCollection<T> (T : RecursiveObservable), which forwards every item's own changes as collection path changes. Its property is [RecursiveMember(false)] — no setter is generated, because the collection is mutated in place (Add, Remove, indexer) rather than replaced. A collection of keyed items keeps an index by key: TryGet(key, out item), Remove(key) and Move(key, index) reach the row a command named without a loop:

[RecursiveMember(false)]
public RecursiveCollection<DemoDeploymentRow> Items { get; } = [.. DemoDeploymentRow.CreateDeployments()];

[RecursiveMember(false)] still registers the path segment but generates no setter — the same attribute an item's own Id needs:

internal sealed partial class DemoDeploymentRow : RecursiveObservable, IBindableItem
{
    [RecursiveMember(false)]
    public string Id { get; init; } = string.Empty;

    [RecursiveMember]
    public partial string Service { get; set; } = string.Empty;
}

A notifying Id would let an item be re-keyed after insertion, leaving the collection's internal lookup pointing at the old key — so Id is always [RecursiveMember(false)], never a plain [RecursiveMember].

Commands

[UICommand] marks a method the client can invoke:

[UICommand]
public void Increment() => Count++;
public UICommandAttribute() { }
public UICommandAttribute(string name)
public string? Name { get; }
public UICommandConcurrencyMode ConcurrencyMode { get; init; } = UICommandConcurrencyMode.Exclusive;
public int MaxConcurrent { get; init; } = 1;
public bool ShowsPending { get; init; } = true;

The optional constructor argument (or Name) is the external command name a view's OnClick/On refers to; unset, the client name is the method name. ConcurrencyMode is Exclusive (the default) or Background. Exclusive commands of one runtime run one at a time — a second waits for the first to finish, whichever command it is. A Background command waits for nothing: it runs alongside other background commands and alongside the exclusive command in progress. It runs alongside itself only as far as MaxConcurrent allows — one run at a time per runtime by default, since a second export or query beside the first is one nobody asked for. The server holds that count whatever the page sends: a run past it — another tab's press under PerClient, a hand-made call — is refused as a command on a closed component is, and told as already running rather than as not allowed (UIStrings.CommandBusy, ErrorHandling.CommandBusyMessage; UICommandBusyException). MaxConcurrent below one is an error, and it means nothing on an Exclusive command, which already runs one at a time. ShowsPending (on by default) lets the element pressed — a button, a row, a card, a submit — show it is working when the answer is slow; turn it off for a command whose wait the view already shows its own way.

Within one tab the two differ in what else can happen while they run. A tab talks to the server over one connection, which takes one call at a time, and whatever the tab sends after a press waits behind it:

  • An Exclusive command holds its tab until it ends. A value the reader types, a list scrolled to rows not yet loaded, a second command — each reaches the server only once the command has answered. Other tabs are not held.
  • A Background command lets go of its tab at once. The server answers the press with "accepted", runs the command on, and pushes its result — effects, changes, a failure's notification — when it ends. Until then the button still counts as pressed: OnClickShowingLoading keeps its spinner and a second press of the same button is refused. Values typed meanwhile land, lists load, and another command runs — a Cancel button can reach it. A lost connection ends the wait rather than leaving the spinner on, but not the command: it runs on the tab's stay on its runtime, not on the connection, so a page attaching again from the same tab is pushed its result. Its CancellationToken is cancelled when the tab moves to another runtime, when the runtime's retention runs out — or, under PerClient, the tab's own, away that long from a runtime other tabs keep — or when the runtime goes.

What was given before a press reaches the controller before the command either way, so a command that needs the value the reader pressed the button with reads it before its first await; a value that arrives while a background command awaits is there when it resumes.

A background command must not read-modify-write state another command also touches. A controller's properties are not locked — Count++ in two commands running at once can lose an increment, and a list one of them is rebuilding can be read half-built by the other. The rule of thumb: make a command Background only when it spends its time waiting on something outside (a query, an HTTP call, a long computation) and writes only state of its own — its result and its busy flag, say — that no other command writes at the same time. A second run of itself cannot while MaxConcurrent is one; raise it only for a command whose runs write nothing the others do. Every command that updates shared state stays Exclusive. What runs before its first await still holds the tab like an exclusive command, so a long computation goes behind an await of its own (Task.Run). Under PerClient one runtime serves every window of the client, so "another command" includes one raised from another tab.

Posted work and an attach wait for an exclusive command; the rest does not. Exclusive commands take turns, and so does work posted to the runtime — Context.Runtime.Post, an IUIBroadcast post, OnDetachedAsync, a session change made on another page — and a page's attach, whose OnNavigatedAsync and OnAttachedAsync run in a turn of their own, as does a language or theme the page switches to: none of them runs while an exclusive command is under way, from its first line to its answer. A tab reloaded while its command still runs attaches once that command ends; the old connection's closing cancels the command's token, and nothing else bounds the wait but the new connection's own. A command's body does not hold the runtime's lock, though, so a Background command, a value another tab types and an InvokeAsync from outside the runtime — a timer, a hosted service — still run beside it, on another thread. A command that writes what one of those writes too does that write through Context.Runtime.InvokeAsync, which it may await from inside itself. Posted work and the lifecycle hooks run the same way — in their turn but outside the runtime's lock — so the same helper works from a command, a post, a broadcast or OnAttachedAsync. Only an InvokeAsync action itself holds a lock: an InvokeAsync called from inside one — into this runtime or any other — throws InvalidOperationException rather than wait on a lock that may never come free (two runtimes awaiting each other); work for another runtime from there is Posted. Posted work's token is the runtime's lifetime, cancelled as the runtime is asked to go.

Work that outlives its tab is a job the runtime owns. A Background command outlives a dropped connection — a phone or a tablet drops its connection whenever its screen sleeps — but not its tab's stay: a reload or a switch to another page's runtime ends it (a closed tab's at the retention), so a reply streamed for a minute would stop half-written there. Context.Runtime.Start starts such work and returns at once: the job runs on the thread pool beside the runtime's commands, goes on while no page is attached — a page that attaches again finds it still running — and its token is cancelled only when the runtime is asked to go (its retention past, its session ended), which then waits for it to end. Start it from a command or later, not from initialization; inside it, Context is the runtime's own, not the starting command's. It writes through InvokeAsync, as anything beside a command does, and a failure goes to HandleRuntimeExceptionAsync:

[UICommand]
public void Send()
    => Context.Runtime.Start(async cancellationToken =>
    {
        await foreach (string token in _model.StreamAsync(Prompt, cancellationToken))
            await Context.Runtime.InvokeAsync(() => Reply += token, cancellationToken);
    });

A Stop button cancels a job through a token source of the controller's own, linked to the one the job is given.

A page has one service scope, and every command shares it. The controller, its scoped dependencies and a scoped command filter are resolved once per runtime, so a scoped DbContext injected into the controller is the same instance for every command the page runs, for as long as the page lives — often hours. Two commands using it at once (a background command beside another command) fail with EF Core's "a second operation was started on this context", and a context that lives that long keeps serving tracked entities that are stale by then. Inject IDbContextFactory<T> (AddDbContextFactory) and create a context per command:

internal sealed partial class ReportController(IDbContextFactory<AppDb> dbs) : UIControllerBase
{
    [UICommand(ConcurrencyMode = UICommandConcurrencyMode.Background)]
    public async Task ExportAsync(CancellationToken cancellationToken)
    {
        await using AppDb db = await dbs.CreateDbContextAsync(cancellationToken);
        Rows = await db.Orders.ToListAsync(cancellationToken);
    }
}

A command may be static — discovery covers static methods deliberately, since a method touching no instance state is exactly what the analyzer asks to be made static.

A command's parameters come from the arguments a view's On/OnClick call names, matched by parameter name; a value the client did not send falls back to the parameter's default, then to null/default for a nullable or reference type, or throws if the parameter is required. CancellationToken, if present, must be the last parameter and is supplied by the runtime, not by the client. A command may return:

Return type Effect
void Always succeeds, no effects.
UICommandResult Whatever it says.
Task / ValueTask Awaited, then always succeeds, no effects.
Task<UICommandResult> / ValueTask<UICommandResult> Awaited, then whatever it says.

UICommandResult.Ok(effects) and UICommandResult.Fail(error, effects) are the two factories — a failed result must carry an error message and a successful one must not. Effects is a list of ClientEffects the client applies after the command's own changes; see interactions and effects for what a ClientEffect can do.

Arguments from the view

OnClick(command, params KeyValuePair<string, UIActionArgument>[] arguments) and the plain On overload take named arguments built with UIAction's static helpers:

new ButtonComponent()
    .OnClick(nameof(TableExamplesController.RestartRow), UIAction.ArgCurrentItemKey("id"))
[UICommand]
public void RestartRow(string id) => ActionGroup.Restart(id);
Helper Resolves to
UIAction.Arg(name, value) A literal value.
UIAction.ArgCurrentItem(name) The current item — inside an item template, the row itself.
UIAction.ArgCurrentItemKey(name) The current item's key; in a group header, the key of the row the header is drawn from.
UIAction.ArgGroupKey(name) The current item's group (IBindableGroup.Group) — in a group header, the group it heads.
UIAction.ArgRoot(name, path) / ArgParent(name, path) / ArgRelative(name, path) A binding path, in the named scope: Relative is the component's own — in a row, the row; Parent the scope around it — the row for a menu inside the row, the list's scope (the controller at the top) for a control straight in the row.
UIAction.ArgEventValue(name, index = 0) What the event carries after the keys that address its component — the index a dragged row was dropped at, or indexed dynamic event values such as an inline trigger's prefix, scope and query/item key.

Every event method takes the same three shapes: bare, with these arguments, and …Literal with plain values (OnClickLiteral, an input's OnChangeLiteral/OnBlurLiteral, OnSubmitLiteral, a host's row events — OnItemOpenLiteral, OnItemMoveLiteral, OnItemRemoveLiteral, a tab's OnRemoveLiteral — and a dialog's OnCloseLiteral), and so do the add-ons' (a chart's OnPointClickLiteral, a grid's OnQueryChangeLiteral) — but for a picture's upload (CodeInput's OnImageUpload, a node's OnImageUpload), whose command needs the upload's own keys to answer. A row's own press takes its key in one call on a button, a surface or a file tile: OnClickWithItemKey(command) passes it as id.

There is no "current item index" argument — an item is addressed by key, so the click site never carries a position; ArgCurrentItem/ArgCurrentItemKey are what a row-level command reaches for. The one index a command is given is a row's new place after a move, which the event itself carries (OnItemMoveWithItemKey, items).

The view's compile checks an event's arguments against its command and its place. It refuses what every press would fail on: a value-type parameter (int index) no argument supplies — give it a default or a nullable type if it may be absent — a path the types it walks do not have or the server cannot read (a controller property that is no [RecursiveMember]), and an item's key or the current item on a component standing in no row (ArgCurrentItem on one that binds a context of its own is that context). A path is refused only where that is certain — a template every row is drawn with, a type every press reads; in a variant chosen by a key, a group's header, a menu's entries and their submenu, or through a row type a derived item may extend, it is a warning. An argument the command has no parameter for is a warning: the command never sees it, though a command filter may read it.

Context

Every controller has a Context (UIContext), available once the runtime attaches it (before that, reading it throws):

Member What it gives
Dialogs, Downloads, Uploads The dialog, download and upload services for the current connection.
Translate(key) Translates a key using the current session's language.
Services The runtime's own service scope, disposed with the runtime. Everything the page runs shares it — a scoped service is one instance for the page's whole life, used by commands that may run at once — so data access takes an IDbContextFactory<T> and a context per command (see Commands).
Logger The controller's logger.
Route The UIRouteDefinition this controller runs on — fixed for the runtime's lifetime.
Handle The connection a command is running for — the invoking connection during a command, the attached one otherwise. Differs from the attached connection only under UIRuntimeLifetime.PerClient.
Connection What the platform knows about that connection (UIConnectionInfo): RemoteAddress (after the host's forwarded-headers handling), UserAgent, and BaseUri, the application's root an absolute link is built on. Captured at the page render and at every attach; what the client or a proxy said, never proof.
TimeZone The reader's time zone — reported by the page as it attaches and kept on the session — or UTC while it has reported none the host knows.
ToLocalTime(instant) The wall-clock time an instant reads for the reader: a DateTime is read as UTC unless it says Local; a DateTimeOffset keeps its instant and takes the reader's offset.
StartOfDayUtc(day) The instant a DateOnly begins for the reader, in UTC — where a filter by a picked day starts, the next day's start being where it ends; a skipped or doubled midnight is handled.
GetSessionAsync(cancellationToken) Reads the stored session behind this connection, or null if signed out or expired.
SignInAsync(userId, roles, permissions, cancellationToken) Marks the session authenticated and moves it to a new id at once; the page is handed the new key before it loads another page, so no navigation is needed. Call it from the page's own command: elsewhere it throws where another page shares the runtime (see security).
SignOutAsync(cancellationToken) Ends the session everywhere: every later command under it is refused, its uploads go, and every other page open under it is sent to sign in.
UpdateSessionAsync(update, cancellationToken) Applies a change to the stored session — language, theme, or anything else that must outlive this connection.
SendEffectsAsync(effects, cancellationToken) / SendEffectsToAllAsync(effects, cancellationToken) Pushes effects outside a command's answer — to this connection, or to every page attached to the runtime (under PerClient, every tab sharing it) — through the send queue, behind the values written before it: InvokeAsync(() => X = …) then a FocusEffect lands after X. Called from inside an InvokeAsync action it throws.
Subscribe(topic) / Unsubscribe(topic) Takes or leaves a topic IUIBroadcast posts to — a chat room, a ticket; every topic is left when the runtime ends (see Reaching another runtime).

Initialization and errors

OnInitializeAsync(CancellationToken) runs once, after the runtime context is attached and before the controller is considered ready — the place to load an items window or anything else that needs Context:

protected override async Task OnInitializeAsync(CancellationToken cancellationToken)
{
    await Rows.LoadWindowAsync(new UIItemWindowRequest(UIItemAnchor.Start, 50), cancellationToken).ConfigureAwait(false);
}

OnNavigatedAsync(UINavigationRequest, CancellationToken) runs with the navigation a page shows the runtime at — the place to read a parameter that shapes what the page shows, first paint included. It runs for the page render that builds the runtime, after OnInitializeAsync and before the render reads the values it paints, and for every attach — a new tab, a reload, a navigation that finds a kept runtime again — before OnAttachedAsync, in the same turn. The attach of the tab whose own render built the runtime skips it, the render having run it with that navigation; a render that paints a runtime already running (a kept one, which may be another tab's) does not run it, and the attach that follows does. So a parameter the route does not key its runtime by still reaches a runtime that already existed, where OnInitializeAsync never runs again. It runs once more, alone, when the reader goes back or forward to another history entry of the same route — one a PushAddressEffect added — with that entry's parameters (see routing):

protected override Task OnNavigatedAsync(UINavigationRequest navigation, CancellationToken cancellationToken)
{
    // A link to one tab of the page: painted on the first load, and applied when a kept runtime is found again.
    if (navigation.TryGetParameter("tab", out var tab))
        SelectedTab = tab;

    return Task.CompletedTask;
}

OnAttachedAsync(UINavigationRequest, CancellationToken) runs each time a page attaches, after the first attach's OnInitializeAsync and after OnNavigatedAsync. Both hooks run between exclusive commands as a command's body does, like posted work, with Context.Handle the page's connection (the render's own in a render). What an attach writes is in the page the attach is answered with, not in the page the render painted — a parameter that shapes the first paint belongs in OnNavigatedAsync.

OnDetachedAsync(CancellationToken) runs, queued, when a page leaves. HasViewers says whether a page is attached now; a page render preparing the page is nobody looking, and runs neither hook. HasVisibleViewers says whether one of its pages is on screen — the test for what only a reader who sees it should do, such as marking messages read: a tab in the background or a minimised window is attached but not seen, so a toast would play out unread there. OnVisibilityChangedAsync(wasVisible, cancellationToken) runs when it flips — the first page coming on screen, the last one leaving it — the moment to mark read what arrived while nobody looked. It is per runtime, so one tab giving way to another on screen raises nothing; it runs queued, as posted work does, after a page's report, an attach (after OnAttachedAsync) or a detach, and a flip undone before it ran is not heard at all.

Context.NotificationPermission is what the browser of the page a command runs for lets it show — Default until the reader is asked, then Granted or Denied, Unsupported where it has none. It belongs to one browser, not to the reader: keep whether the reader wants notifications in your own store. RequestNotificationPermissionEffect asks, raised by an interaction (InteractOn("click", …)) so the browser's prompt opens inside the reader's press; the answer reaches OnNotificationPermissionChangedAsync(previous, cancellationToken), queued as posted work is, so the page's report waits for no command. A page whose permission is Denied should say so: asking again shows nothing.

Unsaved work

HoldsUnsavedWork (a protected setter the controller sets and clears itself) says the page holds work its reader has not saved — an editor whose text differs from what is kept. While it is true, a leave the page starts — a press on one of its links, a menu's entry or a breadcrumb leading to another address of the site, or a NavigateEffect — asks OnLeaveRequestedAsync(target, cancellationToken) instead of leaving, and closing, reloading or going back past the page asks the browser's own question, the only one a browser allows there. The hook runs as a command does, and its answer's effects run on the page; unless overridden it answers ConfirmLeaveEffect(target), the framework's own dialog ("Leave without saving?" — Stay, Leave). A page that asks in its own words opens its own dialog, whose commands clear the flag and answer new NavigateEffect(target); a command that clears the flag and navigates in the same answer leaves without being asked again:

protected override Task<UICommandResult> OnLeaveRequestedAsync(string target, CancellationToken cancellationToken)
{
    _leaveTarget = target;

    return Task.FromResult(UICommandResult.Ok([new OpenDialogEffect(LeaveDialogKey)]));
}

[UICommand]
public UICommandResult SaveAndLeave()
{
    Save();                       // sets HoldsUnsavedWork = false

    return UICommandResult.Ok([new CloseDialogEffect(LeaveDialogKey), new NavigateEffect(_leaveTarget!)]);
}

Set the flag as the value lands — in the bound property's setter, as the page's value reaches it — rather than in an OnChange command: a leave pressed while a value is still on its way waits for that value's answer and then asks the controller, which by then holds the value and the flag its setter set — but it does not wait for a command the value would start after it. The browser's question waits for nothing: it asks while the flag is on, or while a value is on its way on a page that has held work before — never on a page that has not, so a debounced search box's keystrokes do not make closing the tab ask. A press while the question is being decided is swallowed, the runtime's own reloads never ask, and a page whose session ends (a sign-out, EndSessionAsync) lets its work go and leaves unasked.

HandleRuntimeExceptionAsync(RuntimeExceptionContext, CancellationToken) is called when something outside a command throws while the runtime is driving this controller; the base implementation logs and returns RuntimeExceptionResult.Empty — override it to react instead. A failed command is different: it is reported to the client automatically (see interactions and effects) and never reaches this method.

Runtime behaviour

A controller's changes accumulate and are flushed to its pages on the application's flush interval (UIPersistenceOptions.FlushSchedulerInterval, 50 ms by default). [UIControllerRuntime] on the controller class sets an interval of its own, and the flush then ticks as often as the shortest one declared; Timeout.InfiniteTimeSpan as the application's flushes nothing on a schedule, leaving it to the platform's IUIClientEndpoint.FlushAsync. The tick is never shorter than 10 ms, whatever an interval asks:

[UIControllerRuntime(FlushIntervalMilliseconds = 20)]
internal sealed partial class LiveController : UIControllerBase

A command's changes reach its page pushed, in order with every other change: the asking tab's share goes out right after everything drained before it and ahead of everything drained after, and the command's answer waits for that send, so its effects act on the page its changes made. A command's own result carries none of them (UICommandExecutionResult.Changes): a test reads what the page was sent (testing). A route registered with FlushInterval(interval) overrides the attribute for that route specifically — see routing.

Runtime lifetime — how long a runtime instance is kept once a window leaves — is an application-wide setting, UIPersistenceOptions.Lifetime (UIRuntimeLifetime), configured through UIApplicationBuilder.ConfigurePersistence(Action<UIPersistenceOptions>):

Value Kept until
PerPage (page-scoped) The window navigates away from the address — coming back is a fresh page.
PerWindow (default) The window — a browser tab, a desktop window — closes or times out; coming back finds the page as it was left.
PerClient Every window of the client shares one runtime; changes fan out to all of them.

DisconnectedRetention (default 10 minutes) is how long a runtime with no attached connection is kept before it is cleaned up. State survives a reload if and only if it is in the controller — there is no separate page snapshot, so a property the view never binds is not implicitly durable, and a property the view does bind is durable regardless of what it is.

UnclaimedRenderRetention (default 30 seconds) is the same for a runtime the page render built and no client ever presented. A page render reads its values off a runtime of its own and hands it to the attach that follows, normally within a moment; one that no client claimed — a crawler, a health check, a tab closed before it connected — is dead the moment that window passes, and keeping it for the full DisconnectedRetention costs a controller's worth of memory per unclaimed render. Losing the race costs the attach nothing but a fresh runtime.

Reaching another runtime

A command runs on its own runtime and its result reaches its own client. What another person's open page sees is the change to their controller, and the way to make one is to run on their runtime. IUIRuntimeAccess (Context.Runtime) has two ways into a runtime in hand: InvokeAsync runs a delegate under that runtime's lock and lets the caller await it — what it changes goes out with the next flush, and called from inside another action it throws (from there, Post) — and Post queues the delegate and returns at once — it runs on the thread pool as a command's body does, outside the lock and only between that runtime's exclusive commands, one at a time and in the order posted for that runtime, and a failure goes to the controller's HandleRuntimeExceptionAsync. Posted work belongs to no command: Context.Handle there is the page attached, never the page whose command posted it.

Which runtimes to reach is the host's to know. A controller subscribes its runtime to a topic — Context.Subscribe("chat:42"), Context.Unsubscribe — and IUIBroadcast, injected like any service, posts work to every runtime on a topic, or to every page a user has open. A chat room, a ticket everyone is looking at, a dashboard:

internal sealed partial class RoomController(IUIBroadcast broadcast, ChatStore store) : UIControllerBase
{
    private string _room = string.Empty;

    [RecursiveMember(false)]
    public RecursiveCollection<ChatMessage> Messages { get; } = [];

    [RecursiveMember]
    public partial string? Draft { get; set; }

    [UICommand]
    public async Task OpenAsync(string room, CancellationToken cancellationToken)
    {
        if (_room.Length > 0)
            Context.Unsubscribe(Topic(_room));

        _room = room;
        Context.Subscribe(Topic(room));

        await ShowAsync(cancellationToken);
    }

    [UICommand]
    public async Task SendAsync(CancellationToken cancellationToken)
    {
        ChatMessage message = await store.AddAsync(_room, Context.Handle.Session.UserId, Draft, cancellationToken);

        Draft = null;

        // Every page on the room — this one too — appends it in its own turn, in the order the messages were sent.
        await broadcast.PostAsync<RoomController>(Topic(message.Room), open =>
        {
            open.Append(message);

            return Task.CompletedTask;
        }, cancellationToken: cancellationToken);
    }

    // A post queued before this page moved to another room may arrive after it did.
    private void Append(ChatMessage message)
    {
        if (message.Room == _room)
            Messages.Add(message);
    }

    // A page nobody looked at was passed over: it reads what it missed when one attaches.
    protected override Task OnAttachedAsync(UINavigationRequest navigation, CancellationToken cancellationToken)
        => _room.Length > 0 ? ShowAsync(cancellationToken) : Task.CompletedTask;

    private async Task ShowAsync(CancellationToken cancellationToken)
    {
        IReadOnlyList<ChatMessage> messages = await store.ReadAsync(_room, cancellationToken);

        Messages.Clear();
        Messages.AddRange(messages);
    }

    private static string Topic(string room)
        => $"chat:{room}";
}
  • The topics go with the runtime. A runtime asked to go — its tab closed and its retention past, its session ended, a PerPage tab moved on — leaves every topic it took; there is no registry to clear in Dispose(bool), and none to leak.
  • Each runtime runs the work as Post runs it: queued, between its exclusive commands and outside its lock, its writes flushed as a command's; a write a value or a Background command shares goes through Context.Runtime.InvokeAsync. Every runtime on a topic sees the posts in the same order, and the sender's command never waits for another page's code.
  • A page redrawn by posts may redraw inside its own command too. A drop command whose answer must keep the dragged row where it landed (see items) writes the store, raises the post every page redraws from — its own included — and redraws its lists itself; its own post, and another page's, run after it ends and find the lists already drawn.
  • Only a page someone looks at is reached (HasViewers): a runtime kept after its tab left, or one a page render is still preparing, is passed over and catches up when a page attaches — as above, from where the messages are kept. Pass UIViewers.All to reach a kept runtime too, where a controller is the only place the state lives, or UIViewers.Visible for only the pages on screen.
  • PostToUserAsync(userId, action) reaches every page of every session signed in as that user, whatever its route — a notice on every open tab, a badge in every header: PostToUserAsync<UIControllerBase>(userId, open => open.Context.SendEffectsToAllAsync(...)). A system notification for the user goes through IUINotifier instead, which decides across their pages where it shows (dialogs and notifications).
  • A type argument names the controller the action is for — PostAsync<RoomController>(topic, action), PostToUserAsync<TController>(userId, action) — and a runtime whose controller is another is passed over, not posted to. The untyped overloads hand the action an IUIController to test itself.
  • Both answer how many runtimes they posted to, a typed post only those of its type. A topic stands in for a route as well: a page on /tickets/{id} takes ticket:42 as it opens, and the post needs no walk of every open page.

Nothing about it needs a runtime of its own, so a hosted service, a timer or a webhook posts the same way:

internal sealed class StatusFeed(IUIBroadcast broadcast, StatusSource source) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (ServiceStatus status in source.ReadAllAsync(stoppingToken))
        {
            await broadcast.PostAsync<StatusController>("status", board =>
            {
                board.Show(status);

                return Task.CompletedTask;
            }, cancellationToken: stoppingToken);
        }
    }
}

It reaches the runtimes of this process only, as IUISessions does: several servers behind a load balancer would each post to their own pages, and a message bus between them is the application's for now.

An account blocked, deleted or stripped of a role needs no event: IUISessions, injected like any service, ends or changes every session a person is signed in with — EndUserSessionsAsync(userId), UpdateUserSessionsAsync(userId, update), EndSessionAsync(sessionId) — and an ended session's open pages are sent to sign in at once; a changed session's pages whose route it no longer passes are reloaded, to sign in or the forbidden page (see security).

Disposal

Dispose() calls Dispose(bool disposing), which detaches the change notifier once. Override it to release what a controller owns — an event subscription of its own, a timer, a CancellationTokenSource, anything that must not outlive the runtime — the .NET way, which the analyzers' CA2213 reads: dispose your own fields when disposing and the controller is not IsDisposed yet, then call the base. A topic taken through Context.Subscribe needs nothing here.

protected override void Dispose(bool disposing)
{
    if (disposing && !IsDisposed)
        _reply.Dispose();

    base.Dispose(disposing);
}

Where to go next

  • Binding for the paths a [RecursiveMember] property is addressed by.
  • Interactions and effects for what a command's effects can do and how a failed command is reported.
  • Views for the component tree a controller's state feeds.