Files
alkane-os/third-party/flare-ui/docs/page-live.md
T
noahandClaude Opus 4.8 c752fc6d8b third-party: re-vendor flare-ui at sprint (the most-ahead branch)
The vendored flare-ui was a Nov-4 snapshot with no recorded pin. Advance it to
the furthest-along upstream branch: blueflare/flare-ui `sprint`
(0e1f5a259faa), which is 247 commits beyond `main`, 71 beyond `next`, and
already contains `next` in full. The scattered 1-3 commit leads on individual
sp/* feature branches are unmerged side-work, not a more-ahead integration line,
so vendoring one of those would drop the 247-commit integration; `sprint` is the
single most-ahead branch.

This brings sprint's flare-ui crate additions (form.rs, page.rs, page/, table.rs
and the flare-ui-axum / flare-plugin-host crates) into the tree. Record the pin
in flare-ui.lock so the next re-vendor is reproducible.

alkane-os builds against it with no source changes: the console (console.rs) and
the rest compile clean, clippy -D warnings is clean, and 183 lib + integration
tests pass (including the dashboard schema tests, so the wschema model stayed
compatible). Re-verified the live console on sprint: --serve-sim boots, the
flare-ui shell and control pages render, and stop -> ambient:18000 -> start all
succeed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
2026-11-10 20:19:12 -06:00

13 KiB

Named page events

page-live.js consumes the named events emitted by flare-ui-axum. It uses one same-origin fetch stream per document. The byte parser observes comment heartbeats, handles fragmented UTF-8 and CRLF, and bounds each encoded frame to 64 KiB before decoding or changing the page.

Page setup

Load page-live.js before boot.js and declare these meta tags:

<meta name="bf-live-protocol" content="page">
<meta name="bf-stream" content="/status/events?seq=42">

The body must contain exactly one canonical data-page root with data-seq="42". The initial stream cursor must match that snapshot. Without the protocol tag, boot keeps the existing JSON reading client. With page, a missing client or invalid root is an error; boot does not open a legacy stream as a fallback. Repeated boot calls share one result.

Call the returned close() before replacing a page through host navigation. It aborts the stream and pending reload, clears timers and releases the document's connection ownership. A closed response cannot update a new page.

Hosts can construct FlarePageLive.PageLive directly with root, streamUrl and pageUrl. Optional onState and onAction callbacks receive state changes and typed action progress. loadPage({url, signal}) may supply fresh HX body text when the host needs additional request setup. It must honor cancellation. Validation and DOM replacement remain in the canonical client. Call start() once and close() during teardown. An observer exception stops the client, aborts pending work and releases ownership. lastError records it without invoking the failing observer again. A diagnostic observer failing after an applied value leaves that accepted cursor intact; a failed action handler does not advance it. Callbacks may close or restart the client for navigation. The previous connection stops immediately at that boundary and cannot arm a timer, accept its event or change the replacement connection's state. An exception from an already closed or superseded callback cannot stop the new generation. Reader cancellation is awaited before releasing its lock. Reloads and their deadlines belong to the connection generation. Closing clears the deadline immediately; pending reader cleanup cannot suppress the restarted connection's resync or clear its reload state.

Polling mode

Construct PageLive with mode: "poll" to request one batch every three seconds. setMode("stream") or setMode("poll") cancels the previous transport generation before starting the selected mode. A closed client stays closed when its mode changes. Cross-tab admission is a separate coordinator responsibility; direct construction does not grant a stream slot.

Polls use the same route with mode=poll and the accepted seq. A 200 response must contain bounded UTF-8 HTML and a valid X-Seq. The complete mixed r, st and ap update is validated before any target changes. An unchanged sequence cannot carry changed HTML; an empty response may advance the sequence when only JSON events changed. Poll mode does not deliver chart samples or action progress, matching the server's HTML-only poll contract. Those values cannot be presented as refreshed by polling.

Status 205 requires X-Resync: 1, a valid X-Seq and an empty body. It starts one fresh page-body reload and resumes the chosen transport mode from that body's sequence. The response header alone never replaces the accepted cursor. Status 429 uses the canonical integer Retry-After contract, bounded to 1-64 seconds; retries wait at least three seconds. Other transient failures back off to 64 seconds. Each poll has a ten-second deadline. Redirects, access refusals and malformed protocol responses stop the client.

html[data-live="poll"] identifies polling. A successful batch clears transport staleness while preserving each reading's producer stale marker. Mode changes, observer callbacks and delayed responses retain the same generation ownership as streams and reloads.

Aborting the client request does not acknowledge release of the server's stream lease. Browser tests enforce no overlap of client-owned un-aborted requests and record the server's response count separately. A restart rehearsal observed two responses briefly during handoff. Actual server lease caps and cross-tab overload behavior remain integration gates; no delay is added to hide that asynchronous handoff.

Shared ownership

For coordinated pages, load page-owner.js before boot.js, serve the worker asset, and add:

<meta name="bf-live-worker" content="/assets/page-owner-worker.js">

Every adopted page on an origin must use the same stable worker URL and bf-live worker name. Do not add a version query or serve separate owner URLs for different routes. The worker owns every stream, poll and HX body request for each bound port. It admits at most three streams across those pages. Initial and replacement requests retain the same origin, page URL, events URL and session cookies; values are never shared between ports. The server still authenticates every request and snapshot.

BroadcastChannel bf-live carries only bounded version/client/mode control announcements. Each page retains at most 32 peer announcements. These announcements support discovery; they do not prove that another request stopped. The worker is the request authority because it can abort the fetch before reassigning a slot. Missing worker or channel support, or a failed initial handshake, uses polling. When a worker is available but the channel is not, it owns a polling-only binding. Without a worker, visible pages use three-second local polls. This split retains the channel contract without relying on expiring peer claims for safety.

Initially hidden pages do not start page requests. A visible stream that becomes hidden keeps a 30-second grace period only while no visible page needs its slot. Visible demand preempts it by aborting the owned request before assigning the slot. Hidden polling pages pause immediately. Once paused, a page sends no stream, poll or body requests. Control keepalives retain its bounded port registration.

Activation first obtains a fresh HX body through the same owner. It keeps stale markers until the complete body, page identity and sequence are accepted, then resumes its admitted stream or poll mode. Rapid visibility changes cancel the old body and retain only the current request. Existing schema changes use the same replacement validation as stream resync.

The worker owns at most five un-aborted requests: three streams, one poll and one HX body. Poll and body requests have separate FIFO queues, each bounded by the 32-port table with one pending request per port. Each queue waits two seconds after completion or abort before admitting another request. Hiding or closing a queued page removes it without spending a network admission. These bounds do not establish when a server stops work after receiving a cancelled request.

The ten-second poll/body network deadline starts at admission. Queue wait has a separate 384-second cleanup ceiling, derived from 32 ports times a ten-second request plus two-second spacing. This is an overload bound, not a normal freshness target. A poll waiting over 20 seconds marks values stale; activation remains stale throughout its body wait. Fair queue order lets another visible window progress through a slow authorization without repeatedly losing its turn to the first window. The server poll limiter retains its one-request-per-two-seconds session budget.

The worker receives five-second keepalives and removes an unresponsive port after 35 seconds. Removal aborts its owned request before another page receives the slot. Each port receives at most one unacknowledged 16 KiB chunk. A network chunk above 256 KiB is refused. Stream inactivity or a stalled reader reaches its 20-second deadline. Old request cleanup cannot clear its successor.

After contact with an active owner is lost, the page closes and marks its values stale. It does not open a competing local poll. It reconnects to the same worker identity, which cancels the previous client binding before acknowledging the replacement. Failed active channel coordination requests a polling-only binding. This favors the connection bound over availability while ownership is uncertain. Browser abort acknowledgement still does not acknowledge release of the server lease; 429 retries honor Retry-After.

Use the boot result's close() for navigation. Direct Owner users call attach(page) while PageLive is unstarted, then start() and close(). Coordinated pages use the canonical body fetch; Owner rejects a custom loadPage callback that would bypass request admission. Direct PageLive callers retain that callback outside the coordinated owner. The owner releases admission when PageLive closes normally, stops after a protocol or access error, or stops after an observer exception. Internal mode changes and owner rebinds preserve the coordinator. PageLive's optional onClose(reason, page) callback observes cleanup; mode and owner are reserved internal reasons. A callback that starts a successor prevents the old close operation from changing that successor.

Wire handling

Event Handling
r Read-only reading OOB fragments, matched by stable r- IDs
st Existing live nodes declared with data-live-event="st"
ap Existing live nodes declared with data-live-event="ap"
act Bounded {id,state,detail} JSON; boot emits flare:action
series Finite {id,key,p:[t,v]} samples in 64 rings of at most 60 points
rs One cancelled-stream, fresh-body reload, then a new connection
Comment Refreshes the 20-second quiet watchdog

Every data event must carry a valid integer ID. An accepted update advances the cursor; malformed or rejected updates do not. Reconnect requests carry that cursor in both seq and Last-Event-ID, preserving the other query fields. A resync may replace a stale or invalid cursor with the sequence of the freshly authorized page body.

The client accepts the server's 2000-5000 ms retry interval and backs off failed connections to at most 64 seconds. A comment or accepted data event resets the retry count. Connecting alone does not refresh stale values. Missing heartbeats abort the stream after 20 seconds; reconnect remains bounded. Redirects, authorization refusals and protocol errors stop the client. No redirect target receives the request or its cursor.

Read-only updates

The updater validates the complete frame before replacing any node. Each target must already exist once inside the page, declare the same event kind and retain its reading key. Duplicate or overlapping targets fail. Only bounded text elements and a closed attribute set are accepted; scripts, URL attributes, event handlers, SVG and nested identities fail. Reloads must contain exactly one canonical page root. Nested page or sequence attributes and IDs colliding outside that root are rejected.

Forms, editable controls and contenteditable regions are outside this subset. Their presence prevents both OOB updates and body replacement. An edit added while a reload is pending therefore survives. Unsupported markup stops the stream without applying a partial frame. This updater implements the read-only outerHTML contract; it is not a complete htmx implementation.

A stream becoming healthy preserves per-reading stale markers supplied by the server. Action details remain data: host handlers must render them as text. Existing chart binding can use onChange and chartSamples on the page client; it does not need a second legacy connection.

Integration gates

The owner cap covers pages using one stable worker identity. Direct PageLive callers and the legacy EventSource client do not participate. A host must bring every adopted stream path under one owner or keep legacy routes out of the shared origin before claiming an origin-wide bound. Visible-window fairness must be checked against the unchanged server limiter, including duplicate-page windows and slow authorization. Without a worker, several visible local-poll windows can still contend for that session budget; deterministic fairness is not claimed for that fallback. Host GET/HX admission and cancellation remain separate checks. An eight-page stress run establishes request bounds, not simultaneous hidden-page freshness. Those checks remain adoption gates. Host authorization, atomic schema/value/journal snapshots, complete schema pages, actual guest load and full M9 acceptance also remain separate gates.

Checks

Node tests cover parser boundaries, cursor resume, retry, cancellation and response refusal. Rust generates the browser's frames through Event::encode. Chromium and Firefox tests run over plain HTTP with CSP, including real 15-second comment pings, 20-second quiet detection, hostile HTML, edits, redirects and late reloads. Browser timings are diagnostic shared-host measurements, separate from device budgets.

node --test crates/flare-ui/tests/js/page-live.test.js
cd crates/flare-ui/tests/browser
node page-live.cjs
node page-owner.cjs
node page-live.bench.cjs