Repository navigation
Conversation
There was a problem hiding this comment.
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.
| 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, | ||
| }; |
There was a problem hiding this comment.
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.
| 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, | |
| }; |
There was a problem hiding this comment.
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.
| 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)); |
There was a problem hiding this comment.
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;
}There was a problem hiding this comment.
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.
42dee4e to
b827c06
Compare
b827c06 to
a2b6bdd
Compare
a2b6bdd to
78cd9bb
Compare
78cd9bb to
47e5a79
Compare
47e5a79 to
ae0d05d
Compare
ae0d05d to
e6bac60
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 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):
- Stale
CraftRuntimewhen a component ID switches template type (template_catalog.dart): Every template component renders the same_TemplateComponentwidget class withkey: nulland keepslate final CraftRuntime _runtimecreated only ininitState(). IfupdateComponentsreplaces a component'scomponenttype on the sameid(e.g.Counter→Card), or the catalog/registry changes, Flutter reuses_TemplateComponentStateand keeps rendering the old template with the new template's args. Keying_TemplateComponentby(registry, library, name)(or recreating_runtimeindidUpdateWidget) fixes this. setterName('')throwsRangeErroron empty argument names (a2ui_catalog.dart): Callingarg.substring(0, 1)without guardingarg.isEmptycrashes schema derivation if a binary-encoded template contains an empty-stringArgsReferencepart.
Non-blocking reminders / nits:
- Post-stack barrel tightening reminder (
a2ui_craft_renderer_flutter.dartanda2ui_craft.dart): Per our agreement on #23, please includea2ui_craft_renderer_flutter.dartand the newsrc/a2ui_catalog.dart/src/a2ui_props.dartexports ona2ui_craft.dartwhen switching barrels to explicitshowlists (right now they expose internal/conformance helpers likea2uiJson,JsonMap,checkResultArgs,reservedArgs,setterName). - Minor doc nits:
a2ui_catalog.dartanda2ui_props.dartreference 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.)
| 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; | ||
| } |
There was a problem hiding this comment.
🤖 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);
});There was a problem hiding this comment.
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'; |
There was a problem hiding this comment.
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;There was a problem hiding this comment.
Will do in the barrel-tightening PR on top of the stack (explicit show lists for all barrels, internal helpers off the public API).
| export 'src/a2ui_catalog.dart'; | ||
| export 'src/a2ui_props.dart'; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Will do in the barrel-tightening PR on top of the stack (explicit show lists for all barrels, internal helpers off the public API).
| String setterName(String arg) => | ||
| 'set${arg.substring(0, 1).toUpperCase()}${arg.substring(1)}'; |
There was a problem hiding this comment.
🤖 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);
});There was a problem hiding this comment.
Fixed in 4529842: setterName('') returns set instead of throwing; test added.
| /// 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. |
There was a problem hiding this comment.
🤖 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.
There was a problem hiding this comment.
Fixed in 4529842 (requirement 2 for argument kinds, requirement 5 for resolved props).
e6bac60 to
4529842
Compare
4529842 to
50b414b
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 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).
50b414b to
8fd2161
Compare
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.
craft/blueprints/features/craft_a2ui_integration.blueprint.md.a2ui_craft, pure Dart): each component the registry offers gets an A2UI v1.0 JSON schema, derived from how its declaration usesargs:DynamicString,DynamicNumber,DynamicBooleanorDynamicValue, or aChild,ChildListorAction;setFoofor a two-wayfoo) are left out.a2ui_craft):setXsetter that writes to the data model;craft/packages/a2ui_craft_renderer_flutter.templateCatalog(...)builds a catalog fora2ui_flutterusing only its public API, with no changes toa2ui_flutterora2ui_core(published^0.4.0/^0.8.0). Local state survives prop updates.craft/conformance/craft/craft_a2ui_integration.yaml;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.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:
python3 ./scripts/fix_licenses.py --check)../scripts/fix_format.sh --check).