Skip to content

Asgard support in core - #665

Open
simonhamp wants to merge 55 commits into
mainfrom
idea/asgard
Open

simonhamp wants to merge 55 commits into
mainfrom
idea/asgard

Conversation

@simonhamp

@simonhamp simonhamp commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

This merges idea/asgard into main. It holds everything core needs for Asgard, the server-driven UI work. The Asgard client itself lives in NativePHP/midgard, and the spec in NativePHP/asgard-protocol. midgard requires nativephp/mobile at dev-idea/asgard until this lands.

What's in it

These parts also have their own PRs, to make review easier:

These went straight onto this branch:

  • 311c706: a keyed memo row that moved can skip its walk. Before, any move made the row rebuild.
  • 576377a: the iOS shadow-thread reader parses every published frame in order and copies its buffers. Dropped frames used to break REUSE markers and truncate fast-changing lists.

These go into this branch first, then come along with it:

Testing

On a real iPhone, the heimdall demo streamed 60 new rows a second into a 1,000-row list for 60 seconds. It stayed smooth all the way through and the scroll position held. That build used #700 and mobile-ui's new lazy_stack element (NativePHP/mobile-ui#215).

Each PR above lists its own test counts and what isn't verified yet. The biggest gaps are Android on a real device and the Swift unit tests, which don't run under xcodebuild because the test target can't link Bridge and PHP.

🤖 Generated with Claude Code

simonhamp and others added 30 commits November 7, 2026 10:50
NativeComponent called the developer's method from many separate places:
polls, native event listeners, component event listeners, a child's @event
binding (two places), and each kind of UI callback. Anything that has to
happen on every call had to be added to each of them, and a path that got
missed failed with nothing to show for it. That already happened once, when
a guard went onto the tap path only and methods reached by a poll or an
event quietly stopped working.

All of them now go through runAction(), which takes an ActionSource saying
what triggered the call. It applies the callable guard where the source
needs it and then calls callAction(), which apps and packages can override
to wrap every path at once.

Which sources are guarded is decided in one place, ActionSource::guarded().
Names chosen by a template or the device (taps, search, virtual window,
text selection, drag end, @event bindings, native events) must pass
ComponentMethodInvoker's check: public, not static, not a lifecycle hook,
not declared on NativeComponent. Names chosen by an attribute on the method
(#[Poll], a component #[On]) are not, so those can stay protected. This
matches what each path did before.

The guard runs before callAction(), not inside it, so an override that
never calls parent cannot widen what a template or device event can reach.

One behaviour change: the gesture area's @Dragend callback called the
method directly, skipping the guard, the validation error handling and the
event flush that every other UI callback gets. It now goes the same way as
the rest, so a @Dragend bound to a protected method is refused.

Left out on purpose, with the reasons in the docblock: the closure in
fireNativeCallback, #[Computed] getters and updated{Property} hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
firePoll(), firePolls() and search() invoked the developer's method
directly instead of going the way the runloop does. Anything hooked onto
callAction() was invisible to a test driven through the harness, so a test
could pass for a method that does nothing in the real app. They now go
through runAction(). call() already used __invokeInteraction(), which leads
there too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each route is driven end to end and must reach callAction() with the right
source and arguments. A second test has callAction() refuse to delegate and
checks that no handler runs by any route, and that every ActionSource case
was seen, so a new source cannot be added without a test here.

The guard tests check that a name chosen by a template callback or a
child's @event binding cannot reach a protected method, a lifecycle hook or
NativeComponent's own public methods such as run() and stop(), including
when a callAction() override skips parent. A protected #[Poll] method still
runs. The table of which sources are guarded is pinned, so changing it is a
visible, reviewed change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
First pass at the wire contract for server-rendered regions of a native
screen. Written as a protocol rather than package docs because the server
half is meant to be replaceable - asgard and midgard are the reference
implementations, not the definition.

Two things in here differ from the original sketch and are worth a look.
The handshake returns a session secret separate from the session id, so
the encryption key never travels after the handshake; using the id as key
material would have left a logging proxy able to decrypt everything it
logged. And servers return no node or callback ids, only names and
expressions, because ids are namespaced to a position in the client's
tree that a server has no way to know.

Transport is still open. QUERY is right on the merits but needs testing
through real infrastructure before we commit to it with no fallback.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
Callbacks resolve today through a bare method_exists(), which is fine
while only the app's own Blade names a method. Once the expression comes
from a server (ASGARD-PROTOCOL.md §10) that surface is every public
method on the component.

This is the marker only. Nothing dispatches on it yet, but shipping it
now means components can be written against the final rule rather than
retrofitted when the event workstream lands.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
A view marks part of a screen as server-rendered:

    @server('sales-summary')
        <x-skeleton-card />
    @endserver

The block opens a server_region node, the body renders as its children,
and that is what the screen shows until a fragment arrives. No fragment
means the placeholder stays, which is the intended degraded state rather
than an error (ASGARD-PROTOCOL.md §3). Nothing fetches anything yet:
Asgard\ServerRegion::applyFragment() is the seam a transport will feed.

Two things get namespaced to the region, both by reusing machinery that
already exists rather than hashing anything here. The region node is
keyed with its name, so Element::toArray() and the streaming key-path
stack both land a fragment node with relative key "total" at
/sales-summary/total instead of at the root. And fragment callbacks
register into a CallbackRegistry scoped "server:<region>", pinned on the
region node so toArray() hands it to every descendant. Placeholder
callbacks are deliberately left in the screen's scope, since the
placeholder is the client's own markup.

Duplicate region names in one screen throw when app.debug is on and get
suffixed (sales-summary#2) otherwise, following the same trade §5.3
makes for prop drift. The first region keeps working; the duplicate
resolves to nothing and keeps its placeholder.

applyFragment() validates before storing. A fragment naming a type this
build does not have would otherwise throw out of createElement() and
take the whole screen down. Chrome types are refused outright: a region
is a subtree and a nav bar is not its to place.

Supporting seams: NativeElementCollector gained callbacks() and
openElement() so a caller can scope a subtree it just opened, and
setCallbacks() takes null so that scope can be put back exactly as
found. NativeComponent marks the frame boundary for the region record,
rather than the collector's reset(), because a screen returning a
programmatic Element tree never touches the collector and has to read as
having no regions.

The renderers don't know server_region yet. A region is visible in the
tree the client builds but won't paint on a device until they map it to
a plain container.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
Covers the Blade path end to end (placeholder as children, fragment
replacing it, node keys and callback ids landing in the region's
namespace rather than the root, duplicate names, rejected fragments) and
the same primitive through a real screen render, where a region with no
fragment has to leave the rest of the screen working.

The last test there is the one that caught the frame-record bug: a
screen with no regions must report none, not the previous screen's.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
Building the region primitive turned up gaps in the protocol draft. The
node shape was never defined, so anyone writing a non-PHP server had
nothing to write against. Node ids and callback ids were described as one
namespacing rule when they are two, and getting only the first right
leaves fragment callbacks colliding with the screen's own.

The security one is worth reading. props is a free-form bag authored by a
server, and the collector's attribute vocabulary includes spellings that
are not presentational. A server writing _press into props would pick
which client method runs, which walks straight around the NativeAction
rule. Keys starting _, native- or native: are stripped.

Also documents #[Server] methods in a companion file: a client method
whose body runs locally, returns a closure, ships the resulting state to
a server and runs the closure when it answers. The response applies as a
delta under compare-and-set against what was sent, so a field the user
edited while the request was in flight is not overwritten.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
QUERY can't be the only transport. OWASP Core Rule Set ships
tx.allowed_methods=GET HEAD POST OPTIONS as its default and blocks
everything else at paranoia level 1, which is on by default. CRS rides
inside Cloudflare managed rules, Azure DRS and Google Cloud Armor, so the
failure follows any customer who switches on a managed WAF rather than
being one vendor's problem. Akamai has no configuration path to allow it
at all. Both CRS defaults verified against the ruleset.

The fallback header has to be package-owned. All three conventional
override names are in the same ruleset's blocked header list, and
CloudFront strips one of them anyway.

Also killed the edge-caching idea. Nothing in front of the app caches
QUERY, and Fastly drops the body on cache lookup in a way it documents as
not overridable. In-app caching still works.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
A #[Server] method is the imperative half of Asgard: the body runs on
the client, the work happens on a server, and a closure runs on the
client when it answers. This is the vocabulary for that, with no
machinery behind it yet.

ServerTransport has one method and it does not return the answer. PHP on
device runs a blocking runloop, so an HTTP call made from PHP freezes the
UI for the whole round trip, which is the thing the closure design exists
to avoid. An implementation starts the request and hands back the id the
response will arrive under; the response comes back separately on the
event channel the runloop is already blocked on.

Until the native side of that exists, the bound transport is one that
always fails. That is not a fatal by choice: an unsent request takes the
same path as a device with no network, so a screen written against
#[Server] behaves correctly, loading flag cleared and error branch run,
before there is anything to send with.

ServerRequest carries the method name, its arguments and the state
snapshot, and nothing else. The closure is not in it and cannot be: it is
a PHP value held on the device, never serialised or inspected.
ServerResponse is what the closure receives, and it carries the refused
props as well as the applied ones so a developer can react to a refusal
rather than noticing it on screen.

ComponentAddress is the §4 dot-notation conversion in one place, so the
region and #[Server] workstreams cannot drift on what a component is
called. It only runs one way. Turning the identifier back into a class
name on the server is arbitrary object instantiation, which is why the
protocol forbids it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
Three jobs. Invoke: run the client body, snapshot the component's public
state after it returns, hand method plus args plus state to the transport
and keep the closure. Deliver: a response arrives as an EVENT_NATIVE
frame, because the request was performed natively while PHP blocked, so
dispatchNativeEvent routes it here before any listener sees it. And
reconcile.

Reconciliation is the part with teeth. The server returns a delta of the
props it changed, and each one is applied only if the client's current
value still equals the value that request sent. A field the user typed
into while the request was out has diverged, so the server's value is
refused and the edit survives. Out-of-order responses and ABA fall out of
the same rule with no sequence numbers: a stale response loses on any
prop a newer one already changed, and a value changed and changed back
matches what was sent, so the server wins, which is right because the
client's value is the one the server was reasoning about.

What is stored per request is a fingerprint, not the value. A snapshot
that held the values would hold the same object instances the component
still holds, so mutating a prop in place would mutate the "sent" copy too
and the compare would say nothing had changed. Serialising at send time
freezes it, and has the side effect that an equal-but-rebuilt object
reads as unchanged, which is what "still equals" ought to mean. Values
that will not serialise fall back to identity, which errs towards
refusing the server's value.

The pending table is static and keyed by request id. The response frame
is delivered to the component that owns the runloop, which is the screen,
but the request may have come from a child several levels down, and
several components can have calls in flight at once. An entry holds a
closure bound to its component, so it keeps a live screen reachable and
has to be dropped on unmount; a response arriving after that is
discarded, closure and all. The WeakReference is a backstop that only
helps for a call with no continuation, since a closure holds its $this.

Props are written by reflection over public properties rather than
through __syncProperty. That path is for user input: it fires updatedFoo()
hooks and refuses #[Locked] props. A server delta is neither. #[Locked]
exists to stop a binding writing a prop, not to stop the server that owns
it. Public-only is also a boundary, not a convenience, since it means a
delta can never reach the native* internals a component keeps protected.

A response may carry fragments for regions, and they go through
ServerRegion::applyFragment() rather than around it. Same validation,
same stripping of compiler-internal prop keys. A server that could write
_press into props would be choosing which client method runs, and
arriving by this route rather than a region render changes nothing about
that. applyFragment throws instead of returning false when app.debug is
on, so that is caught here: the closure always runs unless the component
is gone, and the reason is reported on the response instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
FakeServerTransport records what would have been sent and hands back an
id. Nothing resolves on its own, which is the point: the cases worth
testing are the ones where timing is wrong. A response that overtakes an
older one, a response for a screen the user has already left, a request
that cannot be sent at all.

Two ways to answer, both real. resolve() and fail() hand the frame to
ServerMethods::deliver(), and payload() builds the frame so a test can
push it through emitNative() instead, which goes down the event channel
and re-renders like the runloop does.

TestableComponent::call() routes a #[Server] method the way dispatch()
does. Calling one directly runs the client body and hands back a closure
with nothing to resolve it, so a harness that called it directly would
quietly test the wrong thing.

The tests cover what the design promises: the state the client body left
behind is what gets sent, the closure runs bound to the component, a prop
the user changed mid-flight is kept while one that did not move is
overwritten, out-of-order and ABA resolve as §5.2 says they will, a
response for an unmounted component is discarded with an empty pending
table behind it, and a failure runs the closure with no delta applied.
Two more pin down decisions the docs left open: an object prop mutated in
place counts as moved, and a #[Server] method that returns no closure
still applies its delta.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
Seven things the draft got wrong or left unsaid. The one that would have
shipped as a data-loss bug: section 5.2 never defined equality, and the
obvious implementation is wrong for object props. The pending table holds
the same instance the component holds, so mutating it in place mutates the
sent copy too, every comparison says unchanged, and the user's edit gets
overwritten by the server. Comparison is on serialize() fingerprints taken
at send time.

The biggest remaining problem is the shape itself. A direct call to a
#[Server] method runs the body, hands back a closure and sends nothing,
silently, because there is no way to intercept an ordinary method call in
PHP. Dispatch is intercepted on the tap path and there is an explicit
entry point, but the API as designed invites the mistake. Fixing it means
returning a request object rather than a closure, so it is written up as
the open question that decides whether this shape survives.

Also: delivery never throws, because the debug-drift rule collided with
the promise that the closure always runs. The response comes back to the
component that owns the runloop, not the one that made the call. And the
closure holds its component through , so weak references buy nothing
and clearing on unmount is the only mechanism that works.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111NTS4Y1rDiTwy6treMeiN
Main replaced the old dispatch() with dispatchUiEvent() and sends every
template-named method through __invokeInteraction() and
ComponentMethodInvoker. The #[Server] check now sits in
__invokeInteraction(), and ServerMethods::call() runs the client body
through the invoker, so the attribute can only narrow what a tap may
call. Adds tests for both, and updates the design doc to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Neither renderer knows server_region. Element gets a wireType() that
toArray() and the streaming collector read when they hand a type name
to native, and ServerRegion returns column from it with no props of its
own. The key still travels, so fragment nodes stay under /<region>/.
getType() is unchanged, so validation still refuses a region inside a
fragment. Both iOS and Android already paint column as a vertical
container, so there is no native change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
native:package shares RunsAndroid but has no --watch option or udid
argument, so PHPStan flags the reads on main. Guard them the way the
trait already guards --fresh. No change for native:run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds the client half of fetching a fragment. After a frame, every region
that painted its placeholder asks the bound FragmentSource once, per
component instance, with a RegionRequest carrying the component address,
region, JSON-safe public state and platform. refreshServerRegions() asks
again after the next frame and keeps the current fragment up meanwhile.
Both render paths do this.

Fragments are now held per component instance instead of by region name,
so two screens, or two mounts of one child, no longer share a fragment.
A region inside a child component belongs to the child.

Delivery goes through ServerRegion::deliver() or
NativeComponent::receiveFragment(). It drops answers for superseded
requests and unmounted components. An AsyncTask completion already
re-renders; a fragment that lands outside an event makes the runloop take
an extra turn.

NullFragmentSource is bound by default and FakeFragmentSource covers
tests, like the #[Server] transport.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The null ServerTransport and FragmentSource were bound with a plain bind().
Package providers register in an order neither package controls, so when
midgard's provider ran first, mobile's default replaced the HTTP source it
had just bound and every region stayed on its placeholder. They are
defaults, so they are now bindIf().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Section 7 described its own HMAC and AEAD scheme. It now points at HTTP
Message Signatures and the aes128gcm content encoding instead, and says
which components each side signs, how the four keys are derived from the
session secret with HKDF, and that keyid is the session id. Responses
cover the request's signature so a fragment only verifies against the
request it answers. Key agreement stays out of scope and is a new open
question.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fragment callbacks need runAction() and ActionSource. The conflict in
__invokeInteraction keeps the #[Server] check first and sends
everything else through runAction().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fragment callback slot is now an object, never a string:
{"call": "shuffle", "args": [3, "x"], "target": "server"}. The
target defaults to server and can be "client". A slot with any other
shape is dropped and logged, or throws when app.debug is on.

A server target sends an ActionRequest through the new
FragmentSource::action(). It is a RegionRequest for that region with
the current state, plus the call and args, and its answer comes back
through ServerRegion::deliver() like any other. Nothing runs locally.

A client target runs a method on the component that owns the region,
through runAction() with the new ActionSource::FragmentClient. The
method must pass the usual guard and carry #[NativeAction]. Args are
passed as they came, so class-typed, callable and by-reference
parameters are refused and nothing is coerced. A refused call runs
nothing and never falls back to the server.

Fragment callbacks keep their own server:<region> registry, now held
per component and chained after a child's scope. What an id resolves
to carries its target. An id that more than one scope claims is
dropped, so a fragment cannot reach the screen's callbacks or another
region's. Placeholder callbacks are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A pushed fragment (from an SSE stream) has no request id, so deliver()
drops it. ServerRegion::push() takes a component address and a region
instead, and paints every live instance of that component that asked
for that region. A region the screen never declared gets nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Section 10 now says how a fragment's callback slots are shaped, that a
tap runs on the server unless the slot says target client, and which
checks each side makes before running anything. A client action needs
#[NativeAction] in the app and never falls back to the server. A server
action needs #[Action] and takes plain values only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The handshake now agrees the session secret with ephemeral P-256 ECDH and
HKDF, so the secret never crosses the wire. §7.1 says what that covers: a
logging proxy learns nothing usable, and an active TLS-terminating attacker
is still TLS's job. asgard_key is a public identifier the server checks,
and the asgard_secret language is gone.

§7.3 now says authorization is covered only when the request has it, lists
the exact parameters, and pins down the nonce for server actions. §6.2 says
where the client keeps its session and why.

New §8.1 covers the push stream: the opening request is signed like a
region request, each event is encrypted with enc_s and carries an HMAC
bound to the stream request's signature, and every reconnect is signed
afresh instead of replaying the old request.

§12 question 6 is settled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
§7.4 now says the server gzips a fragment of 1024 bytes or more before
encrypting it, marks it with the signed Asgard-Content-Coding header, and
that the client stops inflating past 8 MiB. It explains why the stacked
Content-Encoding is not used (Cloudflare rewrites it) and when a region
should opt out because of BREACH. §8.1 adds "enc" to events and to their
signature base, and §6.3 says what the client does with failures only it
can see.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A server route now opens Asgard\ServerScreen, a generic screen whose
body is one region named `screen`. It asks under the server screen's
address with the route parameters and query as state, shows a skeleton
until the answer lands, and handles actions and pushes like any region.

NativeRouter keeps server routes in their own table, replaced as a whole
by registerServerRoutes(). They are matched after every app route, so a
server route can add a screen but never replace one of the app's. Each
entry is checked again here and bad ones are dropped.

A server screen's chrome comes with each answer and push. ServerChrome
checks it against a closed vocabulary, and ServerLayout turns it into the
same NavBar and TabBar builders a layout feeds, so both chrome paths work
unchanged. Chrome buttons register in the screen region's callback scope.
NativeComponent::chromeLayout() is the new seam for this.

Callback slots can navigate: {"navigate": "/path", "replace"?,
"transition"?} or {"back": true}, in press slots only. The tap goes
through only when the path matches a route the app knows, app or server.
There is no way to reach the web from a fragment.

AsyncTask gains anyScreen(), for app-wide work whose answer should land
on whichever screen is showing. midgard uses it to refresh the routes.

The protocol doc now says the client owns the shell and the server may
own screens inside it, adds §12 on screens, chrome, the route list and
navigation, and settles open question 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Server routes only live in NativeRouter, so a request for one went to
Laravel's router and got a 404. That broke cold deep links and the
hot-reload restore to a server screen.

A new device-only middleware, OpensServerRoutes, handles a page load (or a
direct dispatch with no Accept header) when no Laravel route matches the
path and a server route does. It runs the same entry Route::native() runs,
with the generic ServerScreen. Laravel routes keep priority. A fallback
route does not count as a match. Assets, XHRs and other methods pass
through.

The Route::native() closure moved into NativeScreenEntry unchanged so both
can share it. NativeRouter::start() now passes the screen address to a
ServerScreen it launches, which it did not before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds §9.5 on server Blade, including how @Navigate compiles and why it
cannot share an element with @press. §1 and §3 now say Blade is compiled
on the server and never crosses the wire. §4 describes the explicit
component map the code uses instead of autodiscovery. The §9.1 example
shows on_press as an object. §12 covers Blade screen bodies and chrome
views, and how a deep link or hot-reload restore opens a server route.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A push stream is opened per component address with the state of the
latest region request. ServerRegion::push painted every live instance
of that address, so opening /promos/2 on top of /promos/1 pushed Promo
2's body and chrome into the Promo 1 screen underneath. Going back from
Promo 2 then popped correctly, but the screen it landed on looked
exactly like the one it left, so the pop looked like nothing happened.

Each owner now remembers the state it sent with its latest region
request, and a push only lands on owners that asked with the state the
stream was opened with. Instances that asked with the same state are
all still painted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A screen pushed on top with the same address and other state (/promos/2
over /promos/1) takes over the address's push stream. When it pops, the
screen underneath now fetches its regions again on its next frame if the
stream carries other state. That catches up on what it missed and the
answer reopens the stream with its own state. Regions whose stream still
matches are left alone.

The router and test harness resume screens through a new
NativeComponent::resumeComponent(), which calls the hook before onResume().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
simonhamp and others added 12 commits November 13, 2026 00:07
The protocol's push stream (§8.1) is now one stream per device, carrying a
subscription per component instance on screen. The doc is rewritten for it:
the subscription list, version tokens, signals by default with shared
regions sent inline, a 5 second ping, and the cost of one server worker per
device. Two open questions are added, on that cost and on bursts of fetches
after a wide push.

ServerRegion works the set out from live owners: each region with a good
answer, grouped by address and the state it was answered for, with a
subscription id hashed from the address and canonical state. sync() hands
the set to the FragmentSource through a new watch() method when it changes.
It runs at the end of every frame and after the router unmounts a screen,
so a navigation makes one call and unmounting the last owner drops its
subscription. An empty set closes the stream.

Pushes are matched to owners by the subscription's state, so /promos/1
under /promos/2 gets its own. A signal makes each matching owner whose
version differs refresh the region, as refreshServerRegions() would. A
covered screen asks when it is drawn again. A shared region's fragment
paints directly through push().

That makes the resume workaround from 91fc5ac unnecessary, so the stream
state tracking, resumed(), lostStream() and resumeComponent() are gone and
the router calls onResume() again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A server screen whose body has not arrived 15 seconds after its first
frame gives up. So does one whose body request fails outright (network,
server error, a fragment that fails verification or cannot be rendered),
without waiting. It goes back to the screen below, or replaces itself
with / when there is none, and ServerScreenFailed fires once that screen
is live, so it hears it with #[On]. Once a body lands the timer is off.

Server actions and #[Server] calls wait 15 seconds for an answer. A
timeout or hard failure fires ServerActionFailed on the screen that sent
it, with the action, address, region, reason, status and request id.
#[Server] closures still run with a failed response as before.

Transports report failures through the new ServerRegion::failed(). The
runloop acts on due timers at the top of each turn and wakes for the
next deadline with no input. A covered screen's timers wait until it is
on top again. Late answers are dropped.

Config: nativephp.asgard.screen_timeout, action_timeout, and screen (a
ServerScreen subclass every server route opens). Overrides:
ServerScreen::screenTimeout() and NativeComponent::serverActionTimeout().
The test harness gets wait(), and FakeFragmentSource gets fail() and
failAction(). follow() now opens a server screen for its address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A call now carries the platform, as a region request does, so the server
can validate it like any other request.

An answer can arrive while the transport's send() is still running, before
the call is in the pending table. A faked lane in a test does that, and so
does a real lane that fails before it starts. ServerMethods holds such an
answer and delivers it once the call is registered.

The spec now describes the transport that exists: midgard runs the call on
an AsyncTask lane, the same way region fetches go out, and hands the answer
to ServerMethods::deliver(). The protocol doc gains §10.5 for the call
endpoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An @server region request now waits 15 seconds for its fragment. That
covers the first fetch, refreshServerRegions() and a fetch a stream
signal started. A timeout, or a hard failure reported through
ServerRegion::failed(), fires ServerRegionFailed on the screen the
region is on, so #[On] with when: ['region' => ...] works. The event
carries region, component, reason, status, message, requestId and
placeholder, which is true when no fragment ever landed. That lets a
view swap its skeleton for an error message.

A failed region keeps what it had and is not asked for again on its own,
so a server that is down is not hit on every frame. The app retries with
refreshServerRegions(), from the handler or a retry button. Late answers
are dropped, superseded requests fire nothing, and a covered screen's
timers wait until it is on top again.

A server screen's own body keeps its own timer and ServerScreenFailed,
and never fires ServerRegionFailed. In debug, a region fragment that
cannot be rendered still throws, and the event fires as well.

Config: nativephp.asgard.region_timeout (0 turns the timer off).
Override: NativeComponent::serverRegionTimeout().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… fetches

An action or #[Server] call answer can carry other regions of the same
component (refresh() on the server). ServerRegion::paintInline() paints
them on the instance that asked, only for regions it drew, and skips a
region with a request sent after this one. A painted region supersedes
older requests still in flight. ServerMethods now uses it in place of its
own applyFragments loop.

A refresh hint names another component and maybe a region. hint() marks
every live instance that drew it, like a stream signal with no version, so
it fetches with its own state on its next frame. Marks collapse, so many
hints and signals before a frame make one fetch.

When one instance wants several regions after a frame, they go out as one
RegionBatch through the new FragmentSource::batch(). Each region keeps its
own request id, timer and failure. deliverBatch() and failedBatch() answer
them. Docs cover all three cases in protocol 3.1, 8.1, 10.2 and 10.5 and in
SERVER-METHODS 2 and 4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A server route may now carry a title template, like 'Promo #{id}'. The
router keeps it with the route (or drops it, keeping the route, when it
is not plain text of 1 to 100 characters) and the screen shows it with
the route parameters filled in from its first frame. Unknown
placeholders are removed and the query string is never read.

A route without a template shows a placeholder instead. It comes from
ServerScreen::titlePlaceholder(), which a subclass can override, and
defaults to the titlePlaceholderUsing() callback or __('Loading…').

The screen no longer starts in the chrome its address had last time.
That made /promos/2 open under the title and buttons of /promos/1, and
restoring stale actions before the body arrives is not clearly right,
so the whole per-address memory is gone.

Once chrome arrives it is used as sent, except that a nav bar with no
title of its own shows the route title. The placeholder never comes
back after the body lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Simon found the early title caused odd behaviour, so screens go back to
borrowing the last chrome for their address for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A relative src in an app view is one of the app's shipped assets, and a
path starting with / is a file on the device. From a server neither means
what the author meant, and a server should not be able to show the app's
own files. So a fragment, or server chrome, may only carry absolute https
media URLs, plus http while app.debug is on. Anything else rejects the
fragment like any other unsafe content.

The check is on prop names (src on any element, leadingAvatar and
leadingImage) so plugin elements are covered. A webview in php mode is
refused too, since it opens the app's own routes. App views are not
affected. Protocol 9.3 and a new 9.6 describe the rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
refreshServerRegions(), serverActionTimeout(), serverRegionTimeout(),
receiveFragment() and callServerMethod() now live on
Native\Mobile\Edge\Asgard\Concerns\UsesServer instead of NativeComponent.
A component opts in with `use UsesServer;`.

Regions still work in any component. Core reads the timeouts through
ServerRegion::actionTimeout() and regionTimeout(), which use the
component's override when it has one and the config otherwise. Unmount
cleanup stays in core.

A #[Server] method needs the trait, since callServerMethod() is the only
right way to call one from code. ServerMethods::call() throws a
LogicException with app.debug on, and logs a warning and sends the call
without it.

The interaction guard now refuses every UsesServer method, by name in any
case and by file for aliases, because the trait puts them on the app's
class where the NativeComponent check does not see them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
UsesServer gets uploadToServer($method, $path, ...$args). It has no client
body and no closure. It checks the path is a readable regular file (not a
directory, symlink, stream wrapper or NUL path), snapshots the state and
hands an UploadRequest to a new UploadTransport contract. From there the
request sits in the same pending table as a call, so the answer gets the
same compare-and-set delta, inline fragments and hints.

The file is named by path and read on the transport's lane, never on the UI
thread. Over nativephp.asgard.upload_max (20 MB) it fails before sending
with reason too_large. A bad path fails with reason unreadable. Uploads wait
nativephp.asgard.upload_timeout (120s) rather than the action timeout, and
a component can override serverUploadTimeout(). The interaction guard
already refuses both new trait methods by name.

UploadTransport is its own contract so call-only transports keep working.
NullUploadTransport fails as network, and FakeServerTransport takes uploads
too. Protocol §10.6 and SERVER-METHODS §10 describe the wire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#[ServerAddress('home')] on a client component makes its region requests,
#[Server] calls and uploads go to `home`, and only pushes for `home`
reach it. Without it the address is still the class name in dot notation.

This keeps the client's class name out of the protocol, so moving or
renaming the class no longer needs a server config change. The attribute
is not inherited. Protocol §4 covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in the handler expression fix (#677). Child event bindings now
run through runAction() with ActionSource::ParentBinding, so property
handlers and the action pipeline both apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
simonhamp and others added 3 commits November 14, 2026 17:36
Main gained handler expressions since the pipeline was written. A
child's @event binding now goes through invokeChildEventBinding(),
which runs the parent's method via runAction() with
ActionSource::ParentBinding. Property handlers and unknown methods are
handled before that, as main does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds ActionSource::Remote for a call where something outside the app,
for example a server, picks the method name and the arguments. Such a
call may only reach a public method marked #[NativeAction] that passes
the usual callable guard. Every parameter must take plain values (no
class types, callables or references) and each argument must already
match its type. The arguments are passed as they are, with no container
injection or model binding.

The check runs in runAction(), which is private, so a callAction()
override cannot skip it. A refused call throws
RemoteActionNotAllowedException.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
simonhamp and others added 5 commits November 14, 2026 17:56
The spec now lives at https://github.com/NativePHP/asgard-protocol, so
the copy in docs/ is gone and comments cite "Asgard protocol §N".
ASGARD-SERVER-METHODS.md stays here, as it describes this package's
PHP API rather than the wire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Element::wireType() lets a PHP-only element reach the renderers as a type
they already know. The collector gains accessors for its bound registry,
open element and owner, and setCallbacks() takes null so a caller can put
back what it found. CallbackRegistry reads expressions through a
protected parseExpression(), NavBar and TabBar accept prebuilt elements,
and NativeComponent::chromeLayout() is the one place a screen's layout
is built. PendingAsyncTask::anyScreen() runs completions on whichever
screen is on top.

The body of Route::native() moves to Http\NativeScreenEntry so a package
can open a screen from its own route or middleware the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A RunloopExtension registered with NativeComponent::extend() is called
around each frame (both render paths), can ask the loop to wake with
nextWake(), takes a tick() at the top of every turn, can claim a native
event before the app's listeners, can answer for UI callback ids it
registered, wraps every developer action through aroundAction(), and is
told when a component unmounts.

Two rules stay in core. A callback id that more than one scope claims
(the screen and an extension, or two extensions) is dropped and logged,
since an extension's ids may come from outside the app. And
aroundAction() runs inside runAction() after the callable guards, with a
$next that takes no arguments, so a refused call never reaches an
extension and none can swap in a method the guards did not see.

The test harness gains wait(), which moves Carbon's clock and takes the
idle turn the loop takes when it wakes on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ComponentMethodInvoker::reserveTrait() keeps every method a trait
declares out of reach of templates and remote calls. A package uses it
for a trait whose public methods are plumbing it calls itself. On a
component that uses the trait the methods are refused by name in any
case, so an override on the app's class is refused too, and a method
brought in under an alias is refused by the file it comes from. A
component that does not use the trait keeps its own same-named methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NativeRouter::setRouteTable() lets a package add routes while the app
runs. Each entry names a screen class and a context. Tables are matched
only after every app route, so a table route never shadows one of the
app's, even a parameterized one, and an entry whose pattern the app
already has is dropped. clearRoutes() clears them. routeEntryFor() says
which entry a URI opens.

The entry's context reaches the screen through a new
NativeComponent::setRouteContext() before mount(), in the router and in
the harness's visit() and follow(). It does nothing by default, and a
template can never call it.

The harness now fires ScreenMounted, ScreenResumed and ScreenUnmounted
where the router does, so a package listening for them behaves the same
under test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
simonhamp and others added 5 commits November 14, 2026 18:01
The runloop, router and invoker now take the general hooks from
feat/extension-hooks in place of the Asgard calls that were wired into
them. The Asgard classes themselves move to midgard in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Everything Asgard on the device side now lives in nativephp/midgard and
plugs in through the runloop hooks from feat/extension-hooks: the
@server regions, server screens and routes, #[Server] and uploads, the
events, the middleware, the fakes and their tests. An app without
midgard ships none of it.

What is left on this branch next to feat/extension-hooks is the
RunsAndroid option fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It pairs with #[ServerAction] on the server side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A kept #[Memo] root answers with a REUSE marker only when it sits where its
last walk did. That place included its index in the parent, so prepending to
a list moved every kept row and walked them all again.

A keyed element's id comes from its parent's key path and its key, and its
descendants' ids hang off that path, so the index plays no part. The place
now uses the key when there is one and the index otherwise. Nothing under a
key takes a positional id, so restoring nextId on the shortcut stays right,
and the emitted-ids check still guards against collisions.

Tests cover a keyed row that moves (answered without a walk), an unkeyed row
that moves (still walked), and that the published frames match a full walk
for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The subtree memo sends a REUSE marker for any node PHP sent in the frame
before, so the reader has to have parsed that frame. Two things broke
that on the firehose screen (a 1,000-row list taking 60 rows a second):

- The shadow thread kept only the newest pending frame and dropped the
  rest unparsed. A row that first came in a dropped frame was unknown
  from then on, PHP kept reusing it until its heartbeat, and the reader
  dropped it.
- With the double buffer flag the reader viewed the extension's buffer
  without copying it, which only holds until the publish after next.
  A heavy frame could be read half overwritten.

On top of that, a REUSE miss ended the parent's child loop, so every
row after the missing one went too. The list collapsed to the rows added
since, its content shrank, and it jumped back to the top. That happened
after nearly every heartbeat.

Now postTreeUpdate always copies the buffers, the shadow thread parses
every queued frame in order and only hands the newest to the main
thread, and a missed REUSE drops just that node. Android has the same
coalescing and the same break and is not changed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@simonhamp simonhamp changed the title Asgard client: server-rendered regions Asgard support in core Nov 15, 2026
@simonhamp
simonhamp marked this pull request as ready for review November 15, 2026 15:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant