Reactive state with $variables

A generated screen is not a picture. The model declares a few $variables, wires them to inputs and expressions once, and from then on the browser keeps everything in sync. Changing a filter does not need the model, a network round trip to it, or a single new token.

By the end of this lesson you can

  • declare a $variable, bind it to an input, and say which statements re-run when it changes;
  • explain what a custom component must do (reactive() and useStateField) to accept a binding;
  • use @Set and @Reset, and predict when a declared default replaces the current value;
  • write expressions with operators, a ternary, member access and indexing, and combine built-in functions such as @Filter, @Sort, @Count and @Each;
  • state the two rules models break most: $variables hold simple values, and a Query is never a $variable.

A variable is a statement that starts with $

A $variable is declared like any other statement, except its name starts with $. The value on the right is its default. Everything else in the program can read it by name.

$city = "Pune"
$units = "celsius"
$showHelp = false

The model usually does not even need to declare one: a $name that is used but never declared is created automatically with the default null. Declare it when you want a starting value. Variables live in a store inside the Renderer, not in the model's text, which is why the next figure never touches the model.

Step through what happens when the user changes one variable. The program is the weather example from the try-it below: an Input bound to $city, a heading that reads it, and a Query that passes it to a tool.

One variable changes, three things follow

Renderer Store declared default $city = "Pune" $city = "Tokyo" Input("city", …, $city) bound: shows and writes $city title = TextContent(…) "Weather in " + $city → "Weather in Tokyo" w = Query("get_weather", …) deps: ["$city"] User types "Tokyo" get_weather {city: "Tokyo"} Re-render heading text weather card only changed props Model: not called
  1. The program declares $city = "Pune". The Renderer puts the default in its store.
  2. Three statements depend on it. The Input is bound to it. The heading expression reads it. The Query uses it in its arguments, and the parser records deps: ["$city"] for that statement.
  3. The user types "Tokyo". The bound input writes the new value into the store. That is the only thing the user did.
  4. The store tells everything that depends on $city. The heading expression is evaluated again and gives "Weather in Tokyo". The Query now has a new set of arguments, so it fetches again from the tool.
  5. The fetch returns. The Renderer re-renders the components whose props changed: the heading and the weather card. Everything else is left alone.
  6. The model took no part. The program it wrote one turn ago is unchanged; only the data and the variable moved. This is the whole point of $variables: a filter change is a local update, not a conversation turn.

Key idea

When a $variable changes, the Renderer does four things in order: it updates every input bound to the variable, fetches again every Query that uses it in its arguments, re-evaluates every expression that reads it, and re-renders the components whose props changed. The model declares the variable and uses it; the renderer keeps it in sync.

OpenUI rule

Use reactive state for filters, tabs, toggles and form inputs that feed a Query or Mutation. Do not use it when the change needs new reasoning or a new layout from the model. Then send a message with @ToAssistant instead (see the actions lesson).

Binding: a reactive prop takes the variable itself

Most props receive a value. An input's value prop receives the variable, so it can write back as well as read. The prompt shows these props in the component signature as $binding<type>. In the stock library the binding is the last positional argument of Input and Select, which is why a model writes null for the arguments in between:

$days = "7"
filter = Select("days", [SelectItem("7", "7 days"), SelectItem("30", "30 days")], null, null, $days)
title = TextContent("Showing last " + $days + " days")

A component in your own library gets this behaviour in two steps, and both are required. First, mark the prop with reactive(), so the evaluator passes the binding through instead of only its current value, and the prompt shows $binding<…>. Second, read and write through useStateField, not React's useState, so changes reach the store.

The same component shows up in the prompt as UnitToggle(name: string, value?: $binding<"celsius" | "fahrenheit">) (lab 02 prints it). Note useIsStreaming: inputs stay disabled until the program has finished streaming, so a half-written program cannot start fetching.

Watch out

Using useState in a custom input looks fine, because the input still works on screen. But the $variable never changes, so nothing that reads it updates. The symptom is an input that moves while the chart beside it stays still.

In this course's simulator, the stock inputs and UnitToggle are plain HTML written against the same rules. The real components are React and live in @openuidev/react-ui and your own library.

Change a variable, watch the tool calls

Pick a sample, let it stream (or press Show final), then change the city or the units. The Inspector's State tab shows the store, and the line under the player counts model calls and tool calls. Inputs are disabled until the stream ends.

Things to look for

The simulator runs the program against five fake in-page tools; the real Renderer calls your toolProvider. See the Query and Mutation lesson.

@Set, @Reset and the declared default

A button can change a variable too. @Set($var, value) writes a value. @Reset($a, $b) restores each variable to the default it was declared with. To do several things, put the steps in Action([...]); they run in order.

$days = "7"
more = Button("Show 30 days", @Set($days, "30"))
clear = Button("Clear", Action([@Reset($days), @Reset($title)]))

@Reset restores declared defaults, so it is the right tool after a form submit. @Set($title, "") only works if the default is the empty string.

There is one more detail, and it explains a surprise in streaming and edit mode. The store remembers which variables still hold their declared default; call these pristine. While a program is still streaming, a half-written default such as "1" on its way to "14" is stored, and later chunks must be able to replace it. So when the model's text is parsed again, a pristine variable takes the newly declared default, while a variable the user has changed keeps the user's value. @Reset puts the variable back into the pristine state.

Key idea

The model's declared default wins until the user or a persisted value says otherwise. After that, only @Set, @Reset or the user changes the value, and a re-sent or patched program never overwrites it.

The editor below holds a small program. Press the buttons in the rendered UI, then use the two buttons under the editor to rewrite the default as the model would after an edit. Watch the line under the editor to see what the store does.

Expressions and built-in functions

Anywhere a value is expected you can write an expression. The parser knows these forms, and the syntax rules 9 to 16 of the generated prompt teach them to the model (they appear when bindings or toolCalls is on, as the previous lesson showed).

FormExampleNotes
String join, arithmetic"Showing " + $days + " days", (a + b) * c+ - * / %. + joins when either side is a string.
Comparison, logicscore >= 80 && !hidden== != > < >= <=, && || !
Ternary$showHelp ? helpCard : nullShow or hide a part of the UI. Assign the result to a statement.
Member accessw.current.temp, rows.scoreOn an array it plucks that field from every element, giving an array.
Indexrows[0].nameZero-based.
Built-in call@Count(@Filter(rows, "score", ">=", 70))Starts with @. Count(x) without it is not a call.

The built-ins compute in the browser, from your data, so the numbers never come from the model's guess. The ones you will use most:

GroupFunctions
Aggregate@Count @Sum @Avg @Min @Max @First @Last
Filter and sort@Filter(array, field, op, value) with ops == != > < >= <= contains; @Sort(array, field, "asc" | "desc")
Math@Round(n, decimals?) @Abs @Floor @Ceil
Iterate@Each(array, "r", template): the second argument names the loop variable, used inside the template

OpenUI rule

The @ is required. Built-ins convert instead of validating (@Sum(["1", 2]) gives 3). A call to a function that does not exist reports unknown-function and evaluates to null, and the rest of the statement still renders. @Run, @Set, @Reset, @ToAssistant and @OpenUrl are actions, not functions: they run on a click.

Exercise: grow one program

The editor starts with a three-row table of scores. Try each task in the textarea first, then press its button to load a worked solution and compare. The solutions build on each other, so the last one combines everything with a bound $min filter.

  1. 1. Index. Replace the heading so it names only the first row: its name and score.

  2. 2. Ternary. Give each Tag a fourth argument: "success" for scores of 80 or more, otherwise "neutral".

  3. 3. @Filter. Show only the rows scoring at least 70, by filtering the array handed to @Each.

  4. 4. @Sort and @Count. Sort the filtered rows by score, highest first, in a statement of their own. Make the heading say "2 of 3 shown".

  5. 5. Make it live. Replace the 70 with a $min variable bound to a Select. Change the select: the heading, the tags and the count all follow, and no model is involved.

Two rules that models break

The prompt states them, because they are the mistakes a model makes when it treats $variables like ordinary variables in a programming language.

RuleWrongRight
$variables hold simple values (strings or numbers), not arrays or objects.$rows = [{name: "Ada"}]rows = [{name: "Ada"}], and a $pick = "Ada" to choose among them
A Query is a regular identifier, never a $variable.$w = Query("get_weather", …)w = Query("get_weather", {city: $city}, …)
A $variable only does something if an input is bound to it, or an action sets it.Declared and read, never bound or setSelect("days", […], null, null, $days) or @Set($days, "30")
A visible filter must reach the data.A dropdown bound to $range while the Query hardcodes {range: "7"}Every relevant Query passes $range in its arguments

OpenUI rule

These rules come from the "Interactive Filters" section of the generated prompt. Reading the prompt is the fastest way to see what the model has been told; the explorer in the previous lesson lets you open it.

Break it

Predict first, then try it in the weather player or the editors above.

A filter that does nothing. In the exercise editor, load solution 5, then change the @Filter value from $min back to 70. Move the select. What happens?

What should happen

The select still moves and $min still changes, but the heading, the tags and the count stay put. Nothing reads $min any more. This is the "filter wiring" mistake from the table above.

Edit the default after the user changed it. In the Set and Reset editor, press "Show 30 days", then press "Change default to 14". What does the heading say? Then press Reset and change the default back to 7.

What should happen

After the user (or @Set) changes it, the heading keeps 30 even though the program now declares 14. After @Reset, the variable is pristine again with the declared default (14), and the next re-parse with 7 moves it to 7.

A function that is not there. In the exercise editor, load solution 4 and change @Count(shown) in the heading to @Total(shown). What do you see?

What should happen

The heading still renders, with nothing where the count was, and the error list shows unknown-function. The call evaluates to null and the rest of the statement survives. Typos in function names fail quietly in the UI and loudly in the error list.

Quick check

A dashboard has $days bound to a select, a heading that reads it and a Query that passes it. The user picks "30". What happens?

  • The heading is re-evaluated and the query fetches again; the model is not called
  • The browser sends the new value to the model, which writes a fresh program
  • Only the select updates; the heading and query keep their old values until the next message
The store notifies every dependent: bound inputs, expressions that read the variable and queries that list it in their arguments. Only a change that needs new reasoning or layout should go back to the model, through @ToAssistant.

Your custom RangePicker works on screen, but a chart bound to the same $range never updates. What is the most likely cause?

  • The component uses React useState instead of useStateField
  • The model declared the variable with the wrong default
  • The chart needs @Run to refresh whenever the range changes
Two things make a custom prop bindable: reactive() on the schema, and useStateField to read and write. Local state moves the widget but leaves the $variable untouched.

The user has pressed "Show 30 days". The model then patches the program and changes the declared default to "14". What does the heading show?

  • 14, because the newest declaration always wins on re-parse
  • 7, because the original default is restored on re-parse
  • 30, because the variable is no longer at its declared default
Only a pristine variable (still at its declared default) takes a new default on re-parse. @Reset makes it pristine again.

Recap