# Updates

A program updates an existing surface by sending a **delta**: a list of
operations targeting elements by `id` ([§6](https://hotty.neuroplast.io/docs/protocol#6-deltas)). The
host applies these operations directly to its stored document, so wire
overhead scales with what changed rather than the total document size.

```text
program → ESC ] 7279 ; a=doc:s=dash ; <style>.bar { width: calc(var(--p) * 1%) }</style> <div id=cpu class=bar style="--p: 0"></div> <span id=clock></span> ST
program → ESC ] 7279 ; a=delta:s=dash:q=2 ; {"ops": [{"op": "var", "t": "cpu", "k": "p", "v": "42"}, {"op": "text", "t": "clock", "v": "12:00:01"}]} ST
```

(Payloads are shown decoded here, with the msgpack delta rendered as JSON.
On the wire they are base64-encoded.)

The bar width updates to 42% and the clock text becomes `12:00:01`. CSS
handles the visual presentation while the delta transmits only the updated
values.

## A delta

A delta is a single message with action `a=delta`, a surface name `s`, and a
msgpack payload listing its operations ([§6.1](https://hotty.neuroplast.io/docs/protocol#61-adelta)).
Each operation is a map with up to four string fields:

- `op`: the operation name
- `t`: target element `id`
- `k`: property or attribute name (for `attr`, `unattr`, and `var`)
- `v`: value to apply (HTML, text, or property value)

The host applies all operations in a delta sequentially as a single atomic
update, never rendering intermediate states. Batch all changes for one
surface in a given frame into one delta.

## The ops

| `op` | what it does to the target |
| --- | --- |
| `text` | replaces its children with the text `v` |
| `var` | sets the custom property `--k` on it to `v` (`k` may carry its `--`) |
| `attr` | sets its attribute `k` to `v` |
| `unattr` | removes its attribute `k` |
| `morph` | morphs it into the HTML `v`, keeping what stays ([below](#morph)) |
| `inner` | morphs its children into the nodes of `v` |
| `replace` | replaces it with the nodes of `v`, without morphing |
| `append`, `prepend` | adds the nodes of `v` as its last or first children |
| `before`, `after` | adds the nodes of `v` before or after it |
| `remove` | removes it |
| `reveal` | scrolls it into view: its top with `start`, its bottom with `end`, or as little as it takes |
| `scroll` | scrolls from it (no target: the root) as a key bound to the scroll action `v` would, one of the host's steps (new in 0.8) |

`text` and `var` are the primary high-frequency operations for live
dashboards, and hosts are expected to optimize them. Most frequent updates
map cleanly to one of the two: counters and labels use `text`, while bar
widths, progress indicators, and dynamic colors can be driven by CSS custom
properties via `var`.

HTML fragments in `v` are parsed in the context of their destination parent.
Appending a `<tr>` to a `<tbody>` or an `<li>` to a `<ul>` parses as
expected.

`append` and `prepend` deduplicate by `id`: if a node in `v` has an `id`
that already exists as a direct child of the target, that child is morphed
in place rather than duplicated. This allows streaming views like logs to
update their last line by re-appending it.

`reveal` does not modify the DOM. In a scrollable document
([Surfaces](https://hotty.neuroplast.io/docs/concepts/surfaces#scrolling-inside-a-document)), it scrolls all
enclosing scroll containers until the target is visible without changing
focus or keyboard ownership.

`scroll` also leaves the DOM unchanged. It is designed for programs that
retain keyboard focus and implement their own keybindings (such as `j`/`k`
navigation): each operation scrolls the nearest scrollable ancestor of the
target by one host scroll step matching the action in `v`
([§10.2](https://hotty.neuroplast.io/docs/protocol#scrolling-keys)). To scroll multiple steps, emit
multiple `scroll` ops in one delta. If nothing can scroll in that direction,
the op is a no-op; the program tracks the resulting position via `view`
events ([Input](https://hotty.neuroplast.io/docs/concepts/input)).

## Why ids

Targeting by `id` makes delta effects explicit and predictable: each
operation modifies one specific element and nothing else
([Appendix B](https://hotty.neuroplast.io/docs/protocol#appendix-b-rationale)). Because events also
identify targets by `id`, the same identifier serves as the handle in both
directions ([Input](https://hotty.neuroplast.io/docs/concepts/input)).

Use ASCII for element IDs. While deltas match any `id` verbatim against the
document, event control headers replace non-ASCII characters with `_`
([§3.2](https://hotty.neuroplast.io/docs/protocol#32-control))—for example, `café` is reported as `caf_`.

**Missing targets** are skipped without aborting subsequent operations in
the same delta. The host replies with `ENOTARGET`, naming the missing `id`
and `i` (the index of the first failed op). Any other malformed delta (such
as an unknown op name) fails atomically with `EINVAL` and applies nothing.

When neither `q` nor `n` is set, the host replies to a delta only on error
([§3.6](https://hotty.neuroplast.io/docs/protocol#36-replies)). High-frequency frame updates typically
set `q=2` to suppress all replies, which is the default in the SDKs
([SDK design](https://hotty.neuroplast.io/docs/sdk-design#34-commands)).

## Morph

Morphing reconciles an existing element with new HTML while preserving
unchanged DOM nodes and local UI state ([§6.2](https://hotty.neuroplast.io/docs/protocol#62-morph)).
Matched elements are updated in place rather than recreated, retaining:

- Focus and in-progress user text input
- Scroll positions
- `<details>` open/closed state

Two elements match when they have the same tag name and—if both specify
one—the same `id`. Among child nodes, keyed elements (those with an `id`)
match their previous instance regardless of position; unkeyed nodes match
in document order by node type. Matched elements are patched in place and
reordered as needed; unmatched elements are inserted or removed.

**Program values win unless the user is actively editing.** Updating
`value`, `checked`, or `selected` updates the control's live state unless
that control currently holds focus. Focused controls preserve the user's
in-progress input. To update a field that the user might be editing without
clobbering their changes, use `a=field`, which applies the update only if
the user has not modified the control since
([Input](https://hotty.neuroplast.io/docs/concepts/input#changing-what-the-user-is-changing)).

Calling `morph` without a target `t` matches each top-level element in `v`
to the document element with the same `id`. Immediate-mode programs that
re-render their entire view each frame can update the surface this way:

```text
program → ESC ] 7279 ; a=delta:s=signup:q=2 ; {"ops": [{"op": "morph", "v": "<form id=form><input id=email name=email> <p id=hint>That address is taken</p></form>"}]} ST
```

Here, `#hint` updates while `#email` retains its focus and typed text. Any
top-level IDs missing from the document are reported together in a single
`ENOTARGET` error while all matched elements still update.

Unlike `morph`, `replace` inserts fresh nodes without preserving state.
Sending a new document with `a=doc` replaces the entire surface and resets
scroll offsets to the top left.

## Several commands at once

A single delta is already applied atomically. To apply multiple commands or
update multiple surfaces in one visual frame, wrap them in terminal
synchronized output
([§6.3](https://hotty.neuroplast.io/docs/protocol#63-order-and-transactions)):

```text
program → CSI ? 2026 h
program → ESC ] 7279 ; a=delta:s=list:q=2 ; {"ops": [{"op": "attr", "t": "row-4127", "k": "class", "v": "selected"}]} ST
program → ESC ] 7279 ; a=doc:s=detail ; <h2>Build 4127</h2>… ST
program → CSI ? 2026 l
```

Here, one surface highlights the selected row while another loads its detail
pane. The host suppresses intermediate frames—either buffering commands
until `CSI ? 2026 l` or applying them without painting—just as TUIs already
bracket cell updates to avoid flicker.

- The host processes commands in arrival order and should paint at most once
  per display frame.
- Terminals enforce a timeout on synchronized output blocks; if a batch
  times out, the host may flush and apply the buffered commands.

## What an update costs

A delta's wire size is the base64-encoded msgpack of its operations plus one
OSC envelope. The examples in
[Appendix A](https://hotty.neuroplast.io/docs/protocol#appendix-a-examples) show typical wire sizes
including the envelope:

| update | bytes |
| --- | --- |
| one `text`: a button reads "Start" | 68 |
| a `var` and a `text`: a bar and a clock | 104 |

Neither size depends on the overall document size. Prior to 0.3, each
operation required its own message and envelope: 15 small updates took 755
bytes. Batched into one delta, the same 15 updates take 184 bytes
([Appendix B](https://hotty.neuroplast.io/docs/protocol#appendix-b-rationale)).

Minimizing wire traffic is up to the program: a framework that rebuilds its
view tree diffs it against the previous frame and emits targeted ops.
Updating a single table cell with `text` takes 56 bytes, compared to 930
bytes for morphing the entire table
([SDK design](https://hotty.neuroplast.io/docs/sdk-design#29-updates-cost-what-they-change)). Targetless
`morph` remains available as a simpler fallback.

Because `a=doc` is the largest message, send it once and follow up with
deltas. Documents can be zlib-compressed with `o=z`, which more than offsets
base64's 33% expansion on HTML markup ([§3.3](https://hotty.neuroplast.io/docs/protocol#33-payload)).
Stylesheets shared across multiple surfaces should be sent once as a
resource ([Images and the network](https://hotty.neuroplast.io/docs/concepts/resources)).
