A2UI icon indicating copy to clipboard operation
A2UI copied to clipboard

Implement Node Layer Architecture across Core and Renderers

Open jacobsimionato opened this issue 7 months ago • 11 comments

This is a proposal based on a comment that @yjbanov made on the original design for web_core. After thinking about it a bit more and seeing how the libraries evolved, I think he was right!

Description and Rationale

We are introducing a "Node Layer" architecture into the A2UI core libraries and refactoring the existing rendering frameworks (React, Angular, Lit) to consume it.

Currently, frameworks are responsible for complex tasks: traversing the flat SurfaceModel adjacency list, resolving data bindings using GenericBinder, handling template expansions (e.g., ChildList), and managing subscription lifecycles. This causes duplicated logic across frameworks, risks memory leaks due to forgotten binder disposals, and makes adding new framework adapters difficult.

The Node Layer centralizes this "business logic" into the core library. It transforms the flat component map into a living, reactive view hierarchy. Renderers will simply receive fully-resolved, type-safe Node instances and focus solely on mapping them to native UI primitives (pixels).

Detailed Architecture & Design

The Node Layer represents a shift from frameworks directly managing components and data to having the SurfaceModel manage the entire view hierarchy lifecycle.

1. Core Data Structures: The Node

The new architecture introduces a Node<TProps> interface. A Node represents a living, fully resolved component instance in the view hierarchy. By utilizing generics, the Node interface provides type-safe property access to the rendering frameworks.

  • instanceId: A stable, unique identifier for this instance in the rendered tree. For templated nodes, this incorporates the data path (e.g., 'item-card-[/users/0]') to ensure React/Flutter keys remain stable.
  • props: A reactive Signal<TProps>. Dynamic values are primitive strings/numbers/booleans, Actions are callable () => void closures, and Structural props (e.g., child or children) contain actual child Node references (not string IDs).
  • Lifecycle: onDestroyed event and a dispose() method.

2. Internal Node Engine inside SurfaceModel

The management of the Node tree is an implementation detail inside SurfaceModel. Because SurfaceModel encapsulates both the DataModel and the SurfaceComponentsModel, it is perfectly positioned to handle this.

  • Public API: SurfaceModel exposes a single, reactive rootNode: Signal<Node | undefined>. Frameworks simply subscribe to this signal.
  • Internal Engine: The SurfaceModel internally tracks SurfaceComponentsModel changes and DataModel mutations. It manages a private cache of active nodes, automatically instantiating and destroying child nodes as requested by layout containers.

3. 1-to-N Mapping for Templates (ChildLists)

A primary responsibility of the internal Node engine is managing the 1-to-N mapping between a single ComponentModel and multiple rendered Node instances. When an A2UI payload contains a ChildList acting as a template (e.g., a Card with ID "user-card" iterating over /users), it will be rendered multiple times.

  • The internal engine handles subscribing to the DataModel array path (e.g., /users).
  • If the array has 3 items, the engine spawns 3 unique Node instances for the same componentId.
  • Each spawned node receives its own instanceId, scoped dataPath, and an isolated GenericBinder to resolve its properties.
  • If the array length changes (e.g., a 4th user is added), the parent node detects the array mutation and spawns a 4th Node, emitting an updated ChildList prop containing the 4 nodes.
  • When destroyed (e.g., a user is deleted), the Node fires onDestroyed, disposes its GenericBinder, and destroys its children.

4. Soft Transition for Adapters

Framework adapters will expose Node objects for structural properties, but will maintain backward-compatible shims so component authors don't have to rewrite all their UI code immediately.

  • buildChild Overload: The buildChild helper will accept child: string | Node. If it receives a Node, it renders it directly.
  • Node.toString(): Implement Node.prototype.toString() to return its componentId, preventing breakage for logic using ID comparisons.

jacobsimionato avatar Apr 27 '26 06:04 jacobsimionato

Coding agent prompt:

Goal: Implement the Node Layer architecture in A2UI and migrate the framework renderers (Angular, Lit, React) to use it with a non-breaking soft transition. This involves moving hierarchy resolution, template expansion, and data binding lifecycle management from the framework layer into the framework-agnostic core (web_core).

Rationale & Architecture Overview

Currently, frameworks independently traverse the flat SurfaceModel adjacency list and manually manage GenericBinder instances. This duplication causes inconsistencies, memory leaks, and high complexity for new renderers.

The Node Layer centralizes this logic into a reactive, living view hierarchy. Because the SurfaceModel encapsulates both the DataModel (for bindings/templating) and the SurfaceComponentsModel (for definitions), it is perfectly positioned to manage this hierarchy. SurfaceModel will expose a single, reactive rootNode: Signal<Node | undefined>.


1. Core Implementation in web_core (@renderers/web_core/src/v0_9/)

1.1 The Node Interface

Define a living representation of a component instance in the core library.

interface Node<TProps = Record<string, any>> {
  /** Stable, unique ID in the hierarchy (e.g., 'item-card-[/users/0]'). */
  readonly instanceId: string;
  /** The original component ID from the JSON payload (e.g., 'item-card'). */
  readonly componentId: string;
  /** The component type string (e.g., 'Text', 'Button'). */
  readonly type: string;
  /** The scoped data path (e.g., '/users/0'). */
  readonly dataPath: string;
  /** Fully resolved, strongly-typed properties as a reactive signal. */
  readonly props: Signal<TProps>;
  /** Event fired when the node is removed from the view hierarchy. */
  readonly onDestroyed: EventSource<void>;
  /** Cleanup logic for binders and child nodes. */
  dispose(): void;
}

1.2 SurfaceModel Integration

The management of the Node tree should be an implementation detail inside SurfaceModel.

  • Expose: rootNode: Signal<Node | undefined> on SurfaceModel.
  • Internal Node Engine:
    • Watch SurfaceComponentsModel for the component with ID root.
    • Use the GenericBinder logic internally to resolve properties for nodes.
    • 1-to-N Mapping: Handle templated ChildLists. If a container points to a data model array (e.g., path: '/users'), the engine must subscribe to that path in the DataModel and spawn a unique Node for each item.
    • Stability: Ensure instanceId incorporates the data path for templated items so that framework "keys" remain stable.
    • Reconciliation: Update existing nodes' properties when the model changes. If a component's type changes, destroy the old node and create a new one.

2. Framework Integration & Soft Transition

We must ensure existing component implementations continue to work without a full rewrite.

2.1 Compatibility Shims

  • buildChild Overload: Update the buildChild helper in all framework wrappers to accept string | Node. If it receives a Node, it renders it directly. This allows existing code like ${buildChild(props.child)} to stay exactly the same.
  • Node.toString(): Implement Node.prototype.toString() to return its componentId. This prevents breakage for logic using ID comparisons (e.g., if (props.child === 'submit-btn')).

2.2 Framework-Specific Tasks

React Renderer (@renderers/react/src/v0_9/)

  • Adapter: Update A2uiSurface.tsx to subscribe to surface.rootNode. createComponentImplementation should provide a Node object to the component instead of raw IDs.
  • Hook: Create useNodeProps(node) using useSyncExternalStore to subscribe to the node's props signal.
  • Rendering: Update standard components (e.g., ChildList.tsx) to map over Node arrays, passing them directly to buildChild.

Angular Renderer (@renderers/angular/)

  • Signals: Wrap the Preact node.props signal into an Angular Signal using @angular/core. Subscribe the base A2UI Surface component to SurfaceModel.rootNode.
  • Directive: Update the internal outlet directive (e.g., *a2uiOutlet) to accept a Node input. It should gracefully transition from ID-based lookup to direct Node rendering.

Lit Renderer (@renderers/lit/)

  • Controller: Implement a NodeController that subscribes to the node's reactive state and calls host.requestUpdate().
  • Base class: Overload the base class's buildChild method to handle the new Node type.

3. Edge Cases & Testing

  • Memory Safety: Verify that deleting a surface or removing an item from a templated list calls dispose() on all affected nodes and clears all DataModel subscriptions.
  • Type Safety: Properties resolution must remain type-safe. Ensure props.child in a component implementation is typed as Node.
  • Progressive Rendering: Handle cases where a container refers to a component ID that hasn't arrived in the message stream yet (render as a placeholder until the ID is defined).

Context

  • @renderers/web_core/src/v0_9/
  • @renderers/react/src/v0_9/
  • @renderers/angular/
  • @renderers/lit/
  • @specification/v0_9/json/server_to_client.json
  • @specification/v0_9/json/common_types.json
  • @specification/v0_9/json/basic_catalog.json

jacobsimionato avatar Apr 27 '26 07:04 jacobsimionato

@ditman @josemontesp WDYT?

jacobsimionato avatar Apr 27 '26 07:04 jacobsimionato

Renderers will simply receive fully-resolved, type-safe Node instances and focus solely on mapping them to native UI primitives (pixels).

I like this!


interface Node<TProps = Record<string, any>> {

Should TProps be a more specific type, maybe inferred from the Zod definition of the catalog items?


props: A reactive Signal. Dynamic values are primitive strings/numbers/booleans, Actions are callable () => void closures, and Structural props (e.g., child or children) contain actual child Node references (not string IDs).

We got some feedback about props being a single signal maybe being a performance issue, and we should prefer each separate prop to be its own independent signal. Should we model that here?


Structural props (e.g., child or children) contain actual child Node references (not string IDs).

Hmmm, I guess this is fine for the view of the node tree that the renderers use, so rendering there is just a tree traversal, but there's some advantages to the current implementation based off of ids and an adjacency list (for example, almost free path resolutions), no?

I guess the implementation details of the actual tree data structure are TBD, but I'm not sure I'd like to go full blown tree traversal for everything.


Also, can we decouple this work from the v0.10 of the protocol? From my experience in v0.9, updating the protocol seems like quite a fast affair, but then updating the renderers is a whole can of worms.

ditman avatar Apr 28 '26 01:04 ditman

Thanks for taking a look!

Should TProps be a more specific type, maybe inferred from the Zod definition of the catalog items?

Yeah, let's type it as well as we can. This is templated right? So I assume we can instantiate Node instances with more specific props types?

We got some feedback about props being a single signal maybe being a performance issue, and we should prefer each separate prop to be its own independent signal. Should we model that here?

I hear this, but did the developer have measurable issues with performance, or they were they just concerned? Even if we expose a single Signal with all the props, in the uncommon case that someone has a very complex component that they want to update incrementally, l assume frameworks have some way that you could diff the previous props from the current props, allowing for a partial rendering update?

Also, can we decouple this work from the v0.10 of the protocol? From my experience in v0.9, updating the protocol seems like quite a fast affair, but then updating the renderers is a whole can of worms.

Yes! Definitely! That milestone setting was a mistake. We can do this anytime, an incremental improvement.

jacobsimionato avatar Apr 28 '26 01:04 jacobsimionato

See prototype implementation here: https://github.com/google/A2UI/pull/1294

jacobsimionato avatar Apr 28 '26 02:04 jacobsimionato

I like this! web_core would be exposing the component structure together with the data structure in one simple root node. It would make it easier to implement the renderers and keep their implementations more in sync.

One nit detail is the naming. Node is a bit overloaded, specially in web with Nodejs. We will probably have a Nodejs agent layer implementation at some point. Since this name will be part of the public API of web_core I think we should come up with some alternatives.

josemontespg avatar Apr 28 '26 17:04 josemontespg

SGTM - thanks for looking. I'm not attached to node - happy to choose a different name!

jacobsimionato avatar Apr 29 '26 00:04 jacobsimionato

Also, as part of this work, we should update the renderer guide markdown to explain the node layer, so that it can be implemented in other platforms in the future. Ideally, we might replace the existing generic binder with the node layer and some well-architected internal logic that analyses the schema and updates the node layer. If we can decompose the logic into well-defined components, it will be easier to replicate across languages, with an exhaustive test suite.

Places where node layer would also need to be implemented:

  • Dart a2ui_core which already exists but hasn't been released yet - https://github.com/flutter/genui/tree/main/packages/a2ui_core
  • Kotlin a2ui_core which is currently being implemented
  • All future ports of a2ui_core, e.g. C++, Python etc

Another random thought: The node layer may be awesome for debugging on both client and server side. E.g. you can dump out a hierarchical view of what should be displayed on screen, rather than the flat lists which are difficult to understand as a human.

jacobsimionato avatar Apr 29 '26 23:04 jacobsimionato

@nan-yu FYI this is an upcoming improvement that we may add to the core library design which could help with debugging and validation.

I imagine we could build validation utilities on top of this API, e.g. the node tree generation logic could output errors as it runs (e.g. unresolved data model reference), and/or we could walk the tree after it has been generated and check for unresolved children or references.

jacobsimionato avatar Apr 29 '26 23:04 jacobsimionato

I think the design LGTM as-is. However, I don't believe this can actually be done in a non-breaking away.

  • buildChild Overload: Update the buildChild helper in all framework wrappers to accept string | Node. If it receives a Node, it renders it directly. This allows existing code like ${buildChild(props.child)} to stay exactly the same.

This only works for languages that support either proper union types or proper function signature overloading. I suspect that most languages that employ nominal typing and don't support overloading (like Dart) will have to make a breaking change. In these languages we could provide separate named function for the new architecture (and optionally deprecate the existing one), though this obviously incurs API bloat.

  • Node.toString(): Implement Node.prototype.toString() to return its componentId. This prevents breakage for logic using ID comparisons (e.g., if (props.child === 'submit-btn')).

toString() doesn't help ===, because === doesn't coerce (== does). What actually happens in that code example depends on the type of props.child:

  • If props.child is typed Node, === 'submit-btn' won't compile.
  • If we keep it string | Node for compatibility, it compiles and silently evaluates as false at runtime.

Either way the shim doesn't keep === comparisons working.

I'm personally fine with making breaking changes here. I believe extracting as much client-side logic into a2ui_core (and the equivalents for other languages) is necessary for keeping maintenance of so many renderers cognitively tractable. However, I am biased: I've only worked in maintaining these libraries, sheltered from the actual fallout of breaking changes/downstream migrations.

andrewkolos avatar Jun 02 '26 13:06 andrewkolos

A2UI Triage: Decoupled from v1.0 milestone. Marking as P2.

gspencergoog avatar Jun 29 '26 20:06 gspencergoog