diff --git a/packages/genui/CHANGELOG.md b/packages/genui/CHANGELOG.md index a15ea5707..087baa0f9 100644 --- a/packages/genui/CHANGELOG.md +++ b/packages/genui/CHANGELOG.md @@ -1,5 +1,12 @@ # [genui](https://pub.dev/packages/genui) Changelog +## 0.10.7 + +- **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. +- **Behavior change**: `resolve()` and `resolveContext()` recursively resolve dynamic values inside lists. + ## 0.10.6 - Added `AsynchronousClientFunction` base class for single-shot asynchronous diff --git a/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart b/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart index f8809346e..fc012c267 100644 --- a/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart +++ b/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart @@ -92,7 +92,7 @@ final checkBox = CatalogItem( ); } }, - subtitle: errorMessage != null + subtitle: isError ? Text( errorMessage, style: TextStyle( diff --git a/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart b/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart index db6325add..479984415 100644 --- a/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart +++ b/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart @@ -139,28 +139,3 @@ Widget buildWeightedChild({ } return childWidget; } - -/// Converts a list of validation checks into a single expression that evaluates -/// to true if all checks pass. -Object? checksToExpression(List? checks) { - if (checks == null || checks.isEmpty) { - return true; - } - - final List conditions = checks - .map((c) => c['condition']) - .where((c) => c != null) - .toList(); - if (conditions.isEmpty) { - return true; - } - if (conditions.length == 1) { - return conditions.first; - } - - // Combine all checks into a single 'and' condition - return { - 'call': 'and', - 'args': {'values': conditions}, - }; -} diff --git a/packages/genui/lib/src/model.dart b/packages/genui/lib/src/model.dart index 43e4d66dc..39edb23ad 100644 --- a/packages/genui/lib/src/model.dart +++ b/packages/genui/lib/src/model.dart @@ -13,7 +13,7 @@ export 'model/catalog.dart'; export 'model/catalog_item.dart'; export 'model/chat_message.dart'; export 'model/client_function.dart'; -export 'model/data_model.dart'; +export 'model/data_model.dart' hide isTruthy; export 'model/data_path.dart'; export 'model/generation_events.dart'; export 'model/parts.dart'; diff --git a/packages/genui/lib/src/model/data_model.dart b/packages/genui/lib/src/model/data_model.dart index 7034de67f..e95d6c460 100644 --- a/packages/genui/lib/src/model/data_model.dart +++ b/packages/genui/lib/src/model/data_model.dart @@ -115,9 +115,6 @@ class DataContext implements cf.ExecutionContext { if (value.containsKey('call')) { return _evaluateFunctionCall(value as JsonMap); } - if (value.containsKey('functionCall') && value['functionCall'] is Map) { - return _evaluateStream(value['functionCall']); - } } if (value is List) { if (value.isEmpty) return Stream.value([]); @@ -152,7 +149,52 @@ class DataContext implements cf.ExecutionContext { for (final Object? key in argsJson.keys) { final argName = key.toString(); final Object? val = argsJson[key]; - args[argName] = _evaluateStream(val); + if ((name == 'and' || name == 'or') && + argName == 'values' && + val is List) { + final List> itemStreams = val.map((item) { + if (item is Map) { + if (item.containsKey('functionCall')) { + final Object? fc = item['functionCall']; + if (fc is Map && _isValidConditionShape(fc)) { + return _evaluateStream(fc); + } else { + genUiLogger.warning('Invalid condition expression: $item'); + return Stream.value(false); + } + } + if (!_isValidConditionShape(item)) { + genUiLogger.warning('Invalid condition expression: $item'); + return Stream.value(false); + } + } + return _evaluateStream(item); + }).toList(); + args[argName] = itemStreams.isEmpty + ? Stream.value([]) + : itemStreams.combineLatestAll(); + } else if (name == 'not' && argName == 'value') { + if (val is Map) { + if (val.containsKey('functionCall')) { + final Object? fc = val['functionCall']; + if (fc is Map && _isValidConditionShape(fc)) { + args[argName] = _evaluateStream(fc); + } else { + genUiLogger.warning('Invalid condition expression: $val'); + args[argName] = Stream.value(true); + } + } else if (!_isValidConditionShape(val)) { + genUiLogger.warning('Invalid condition expression: $val'); + args[argName] = Stream.value(true); + } else { + args[argName] = _evaluateStream(val); + } + } else { + args[argName] = _evaluateStream(val); + } + } else { + args[argName] = _evaluateStream(val); + } } } @@ -180,12 +222,20 @@ 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')) { - genUiLogger.warning('Invalid condition expression: $condition'); - return Stream.value(false); + if (condition is Map) { + if (condition.containsKey('functionCall')) { + final Object? fc = condition['functionCall']; + if (fc is Map && _isValidConditionShape(fc)) { + return evaluateConditionStream(fc); + } else { + genUiLogger.warning('Invalid condition expression: $condition'); + return Stream.value(false); + } + } + if (!_isValidConditionShape(condition)) { + genUiLogger.warning('Invalid condition expression: $condition'); + return Stream.value(false); + } } final Stream resultStream = _evaluateStream(condition); @@ -193,20 +243,25 @@ class DataContext implements cf.ExecutionContext { } } +bool _isValidConditionShape(Map map) { + if (map.containsKey('path') || map.containsKey('call')) return true; + if (map.containsKey('functionCall')) { + final Object? fc = map['functionCall']; + return fc is Map && _isValidConditionShape(fc); + } + return false; +} + /// Helper to determine truthiness according to A2UI expression semantics. +@internal bool isTruthy(Object? value) { - if (value is bool) return value; if (value == null) return false; + if (value is bool) return value; 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) { - return value['valid'] as bool; - } - return value.isNotEmpty; - } - return false; + if (value is Map) return value.isNotEmpty; + return true; } /// Resolves a context map definition against a [DataContext]. diff --git a/packages/genui/pubspec.yaml b/packages/genui/pubspec.yaml index 9ee257e5c..a21ce65d1 100644 --- a/packages/genui/pubspec.yaml +++ b/packages/genui/pubspec.yaml @@ -4,7 +4,7 @@ name: genui description: Generates and displays generative user interfaces (GenUI) in Flutter using AI. -version: 0.10.6 +version: 0.10.7 homepage: https://github.com/flutter/genui/tree/main/packages/genui license: BSD-3-Clause issue_tracker: https://github.com/flutter/genui/issues diff --git a/packages/genui/test/model/data_model_test.dart b/packages/genui/test/model/data_model_test.dart index 799341bd1..75cdefd1e 100644 --- a/packages/genui/test/model/data_model_test.dart +++ b/packages/genui/test/model/data_model_test.dart @@ -7,7 +7,6 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:genui/src/catalog/basic_catalog.dart'; -import 'package:genui/src/catalog/basic_catalog_widgets/widget_helpers.dart'; import 'package:genui/src/model/data_model.dart'; import 'package:genui/src/primitives/logging.dart'; import 'package:genui/src/primitives/simple_items.dart'; @@ -427,36 +426,189 @@ void main() { isFalse, ); - // ValidationResult map: valid flag determines truthiness - dataModel.update(DataPath('/valResult'), {'valid': true}); - final valResultCondition = {'path': '/valResult'}; + // Custom non-null objects are truthy + dataModel.update(DataPath('/custom'), DateTime(2025)); + final customCondition = {'path': '/custom'}; expect( - await context.evaluateConditionStream(valResultCondition).first, + await context.evaluateConditionStream(customCondition).first, isTrue, ); - - dataModel.update(DataPath('/valResult'), { - 'valid': false, - 'message': 'err', - }); - expect( - await context.evaluateConditionStream(valResultCondition).first, - isFalse, - ); }); test('evaluateConditionStream treats unknown functions and invalid maps as ' - 'false', () async { + 'false and logs warnings', () async { + final List logs = []; + final StreamSubscription sub = genUiLogger.onRecord.listen( + logs.add, + ); + addTearDown(sub.cancel); + final JsonMap unknownFunc = { 'call': 'noSuchFunction', 'args': {}, }; expect(await context.evaluateConditionStream(unknownFunc).first, isFalse); + expect( + logs.any( + (r) => + r.level == Level.WARNING && + r.message.contains('Function not found: noSuchFunction'), + ), + isTrue, + ); + + final JsonMap missingCall = {'call': null, 'args': {}}; + expect(await context.evaluateConditionStream(missingCall).first, isFalse); + expect( + logs.any( + (r) => + r.level == Level.WARNING && + r.message.contains('Function call missing "call" property'), + ), + isTrue, + ); - final invalidMap = {'invalid': 'structure'}; + final JsonMap invalidMap = {'invalid': 'structure'}; expect(await context.evaluateConditionStream(invalidMap).first, isFalse); + expect( + logs.any( + (r) => + r.level == Level.WARNING && + r.message.contains('Invalid condition expression'), + ), + isTrue, + ); + + final JsonMap invalidFc = {'functionCall': 'notAMap'}; + expect(await context.evaluateConditionStream(invalidFc).first, isFalse); + expect( + logs.any( + (r) => + r.level == Level.WARNING && + r.message.contains('Invalid condition expression'), + ), + isTrue, + ); }); + test( + 'nested malformed expressions inside and, or, not fail and log warning', + () async { + final contextWithFuncs = DataContext( + dataModel, + DataPath.root, + functions: BasicCatalogItems.asCatalog().functions, + ); + + final List logs = []; + final StreamSubscription sub = genUiLogger.onRecord.listen( + logs.add, + ); + addTearDown(sub.cancel); + + // Typo in nested function call inside `and` + final JsonMap andMalformed = { + 'call': 'and', + 'args': { + 'values': [ + {'cal': 'required', 'args': {}}, + true, + ], + }, + }; + expect( + await contextWithFuncs.evaluateConditionStream(andMalformed).first, + isFalse, + ); + expect( + logs.any( + (r) => + r.level == Level.WARNING && + r.message.contains('Invalid condition expression'), + ), + isTrue, + ); + + // Typo in nested function call inside `not` + final JsonMap notMalformed = { + 'call': 'not', + 'args': { + 'value': {'cal': 'required', 'args': {}}, + }, + }; + expect( + await contextWithFuncs.evaluateConditionStream(notMalformed).first, + isFalse, + ); + + // Malformed inner map inside functionCall wrapper in `and` + final JsonMap andMalformedFc = { + 'call': 'and', + 'args': { + 'values': [ + { + 'functionCall': { + 'cal': 'required', + 'args': {}, + }, + }, + true, + ], + }, + }; + expect( + await contextWithFuncs.evaluateConditionStream(andMalformedFc).first, + isFalse, + ); + + // Malformed inner map inside functionCall wrapper in `not` + final JsonMap notMalformedFc = { + 'call': 'not', + 'args': { + 'value': { + 'functionCall': {'cal': 'required', 'args': {}}, + }, + }, + }; + expect( + await contextWithFuncs.evaluateConditionStream(notMalformedFc).first, + isFalse, + ); + + // Top-level functionCall with malformed inner map + final JsonMap topMalformedFc = { + 'functionCall': {'cal': 'required', 'args': {}}, + }; + expect( + await contextWithFuncs.evaluateConditionStream(topMalformedFc).first, + isFalse, + ); + + // Unknown function inside `and` + final JsonMap andUnknown = { + 'call': 'and', + 'args': { + 'values': [ + {'call': 'nope', 'args': {}}, + true, + ], + }, + }; + expect( + await contextWithFuncs.evaluateConditionStream(andUnknown).first, + isFalse, + ); + expect( + logs.any( + (r) => + r.level == Level.WARNING && + r.message.contains('Function not found: nope'), + ), + isTrue, + ); + }, + ); + test( 'evaluateConditionStream resolves and/or functions with nested paths and function calls', () async { @@ -505,57 +657,16 @@ void main() { }, ); - test('evaluateConditionStream and checksToExpression correctly validate ' - 'check rules (Issue 2853)', () async { - final contextWithFuncs = DataContext( - dataModel, - DataPath.root, - functions: BasicCatalogItems.asCatalog().functions, - ); - - dataModel.update(DataPath('/email'), ''); - final checks = [ - { - 'condition': { - 'call': 'required', - 'args': { - 'value': {'path': '/email'}, - }, - }, - 'message': 'Required.', - }, - ]; - - // Single check condition alone evaluates to false when empty - expect( - await contextWithFuncs - .evaluateConditionStream(checks.first['condition']) - .first, - isFalse, - ); - - // checksToExpression combined expression evaluates to false when empty - expect( - await contextWithFuncs - .evaluateConditionStream(checksToExpression(checks)) - .first, - isFalse, - ); - - // When populated, both evaluate to true - dataModel.update(DataPath('/email'), 'ada@example.com'); - expect( - await contextWithFuncs - .evaluateConditionStream(checks.first['condition']) - .first, - isTrue, - ); - expect( - await contextWithFuncs - .evaluateConditionStream(checksToExpression(checks)) - .first, - isTrue, - ); + test('resolveContext resolves dynamic values inside lists', () async { + dataModel.update(DataPath('/n'), 42); + final JsonMap contextDef = { + 'items': [ + {'path': '/n'}, + 'literal', + ], + }; + final JsonMap resolved = await resolveContext(context, contextDef); + expect(resolved['items'], [42, 'literal']); }); }); }