Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/genui/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# [genui](https://pub.dev/packages/genui) Changelog

## 0.10.5

- **Fix**: Resolve validation checks and preserve error messages across basic catalog components.
- Recursively evaluate `List` arguments in `DataContext._evaluateStream` so logical functions (`and`, `or`) receive resolved values.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Describe behavior, not internals

The entry names DataContext._evaluateStream, a private method, and describes the implementation. Suggested wording, aimed at people using the package:

## 0.10.5

- **Fix**: Validation `checks` on `CheckBox`, `Slider` and `ChoicePicker` now fail when their condition is false, and show the check's `message` instead of a generic "Invalid value".
- **Fix**: `and`/`or` now evaluate bindings and function calls inside `values`, so a failing nested check fails the rule.
- **Behavior change**: Conditions use truthiness instead of a null check. `0`, `''`, `[]`, `{}` and unknown functions evaluate to `false`, and malformed condition expressions log a warning.

- Remove invalid `'functionCall'` envelope from `checksToExpression` and support tolerant unwrapping in `_evaluateStream`.
- Align truthiness evaluation in `isTruthy` across primitives, data model objects, and structured `ValidationResult` objects, while warning on malformed expressions or missing functions.
- Migrate `CheckBox`, `Slider`, and `ChoicePicker` to `ValidationHelper.validateStream` to evaluate rules individually and display authored error messages.

## 0.10.4

- **Fix**: `Image` now takes the catalog's `description` property and announces it. The property is what the basic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import 'package:json_schema_builder/json_schema_builder.dart';
import '../../model/a2ui_schemas.dart';
import '../../model/catalog_item.dart';
import '../../model/data_model.dart';
import '../../model/validation_helper.dart';
import '../../primitives/simple_items.dart';
import '../../widgets/widget_utilities.dart';
import 'widget_helpers.dart';

final _schema = S.object(
description: 'A selectable checkbox used for boolean toggles with a label.',
Expand Down Expand Up @@ -61,14 +61,14 @@ final checkBox = CatalogItem(
value: checkBoxData.label,
builder: (context, label) {
// Wrap the checkbox in validation
return StreamBuilder<bool>(
stream: itemContext.dataContext.evaluateConditionStream(
checksToExpression(checkBoxData.checks),
return StreamBuilder<String?>(
stream: ValidationHelper.validateStream(
checkBoxData.checks,
itemContext.dataContext,
),
initialData: true,
builder: (context, snapshot) {
final bool isValid = snapshot.data ?? true;
final bool isError = !isValid;
final String? errorMessage = snapshot.data;
final isError = errorMessage != null;

return ListTileTheme.merge(
child: BoundBool(
Expand All @@ -92,9 +92,9 @@ final checkBox = CatalogItem(
);
}
},
subtitle: isError
subtitle: errorMessage != null

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit

CheckBox now uses both isError and errorMessage != null, while Slider and ChoicePicker rely on promotion through isError. It works either way, but I'd use the same pattern in all three.

? Text(
'Invalid value',
errorMessage,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontSize: 12,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import 'package:json_schema_builder/json_schema_builder.dart';
import '../../model/a2ui_schemas.dart';
import '../../model/catalog_item.dart';
import '../../model/data_model.dart';
import '../../model/validation_helper.dart';
import '../../primitives/simple_items.dart';
import '../../widgets/widget_utilities.dart';
import 'widget_helpers.dart';

final _schema = S.object(
description:
Expand Down Expand Up @@ -85,14 +85,14 @@ final choicePicker = CatalogItem(
final isChips = data.displayStyle == 'chips';

// Wrap the picker in validation
return StreamBuilder<bool>(
stream: itemContext.dataContext.evaluateConditionStream(
checksToExpression(data.checks),
return StreamBuilder<String?>(
stream: ValidationHelper.validateStream(
data.checks,
itemContext.dataContext,
),
initialData: true,
builder: (context, snapshot) {
final bool isValid = snapshot.data ?? true;
final bool isError = !isValid;
final String? errorMessage = snapshot.data;
final isError = errorMessage != null;

return BoundList(
dataContext: itemContext.dataContext,
Expand Down Expand Up @@ -121,7 +121,7 @@ final choicePicker = CatalogItem(
Padding(
padding: const EdgeInsets.only(left: 16.0, top: 4.0),
child: Text(
'Invalid selection',
errorMessage,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontSize: 12,
Expand Down
16 changes: 8 additions & 8 deletions packages/genui/lib/src/catalog/basic_catalog_widgets/slider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import 'package:json_schema_builder/json_schema_builder.dart';
import '../../model/a2ui_schemas.dart';
import '../../model/catalog_item.dart';
import '../../model/data_model.dart';
import '../../model/validation_helper.dart';
import '../../primitives/simple_items.dart';
import '../../widgets/widget_utilities.dart';
import 'widget_helpers.dart';

final _schema = S.object(
description: 'A slider for selecting a value from a range.',
Expand Down Expand Up @@ -116,14 +116,14 @@ final slider = CatalogItem(
dataContext: itemContext.dataContext,
value: sliderData.label,
builder: (context, label) {
return StreamBuilder<bool>(
stream: itemContext.dataContext.evaluateConditionStream(
checksToExpression(sliderData.checks),
return StreamBuilder<String?>(
stream: ValidationHelper.validateStream(
sliderData.checks,
itemContext.dataContext,
),
initialData: true,
builder: (context, snapshot) {
final bool isValid = snapshot.data ?? true;
final bool isError = !isValid;
final String? errorMessage = snapshot.data;
final isError = errorMessage != null;

final List<Widget> children = [
if (label != null)
Expand All @@ -142,7 +142,7 @@ final slider = CatalogItem(
Padding(
padding: const EdgeInsets.only(left: 16.0, top: 4.0),
child: Text(
'Invalid value',
errorMessage,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontSize: 12,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,20 @@ Object? checksToExpression(List<JsonMap>? checks) {
return true;
}

final List<Object?> conditions = checks
.map((c) => c['condition'])
.where((c) => c != null)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

checksToExpression has no callers left

After the migration, the only use of checksToExpression is in data_model_test.dart. Its semantics also differ from validateStream now. It drops checks with no condition, which then pass, while validateStream evaluates null as false and shows the message. I'd delete the function and its test section instead of keeping two paths that disagree.

.toList();
if (conditions.isEmpty) {
return true;
}
if (conditions.length == 1) {
return conditions.first;
}

// Combine all checks into a single 'and' condition
return {
'functionCall': {
'call': 'and',
'args': {'values': checks.map((c) => c['condition']).toList()},
},
'call': 'and',
'args': {'values': conditions},
};
}
14 changes: 4 additions & 10 deletions packages/genui/lib/src/catalog/basic_functions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'package:url_launcher/url_launcher.dart';
import '../functions/format_string.dart';
import '../model/a2ui_schemas.dart';
import '../model/client_function.dart';
import '../model/data_model.dart';
import '../primitives/simple_items.dart';

// ignore: avoid_classes_with_only_static_members
Expand Down Expand Up @@ -48,13 +49,6 @@ class BasicFunctions {
];
}

/// Helper to check for truthiness.
bool _isTruthy(Object? value) {
if (value is bool) return value;
if (value == null) return false;
return true;
}

/// Checks if all values in a list are truthy.
class AndFunction extends SynchronousClientFunction {
const AndFunction();
Expand All @@ -78,7 +72,7 @@ class AndFunction extends SynchronousClientFunction {
final Object? values = args['values'];
if (values is! List) return false;
for (final Object? element in values) {
if (!_isTruthy(element)) return false;
if (!isTruthy(element)) return false;
}
return true;
}
Expand Down Expand Up @@ -108,7 +102,7 @@ class OrFunction extends SynchronousClientFunction {
final Object? values = args['values'];
if (values is! List) return false;
for (final Object? element in values) {
if (_isTruthy(element)) return true;
if (isTruthy(element)) return true;
}
return false;
}
Expand All @@ -134,7 +128,7 @@ class NotFunction extends SynchronousClientFunction {
@override
Object? executeSync(JsonMap args, ExecutionContext _) {
if (!args.containsKey('value')) return false;
return !_isTruthy(args['value']);
return !isTruthy(args['value']);
}
}

Expand Down
42 changes: 38 additions & 4 deletions packages/genui/lib/src/model/data_model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ class DataContext implements cf.ExecutionContext {
if (value.containsKey('call')) {
return _evaluateFunctionCall(value as JsonMap);
}
if (value.containsKey('functionCall') && value['functionCall'] is Map) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should functionCall unwrapping be limited to conditions?

checksToExpression no longer produces the envelope, so this only matters for agent-authored conditions. But _evaluateStream also backs resolve(), which runs for event contexts (resolveContext), BoundValue and Button's function-call path. With this change, any {'functionCall': {...}} map that reaches resolve() gets executed, not just ones in a condition. Since the spec only puts functionCall in Action, I'd do the unwrapping in evaluateConditionStream and leave resolve() strict.

return _evaluateStream(value['functionCall']);
}
}
if (value is List) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

List recursion applies to every resolve(), not just function args

This fixes and/or, but it also changes how any literal list passed to resolve() behaves. A list element that is a map with a path or call key is now treated as a binding. For example, an event context value [{'path': '/n', 'label': 'file'}] resolves to [0], the data model value at /n. Maps aren't recursed into, though, so [{'label': {'path': '/x'}}] stays literal. The rules end up depending on nesting depth.

This may be what we want for lists of dynamic values, but it's a behavior change beyond validation. Could you either limit the recursion to function args or note it in the CHANGELOG, and add a resolveContext test with a list?

if (value.isEmpty) return Stream.value(<Object?>[]);
final List<Stream<Object?>> itemStreams = value
.map(_evaluateStream)
.toList();
return itemStreams.combineLatestAll();
}
if (value is Stream) return value.cast<Object?>();
return Stream.value(value);
Expand All @@ -123,6 +133,9 @@ class DataContext implements cf.ExecutionContext {
Stream<Object?> _evaluateFunctionCall(JsonMap callDefinition) {
final name = callDefinition['call'] as String?;
if (name == null) {
genUiLogger.warning(
'Function call missing "call" property: $callDefinition',
);
return Stream.value(null);
}

Expand Down Expand Up @@ -167,12 +180,33 @@ class DataContext implements cf.ExecutionContext {
if (condition == null) return Stream.value(false);
if (condition is bool) return Stream.value(condition);

if (condition is Map &&
!condition.containsKey('path') &&
!condition.containsKey('call') &&
!condition.containsKey('functionCall')) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

functionCall with a non-map value passes

The guard accepts any map that has a functionCall key, but _evaluateStream only unwraps it when the value is a Map. {'functionCall': 'required'} therefore gets through the guard, falls through as a literal, and isTruthy sees a non-empty map. The result is true, and nothing is logged.

Suggest checking condition['functionCall'] is Map in the guard, so this case logs and returns false like other invalid shapes.

genUiLogger.warning('Invalid condition expression: $condition');
return Stream.value(false);
}

final Stream<Object?> resultStream = _evaluateStream(condition);
return resultStream.map((v) {
if (v is bool) return v;
return v != null;
});
return resultStream.map(isTruthy);
}
}

/// Helper to determine truthiness according to A2UI expression semantics.
bool isTruthy(Object? value) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

isTruthy becomes public API

src/model.dart exports data_model.dart, so this top-level isTruthy is now part of package:genui/genui.dart. A name this generic in the public namespace is easy to collide with, and the CHANGELOG doesn't mention it. Could it go in an unexported file (or be marked @internal) and be imported from basic_functions.dart directly?

if (value is bool) return value;
if (value == null) return false;
if (value is String) return value.isNotEmpty;
if (value is num) return value != 0 && !value.isNaN;
if (value is List) return value.isNotEmpty;
if (value is Map) {
if (value.containsKey('valid') && value['valid'] is bool) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Where do {valid: bool} maps come from?

As far as I can tell, no function in genui returns a map with a valid key. The only ValidationResult in the repo is the class in json_schema_builder, and it isn't a map. Meanwhile the branch changes what user data means. With {path: /coupon} and /coupon = {code: 'X', valid: false}, the result is false, while any other non-empty object is true. I'd drop this branch until something actually produces that shape, or link to where it's produced.

return value['valid'] as bool;
}
return value.isNotEmpty;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nested malformed expressions pass again

Now that a non-empty map is truthy, a typo inside and/or makes the check pass:

condition result
{call: and, args: {values: [{cal: required, ...}]}} true
{call: not, args: {value: {cal: required, ...}}} false
{call: and, args: {values: [{call: nope}]}} false (unknown function → null)

The Invalid condition expression guard in evaluateConditionStream only looks at the outermost condition. Once a nested map reaches and, it has been resolved as a literal, and isTruthy can't tell it apart from a data object. The PR description (point 3) still says unresolvable expression maps count as false, which stopped being true with this commit.

A literal map isn't a valid DynamicBoolean, so one option is to run the elements of and/or values and not's value through the same shape check before resolving them. Whatever the fix, could you add a test for the nested case?

}
return false;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Unknown non-null types are now falsy

Before this PR, any non-null value was truthy. Now anything that isn't bool/String/num/List/Map returns false. DataModel.update accepts any Dart object, so a DateTime (or any custom object) at a path makes {path: /d} evaluate to false. JS-style truthiness treats objects as truthy. Should this be return true?

On the broader change: 0, '' and [] at a path used to pass as non-null and now fail. That seems right to me, but it's a user-visible behavior change for existing surfaces. The doc comment says "according to A2UI expression semantics". Is there a spec section we can link to?

}

/// Resolves a context map definition against a [DataContext].
Expand Down
2 changes: 1 addition & 1 deletion packages/genui/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

name: genui
description: Generates and displays generative user interfaces (GenUI) in Flutter using AI.
version: 0.10.4
version: 0.10.5
homepage: https://github.com/flutter/genui/tree/main/packages/genui
license: BSD-3-Clause
issue_tracker: https://github.com/flutter/genui/issues
Expand Down
65 changes: 65 additions & 0 deletions packages/genui/test/catalog/core_widgets/check_box_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,69 @@ void main() {
isTrue,
);
});

testWidgets('CheckBox validation checks show error message when failing', (
WidgetTester tester,
) async {
final surfaceController = SurfaceController(
catalogs: [BasicCatalogItems.asCatalog()],
);
addTearDown(surfaceController.dispose);
const surfaceId = 'validationTest';
surfaceController.handleMessage(
updateDataModel(
surfaceId: surfaceId,
path: DataPath('/accepted'),
value: false,
),
);

final List<JsonMap> components = [
component(
id: 'root',
type: 'CheckBox',
properties: {
'label': 'I agree',
'value': {'path': '/accepted'},
'checks': [
{
'message': 'You must accept the terms',
'condition': {'path': '/accepted'},
},
],
},
),
];

surfaceController.handleMessage(
updateComponents(surfaceId: surfaceId, components: components),
);
surfaceController.handleMessage(
createSurface(surfaceId: surfaceId, catalogId: basicCatalogId),
);

await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Surface(
surfaceContext: surfaceController.contextFor(surfaceId),
),
),
),
);
await tester.pumpAndSettle();

expect(find.text('You must accept the terms'), findsOneWidget);

surfaceController.handleMessage(
updateDataModel(
surfaceId: surfaceId,
path: DataPath('/accepted'),
value: true,
),
);
await tester.pumpAndSettle();

expect(find.text('You must accept the terms'), findsNothing);
});
}
Loading
Loading