Skip to content

feat(craft): render templates as A2UI catalog components - #31

Open
innkuika wants to merge 2 commits into
craft/engine-flutterfrom
craft/engine-a2ui
Open

innkuika wants to merge 2 commits into
craft/engine-flutterfrom
craft/engine-a2ui

Conversation

@innkuika

@innkuika innkuika commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Makes Craft templates ordinary catalog components of an A2UI renderer, so an agent uses them with regular A2UI messages. Stacked on #30. Same three parts as the other engine PRs: a blueprint, conformance cases and the code.

  • Blueprint: craft/blueprints/features/craft_a2ui_integration.blueprint.md.
  • Catalog schemas (a2ui_craft, pure Dart): each component the registry offers gets an A2UI v1.0 JSON schema, derived from how its declaration uses args:
    • a property becomes a DynamicString, DynamicNumber, DynamicBoolean or DynamicValue, or a Child, ChildList or Action;
    • argument kinds flow through calls to other templates, and primitives can state the kind of each argument in their metadata;
    • binder-supplied setters (setFoo for a two-way foo) are left out.
  • Props and events (a2ui_craft):
    • resolved A2UI props become template arguments; a path-bound value also gets a setX setter that writes to the data model;
    • actions become handlers, and children become host widgets;
    • template events become A2UI actions.
  • The runtime gains host widgets, so a child component from A2UI can be placed inside a template. This updates the runtime blueprint and adds cases.
  • Flutter: the new package craft/packages/a2ui_craft_renderer_flutter. templateCatalog(...) builds a catalog for a2ui_flutter using only its public API, with no changes to a2ui_flutter or a2ui_core (published ^0.4.0 / ^0.8.0). Local state survives prop updates.
  • Tests:
    • 34 conformance cases in craft/conformance/craft/craft_a2ui_integration.yaml;
    • unit tests;
    • 8 widget tests on a real A2UI surface (createSurface, updateComponents, updateDataModel). They cover a two-way write seen by a basic-catalog component on the same surface, actions, @checks, validation of undeclared props and unavailable components.
  • Not in this PR: calling other catalogs' components from inside a template (an agent can still pass them in as children), v0.9 catalogs, and mapping the surface theme.

An independent review checked the blueprint against the tests, the code and the A2UI specification, including mutations.

Pre-launch Checklist

One time:

For this PR:

  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • License checks pass (python3 ./scripts/fix_licenses.py --check).
  • Format checks pass (./scripts/fix_format.sh --check).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements the A2UI integration feature for the Craft engine, enabling Craft templates to serve as catalog components for an A2UI renderer. It introduces the a2ui_integration feature blueprint, updates the runtime and Flutter view to support host widgets, and adds the a2ui_craft_renderer_flutter package to build the template catalog. Feedback on the implementation highlights a type-matching bug in a2uiJson due to Dart's reified generics, and suggests a performance optimization in _TemplateComponentState.didUpdateWidget to use DeepCollectionEquality instead of jsonEncode for comparing arguments.

Comment on lines +256 to +264
Object? a2uiJson(Object value) => switch (value) {
Missing() => null,
List<Object>() => <Object?>[for (final Object e in value) a2uiJson(e)],
Map<String, Object>() => <String, Object?>{
for (final MapEntry<String, Object> e in value.entries)
if (e.value is! Missing) e.key: a2uiJson(e.value),
},
_ => value,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In Dart, generic collections are reified, meaning List<dynamic> is not a subtype of List<Object>, and Map<String, dynamic> is not a subtype of Map<String, Object>. Since incoming dynamic values or external data collections are frequently typed as List<dynamic> or Map<String, dynamic>, matching against List<Object>() and Map<String, Object>() will fail and fall through to the default case _ => value. This prevents nested collections from being recursively processed and converting Missing values to null.

Using List<Object?>() and Map<String, Object?>() instead ensures that any list or map type is correctly matched and recursively processed.

Suggested change
Object? a2uiJson(Object value) => switch (value) {
Missing() => null,
List<Object>() => <Object?>[for (final Object e in value) a2uiJson(e)],
Map<String, Object>() => <String, Object?>{
for (final MapEntry<String, Object> e in value.entries)
if (e.value is! Missing) e.key: a2uiJson(e.value),
},
_ => value,
};
Object? a2uiJson(Object value) => switch (value) {
Missing() => null,
List<Object?>() => <Object?>[
for (final Object? e in value) e != null ? a2uiJson(e) : null,
],
Map<String, Object?>() => <String, Object?>{
for (final MapEntry<String, Object?> e in value.entries)
if (e.value is! Missing) e.key: e.value != null ? a2uiJson(e.value!) : null,
},
_ => value,
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a2uiJson only takes runtime values, whose collections have these exact types. Raw JSON can't contain Missing, so returning it unchanged is already correct JSON.

Comment on lines +159 to +168
void didUpdateWidget(_TemplateComponent oldWidget) {
super.didUpdateWidget(oldWidget);
final TemplateArgs next = widget.template.args(widget.props);
final bool changed = _key(next) != _key(_args);
_args = next;
if (changed) _runtime.args = next.args;
}

static String _key(TemplateArgs args) =>
jsonEncode(canonicalExpansionValue(args.args));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Performing jsonEncode(canonicalExpansionValue(args.args)) on every didUpdateWidget call to check for changes can be a significant performance bottleneck, especially during high-frequency updates (e.g., animations or slider drags). It recursively traverses the entire arguments structure, allocates new maps/lists, and serializes them to a JSON string on every frame.

Since TemplateArgs contains only primitive values, HostWidgets, and HostHandlers (all of which implement proper == operators), we can use DeepCollectionEquality from package:collection/collection.dart to perform a highly optimized deep comparison of the arguments map directly, completely avoiding string serialization and garbage collection overhead.

Note: Remember to add import 'package:collection/collection.dart'; at the top of the file.

  @override
  void didUpdateWidget(_TemplateComponent oldWidget) {
    super.didUpdateWidget(oldWidget);
    final TemplateArgs next = widget.template.args(widget.props);
    final bool changed = !const DeepCollectionEquality().equals(_args.args, next.args);
    _args = next;
    if (changed) _runtime.args = next.args;
  }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the canonical key on purpose: DeepCollectionEquality treats 1 and 1.0 as equal, but Craft distinguishes them (e.g. concat shows 1 vs 1.0), so that change would be missed. This only runs on widget updates of one component's props.

@ditman ditman left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Great end-to-end A2UI v1.0 integration — deriving catalog schemas from primitive metadata + template call graphs without modifying a2ui_core or a2ui_flutter, with 34 conformance cases and strict-validation widget tests, is very clean.

Blocking (prompting Request Changes):

  1. Stale CraftRuntime when a component ID switches template type (template_catalog.dart): Every template component renders the same _TemplateComponent widget class with key: null and keeps late final CraftRuntime _runtime created only in initState(). If updateComponents replaces a component's component type on the same id (e.g. Counter → Card), or the catalog/registry changes, Flutter reuses _TemplateComponentState and keeps rendering the old template with the new template's args. Keying _TemplateComponent by (registry, library, name) (or recreating _runtime in didUpdateWidget) fixes this.
  2. setterName('') throws RangeError on empty argument names (a2ui_catalog.dart): Calling arg.substring(0, 1) without guarding arg.isEmpty crashes schema derivation if a binary-encoded template contains an empty-string ArgsReference part.

Non-blocking reminders / nits:

  1. Post-stack barrel tightening reminder (a2ui_craft_renderer_flutter.dart and a2ui_craft.dart): Per our agreement on #23, please include a2ui_craft_renderer_flutter.dart and the new src/a2ui_catalog.dart / src/a2ui_props.dart exports on a2ui_craft.dart when switching barrels to explicit show lists (right now they expose internal/conformance helpers like a2uiJson, JsonMap, checkResultArgs, reservedArgs, setterName).
  2. Minor doc nits: a2ui_catalog.dart and a2ui_props.dart reference requirement 1 / requirement 2 instead of requirement 2 / requirement 5.

(Noted that media: and errorBuilder: options on templateCatalog, live registry refresh, and the model.dart barrel split are already queued in #39, so I left those out of this review.)

Comment on lines +143 to +166
class _TemplateComponentState extends State<_TemplateComponent> {
late TemplateArgs _args;
late final CraftRuntime _runtime;

@override
void initState() {
super.initState();
_args = widget.template.args(widget.props);
_runtime = CraftRuntime(
widget.template.registry,
library: widget.template.library,
widget: widget.template.name,
args: _args.args,
);
}

@override
void didUpdateWidget(_TemplateComponent oldWidget) {
super.didUpdateWidget(oldWidget);
final TemplateArgs next = widget.template.args(widget.props);
final bool changed = _key(next) != _key(_args);
_args = next;
if (changed) _runtime.args = next.args;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Every component in templateCatalog(...) builds the same _TemplateComponent widget class with key: null, and _runtime is late final created once in initState().

If an agent sends updateComponents changing an existing component's component type on the same id (e.g. {"id": "root", "component": "Counter"} → {"id": "root", "component": "Card"}), or if the host swaps in a new templateCatalog with a different registry/library, Flutter sees oldWidget.runtimeType == newWidget.runtimeType and key == null, reuses _TemplateComponentState, and keeps rendering the old template (Counter) with the new template's (Card's) args.

Passing a key on _TemplateComponent at lines 63-75 (e.g. key: ValueKey<(TemplateRegistry, LibraryName, String)>((registry, library, c.key)))—or recreating _runtime in didUpdateWidget when registry, library, or name changes—ensures the state and runtime reset cleanly.

Drop-in regression test for craft/packages/a2ui_craft_renderer_flutter/test/template_catalog_test.dart:

  testWidgets('replacing a component with another template renders the new one', (
    WidgetTester tester,
  ) async {
    final _Harness h = _Harness();
    await h.pump(tester, <Map<String, Object?>>[
      <String, Object?>{'id': 'root', 'component': 'Counter', 'title': 'Clicks'},
    ]);
    expect(find.text('Clicks: 0'), findsOneWidget);
    expect(find.text('more'), findsOneWidget);

    h.send('updateComponents', <String, Object?>{
      'components': <Object?>[
        <String, Object?>{'id': 'root', 'component': 'Card', 'title': 'Details'},
      ],
    });
    await tester.pump();
    await tester.pump();

    expect(find.text('Details'), findsOneWidget);
    expect(find.text('save'), findsOneWidget);
    expect(find.text('Details: 0'), findsNothing);
    expect(find.text('more'), findsNothing);
  });

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4529842: each template component is keyed by (registry, library, template name), with your Counter→Card test. For the record, your reproducer also passes without the key because a2ui_flutter 0.4 already keys each node's subtree by its implementation; the key makes us independent of that.

/// (`a2ui_flutter`): see `templateCatalog`.
library;

export 'src/template_catalog.dart';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder for the post-stack barrel-tightening pass agreed in #23: please include lib/a2ui_craft_renderer_flutter.dart when switching public barrels to explicit show lists:

export 'src/template_catalog.dart' show TemplateErrorCallback, templateCatalog;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do in the barrel-tightening PR on top of the stack (explicit show lists for all barrels, internal helpers off the public API).

Comment on lines +20 to +21
export 'src/a2ui_catalog.dart';
export 'src/a2ui_props.dart';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder for the post-stack barrel-tightening pass agreed in #23: please include src/a2ui_catalog.dart and src/a2ui_props.dart when switching lib/a2ui_craft.dart to explicit show lists (even in #39 these two remain wildcards). Right now they export internal/conformance helpers like a2uiJson, JsonMap, checkResultArgs, reservedArgs, and setterName directly on the top-level a2ui_craft barrel.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do in the barrel-tightening PR on top of the stack (explicit show lists for all barrels, internal helpers off the public API).

Comment on lines +75 to +76
String setterName(String arg) =>
'set${arg.substring(0, 1).toUpperCase()}${arg.substring(1)}';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 arg.substring(0, 1) throws a RangeError if arg is empty (''). While the text format cannot parse an empty identifier after args., binary-encoded templates (or constructed ArgsReference(<Object>['']) ASTs) can contain an empty string part, which would crash templateInterfaces / templateCatalogSchemas whenever the template also has an action arg. Guarding if (arg.isEmpty) return 'set'; (or ignoring empty argument names in _Walk._record) keeps schema derivation safe for untrusted binary inputs.

Drop-in regression test for craft/packages/a2ui_craft/test/a2ui_integration_test.dart:

class _Primitives extends PrimitiveLibrary {
  const _Primitives(this.widgetMeta);

  @override
  Iterable<String> get widgetNames => widgetMeta.keys;

  @override
  final Map<String, Map<String, Object?>> widgetMeta;
}
  test('empty-string argument reference does not throw RangeError', () {
    const LibraryName main = LibraryName(<String>['main']);
    final TemplateRegistry registry = TemplateRegistry()
      ..setPrimitiveLibrary(
        coreLibrary,
        const _Primitives(<String, Map<String, Object?>>{
          'Button': <String, Object?>{
            'args': <String, Object?>{
              'label': 'string',
              'onPressed': 'handler',
            },
          },
        }),
      )
      ..setTemplateLibrary(
        main,
        const RemoteWidgetLibrary(
          <Import>[Import(coreLibrary)],
          <WidgetDeclaration>[
            WidgetDeclaration(
              'Bad',
              null,
              ConstructorCall('Button', <String, Object>{
                'label': ArgsReference(<Object>['']),
                'onPressed': ArgsReference(<Object>['onTap']),
              }),
              exported: true,
            ),
          ],
        ),
      );
    expect(() => templateInterfaces(registry, main), returnsNormally);
  });

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4529842: setterName('') returns set instead of throwing; test added.

Comment on lines +21 to +24
/// A resolved property of an A2UI component node, as an A2UI renderer hands it
/// to a component implementation (see the `craft_a2ui_integration` blueprint,
/// requirement 2). [host] is the renderer's own object for it (a binding, an
/// action, a child node), which the integration never looks into.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Nit: craft_a2ui_integration.blueprint.md specifies resolved props to arguments in requirement 5 (requirement 2 is argument kinds). Similarly, ArgKind in a2ui_catalog.dart:22 references requirement 1 instead of requirement 2.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4529842 (requirement 2 for argument kinds, requirement 5 for resolved props).

@ditman ditman left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Thanks for addressing all of the comments — keying _TemplateComponent by (registry, library, name), guarding setterName(''), and updating the blueprint requirement references all look clean and well-tested. LGTM!

Adds the craft_a2ui_integration feature: Craft templates as ordinary
catalog components of an A2UI renderer, used by an agent with regular
A2UI messages.

- craft/blueprints/features/craft_a2ui_integration.blueprint.md: the
  catalog of a template library (its offered components); argument kinds
  derived from the positions of `args` references (primitive metadata
  kinds widget, widgets, handler, string, number, boolean; template
  calls passing kinds on, chain-relative for calls back into a template
  under analysis; lists, loops, switches, handlers, builders); joining
  uses; the A2UI v1.0 component schema (common types, Checkable for
  templates that read check results, two-way setters and reserved names
  left out); resolved props to arguments (values, setX host handlers for
  path-bound values, actions as host handlers, children as host widgets,
  check results); effects of firing (dispatch an action, run an action,
  write a path); rendering.
- craft/conformance/craft/craft_a2ui_integration.yaml: 34 cases (schemas
  as JSON, props in JSON form to canonical arguments, firing to JSON
  effects).
- packages/a2ui_craft: lib/src/a2ui_catalog.dart (TemplateInterface,
  templateCatalogSchemas) and lib/src/a2ui_props.dart (TemplateArgs,
  A2uiEffect), framework-independent; TemplateRegistry.primitiveMeta.
- runtime: host widgets. A host may pass widgets in the root's arguments
  by identifier; the expansion places them as host widget nodes ({$:
  hostWidget, id}) wherever a widget call would go, and they are no
  values. Blueprint, 3 craft_runtime.yaml cases, unit tests; CraftView
  renders them with hostWidgetBuilder.
- packages/a2ui_craft_renderer_flutter (new): templateCatalog, a v1.0
  CatalogImplementation for a2ui_flutter whose components keep one
  CraftRuntime per node and render with CraftView; widget tests drive an
  A2UI surface with createSurface/updateComponents/updateDataModel
  messages under strict validation, with a basic-catalog child, data and
  property updates keeping state, a two-way write, an agent action, a
  template event and check results. It depends on the published
  a2ui_core 0.8.0 and a2ui_flutter 0.4.0 and changes neither.
- Conformance: the derive_catalog_schema and map_props actions,
  expand_template's host widgets, and the F-CRAFT-A2UI-01 to 07 feature
  IDs; requirement 7, rendering, is claimed by the Flutter side
  (dart-craft-flutter) and covered by its widget tests.

Based on the Craft prototype's renderer-hosted branch (template catalog,
templateArgsFromProps, dispatchTemplateEvent) and its catalog skeleton,
rewritten against the new runtime with the slot-name heuristics replaced by
primitive metadata. Calling other catalogs' components from inside a
template, v0.9 catalogs, schema defaults and theme mapping are left out.
- A template component's widget is keyed by its registry, library and
  template name, so a node whose component becomes another template, or
  whose catalog has another registry or library, gets a new runtime
  instead of keeping the old template's. (a2ui_flutter 0.4 already keys
  each node's subtree by its implementation; the key keeps this from
  depending on that.) A widget test switches a node from Counter to
  Card.
- setterName('') is `set` instead of a RangeError, so deriving the
  interfaces of a decoded template with an argument named '' works.
- Doc comments cite the right requirements of craft_a2ui_integration
  (2 for argument kinds, 5 for resolved props).
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.

2 participants