Streaming and hoisting

A model writes an interface one token at a time, and the user should not wait for the last token to see anything. OpenUI's streaming parser makes that work by building a fresh tree after every chunk, and the system prompt makes it pay off by asking the model to write the layout first.

By the end of this lesson you can

  • describe what the parser does with each new chunk, and why it rebuilds the tree instead of patching it;
  • tell a partial node (a statement whose text is cut) from an unresolved reference (a name whose statement has not arrived);
  • list the recommended statement order and say why a leaves-first program shows nothing until the end;
  • read the lab's chunk table, including the transient errors in it, and explain why they are normal.

A fresh tree, every chunk

The parser does not hold a half-built tree and patch it. It keeps one buffer of text. A statement is finished when a newline ends it outside any brackets. The parser parses it once and caches it. Each time a chunk arrives, the chunk is appended, and only the unfinished statement at the end is closed off, tokenized and parsed again. Then the parser builds a fresh result from all the statements: how many are done, which names are still missing, and the element tree for everything it can build. The result after the last chunk is the same as parsing the finished text in one go.

That gives the Renderer a simple job. After every chunk it receives a new tree and draws it. Watch four chunks of one program arrive. The figure shows the end of the buffer and the parse result for it.

One buffer, four parses

Buffer after chunk 1 root = Stack([title,▌ Parse result 1 statement, root partial · unresolved: title tree: Stack with no children yet Buffer after chunk 2 (last two lines) root = Stack([title, chart]) title = TextContent("Reven▌ Parse result 2 statements, title partial · unresolved: chart tree: Stack [ TextContent("Reven") ] Buffer after chunk 3 (last line) title = TextContent("Revenue", "large-heavy")↵ Parse result 2 statements, none partial · unresolved: chart tree: Stack [ TextContent("Revenue") ] Buffer after chunk 4 (last two lines) chart = BarChart(["NA"], [rev]) rev = Series("R", [1])▌ Parse result 4 statements, none partial · unresolved: none tree: Stack [ TextContent, BarChart [ Series ] ]
  1. The first chunk ends in the middle of an array. The parser closes the open bracket for itself (more on that below), reads root = Stack([title,]), and returns a root with no children. title is not in the text yet, so it is listed as unresolved.
  2. Chunk 2 finishes the root line and starts the title line, cut inside the string. The parser closes the string and the call, and TextContent appears with the text "Reven". The statement is still being written, so the node is marked partial. chart is the unresolved name now.
  3. Chunk 3 ends right after a finished line. Nothing is partial any more, yet chart is still unresolved. The two flags are independent.
  4. The last chunk arrives with complete = true. All four statements exist, every name resolves, and the tree is final. The lab runs exactly this loop against a recorded response, further down.

Key idea

Rebuilding the tree costs a little CPU on every chunk and buys correctness. Finished statements are not parsed again, only the last, unfinished one. There is no half-updated state to repair: the tree on screen is always what the text so far means. A program is small (hundreds of characters to a few thousand), so the repeated work is cheap.

Partial is not unresolved

Two different things can be missing from a half-written program, and the parser tracks them separately.

Partial nodeUnresolved reference
What is missingThe end of a statement's text. The line stops mid-string, mid-array or mid-call.A whole statement. A name is used, but no line with that name has arrived.
Where it showspartial: true on the element, and incomplete in the result's meta.The name appears in meta.unresolved, and the slot that uses it is left out of the tree.
What the user seesThe element, with whatever arrived: "Reven" before "Revenue".Nothing at that slot yet (the course's simulator draws a grey placeholder).
How it endsThe statement's closing characters arrive.A line that defines the name arrives.

Common misconception

"partial means some children are missing." It means the statement's text was cut. A parent with all of its children defined can still be partial if the last line has not finished, and a parent whose children are all unresolved is not partial at all once its own line is complete. The next widget lets you see both.

Cut the text anywhere

Drag the slider to choose how much of the program has arrived. The panels show the buffer, the buffer after the parser has closed whatever is open, and the parse result. Use the buttons to jump to the three cases worth studying. Predict the result before you look.

Buffer

After autoClose

Parse result

    Tree so far

    What should happen

    Inside the title string: autoClose adds the closing quote, the parenthesis and nothing else, and the tree shows TextContent with the characters received so far, flagged partial. chart is unresolved, because the root line already names it.

    After the title line: no node is partial, yet chart is still unresolved. Complete and resolved are different questions.

    Inside the root line: the root exists and is partial, with only the children it has named so far. Names it has not reached yet are not in the text at all, so they do not appear as unresolved.

    This panel uses the course's teaching simulator, a port of the real parser's streaming logic. OUI.autoClose mirrors autoClose in @openuidev/lang-core: it closes an open string, then open (, [ and { in reverse order.

    Hoisting: write the shell first

    The parser accepts a reference before its definition, so the model decides the order of the lines. The generated system prompt has a section titled Hoisting & Streaming (CRITICAL) that asks for a specific order, and it explains the reason: always write root first "so the UI shell appears immediately, even before child data has streamed in". Hoisting is the name for using a name before it is defined.

    Recommended statement order

    1root = Stack([header, controls, card])The shell appears at once. 2$city = "Pune"State exists, so inputs can bind to it. 3weather = Query("get_weather", …, {…})Default values resolve now, socomponents render with data. 4card = Card([title, table])Components fill in the shell. 5rows = [["Pune", 31], …]Leaf data arrives last.
    1. root first. The Renderer can draw the outer layout as soon as the first line is complete, and every name it uses is a slot waiting to be filled.
    2. $variables next, so that inputs bound to them have state to read when they appear. This step exists only when the prompt has state turned on.
    3. Query statements next. Their default values (the third argument) resolve immediately, so components that read query data have something to render. The query itself does not run until the stream ends. This step exists only when tools are on.
    4. Component definitions follow, each one filling a slot in the shell with data that already exists.
    5. Leaf data last: the long arrays and strings, which are also the slowest to generate.

    Without state and tools the list shortens to three steps, root, components, data. The prompt builds the list from the library's flags, so a library with no tools never mentions queries.

    OpenUI rule

    "Always write the root = Stack(...) statement first so the UI shell appears immediately." The parser does not require it; the prompt asks for it because it changes what the user sees while waiting.

    Same program, two orders

    Both players below stream the same six statements into the same library. The left player writes them in the recommended order. The right player writes them leaves first and root last. Press Play both and watch the interface pane. Predict first: when does the right player draw its first element?

    Hoisted: root first

    Leaves first: root last

    What should happen

    The left player draws its first element within the first twenty characters and fills it in as lines arrive. The right player draws nothing for most of the run: every statement it receives is valid but unreachable, so each one is orphaned until the root line comes last. Then the whole interface appears in one step. Both players end with the identical interface, and the readouts show how much of the text each needed before the first element could be drawn.

    Nothing errors in either order. The parser is happy with both, which is why the order is a prompt rule and not a syntax rule.

    The simulator draws grey placeholders for names that have not arrived, to make the shell visible. The real parser leaves those slots out of the tree until they resolve, so the shell is sparser there. The ordering effect is the same.

    Time to first token, and to first pixel

    TTFT, time to first token, is how long the user waits before any output arrives. It depends on the model, the provider and the network, and a UI library cannot change it. What the library can change is how long after that first token the user sees something.

    OpenUI's streaming claims are about this progressive reveal: structure first, then data fills in. The comparison in the previous section is the effect in miniature. How many seconds it saves depends on the model's speed and the length of the program, and this course makes no latency claim of its own.

    Mid-stream errors are normal

    A half-built tree can break the library's validation rules in ways that disappear a moment later. A required field whose value is a reference to a line that has not arrived is null for now, and a required null is an error. A table cut in the middle of its first Col( call is missing its required arguments. Neither is a mistake by the model.

    The lab below prints this. Look at its chunk 4, where the chart's regions have not arrived: the parser reports null-required and missing-required. By chunk 5 both are gone. The real Renderer hides this from you: it reports parser errors to onError only after the stream ends, so the transient ones never reach your handler.

    OpenUI rule

    Judge a program by its final parse, not by its intermediate ones. If you call the parser yourself, as the lab does, ignore errors until you push the last chunk with complete = true. Queries also wait: they do not run until streaming ends.

    Lab: parse a stream chunk by chunk

    The first lab feeds a recorded model response to the real streaming parser from @openuidev/lang-core, 48 characters at a time, with no model and no keys. The response is the revenue dashboard from the simulator, with root first and its children hoisted below it.

    One streaming parser is created for the whole response. It owns the buffer. The loop pushes a chunk, passes complete = true only on the last one, and prints what the result says.

    The library it parses against defines the five components the response uses. The key order in each schema is the argument order, as in the signature section of the previous lesson.

    This is the real output of the script. Read it from the top.

    ChunkCharsStatementsRoot partialUnresolvedErrors
    1481false["title","metrics","chart","tbl"]none
    2962true["metrics","chart","tbl"]none
    31443true["chart","tbl"]none
    41924true["regions","tbl"]null-required, missing-required
    52405true["rev","tbl"]none
    62886true["tbl"]missing-required
    73367true[]missing-required
    83847true[]none
    93967false[]none

    The lab cuts fixed 48-character chunks, often in the middle of a string, so some statement is usually partial. Partial propagates up, so the root reports partial: true. The figure above ends its chunks at chosen points instead.

    Lab

    Run it yourself, in the openui/ folder of this repository. The flag skips the package's install-time telemetry script. Then change CHUNK to 8 and to 400, and move the root line to the end of RESPONSE to see the leaves-first order in the table.

    cd openui && npm install --ignore-scripts && node 01-parse-stream/stream.mjs

    The same script goes on to parse a deliberately broken program. That second half belongs to When the model gets it wrong.

    Quick check

    After chunk 3 of the figure, the parse result says nothing is partial and chart is unresolved. What does that mean?

    • The parser is confused: a complete program cannot have an unresolved name
    • The text so far ends between statements, but the root names chart and no line defines it yet
    • The chart line arrived but was cut short
    Partial describes the end of the text. Unresolved describes names with no definition yet. A cut-short chart line would make chart a partial node, not an unresolved name.

    A model writes all the leaf data first and root as the last line. What does the user see while it streams?

    • Nothing, until the root line arrives and connects everything
    • An error for each unreachable statement
    • The leaf data, drawn as loose elements
    Rendering starts at root. Statements nothing reaches are orphaned and are not drawn, and they raise no error. The final interface is identical, but the first element appears at the end instead of the start.

    The lab's chunk 4 shows null-required. Should your app send that error back to the model?

    • Yes, immediately, so the model can correct itself mid-stream
    • No: it is transient, and only the errors from the final parse matter
    • Yes, but only if the error repeats in the next chunk
    A required field that points at a not-yet-defined name is null until that line arrives. The Renderer reports parser errors only after the stream ends for this reason. Check errors on the complete result.

    Recap