diff --git a/docs/contributing/design.md b/docs/contributing/design.md index 7b1ccffcf..ac606b91f 100644 --- a/docs/contributing/design.md +++ b/docs/contributing/design.md @@ -54,6 +54,9 @@ This layer defines the data structures that represent the dynamic UI and the con - **`UiDefinition` and `UiEvent`**: `UiDefinition` represents a complete UI tree to be rendered, including the root widget and a map of all widget definitions. `UiEvent` is a data object representing a user interaction. `UserActionEvent` is a subtype used for events that should trigger a submission to the AI, like a button tap. - **`ChatMessage`**: A sealed class representing the different types of messages in a conversation: `UserMessage`, `AiTextMessage`, `ToolResponseMessage`, `AiUiMessage`, `InternalMessage`, and `UserUiInteractionMessage`. - **`DataModel` and `DataContext`**: The `DataModel` is a centralized, observable key-value store that holds the entire dynamic state of the UI. Widgets receive a `DataContext`, which is a view into the `DataModel` that understands the widget's current scope. This allows widgets to subscribe to changes in the data model and rebuild reactively. This separation of data and UI structure is a core principle of the architecture. +- **`ClientFunction`**: The base interface for client-side functions registered in a `Catalog` and invoked by expressions. It provides reactive stream execution via `execute(JsonMap args, ExecutionContext context)`. Implementations include: + - `SynchronousClientFunction`: A base class for synchronous client functions overriding `executeSync`. + - `AsynchronousClientFunction`: A base class for single-shot asynchronous client functions overriding `executeAsync`. ### 4. Widget Catalog Layer (`lib/src/catalog/`) diff --git a/packages/genui/CHANGELOG.md b/packages/genui/CHANGELOG.md index 72880c452..18c4c02b2 100644 --- a/packages/genui/CHANGELOG.md +++ b/packages/genui/CHANGELOG.md @@ -1,5 +1,11 @@ # [genui](https://pub.dev/packages/genui) Changelog +## 0.10.6 + +- Added `AsynchronousClientFunction` base class for single-shot asynchronous + client functions returning a `Future` (via `executeAsync`), complementing + `SynchronousClientFunction` (`executeSync`). + ## 0.10.5 - **Fix**: Resolve validation checks and preserve error messages across basic catalog components. diff --git a/packages/genui/lib/src/model/client_function.dart b/packages/genui/lib/src/model/client_function.dart index d025cacf4..2078543f4 100644 --- a/packages/genui/lib/src/model/client_function.dart +++ b/packages/genui/lib/src/model/client_function.dart @@ -50,6 +50,10 @@ abstract interface class ExecutionContext { /// Functions are reactive, returning a [Stream] of values. /// This allows functions to push updates to the UI (e.g. a clock or network /// status). +/// +/// For single-shot synchronous functions, extend [SynchronousClientFunction]. +/// For single-shot asynchronous functions that return a [Future], extend +/// [AsynchronousClientFunction]. /// The type of value a client function returns. enum ClientFunctionReturnType { string('string'), @@ -101,9 +105,16 @@ abstract interface class ClientFunction { /// A base class for synchronous client functions. /// /// Implementers should override [executeSync] to provide the synchronous logic. +/// +/// For asynchronous functions returning a [Future], extend +/// [AsynchronousClientFunction]. For multi-value streaming or reactive +/// functions, implement [ClientFunction] directly. abstract class SynchronousClientFunction implements ClientFunction { const SynchronousClientFunction(); + @override + ClientFunctionReturnType get returnType => ClientFunctionReturnType.any; + @override Stream execute(JsonMap args, ExecutionContext context) { try { @@ -116,3 +127,26 @@ abstract class SynchronousClientFunction implements ClientFunction { /// Executes the function synchronously. Object? executeSync(JsonMap args, ExecutionContext context); } + +/// A base class for asynchronous client functions that return a [Future]. +/// +/// Implementers should override [executeAsync] to provide the asynchronous +/// logic. +/// +/// For synchronous logic, extend [SynchronousClientFunction]. For multi-value +/// streaming or reactive functions (e.g. subscribing to continuous data +/// updates), implement [ClientFunction] directly. +abstract class AsynchronousClientFunction implements ClientFunction { + const AsynchronousClientFunction(); + + @override + ClientFunctionReturnType get returnType => ClientFunctionReturnType.any; + + @override + Stream execute(JsonMap args, ExecutionContext context) async* { + yield await executeAsync(args, context); + } + + /// Executes the function asynchronously. + Future executeAsync(JsonMap args, ExecutionContext context); +} diff --git a/packages/genui/pubspec.yaml b/packages/genui/pubspec.yaml index f4ae0019a..9ee257e5c 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.5 +version: 0.10.6 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/client_function_test.dart b/packages/genui/test/model/client_function_test.dart new file mode 100644 index 000000000..cb89a4475 --- /dev/null +++ b/packages/genui/test/model/client_function_test.dart @@ -0,0 +1,306 @@ +// Copyright 2025 The Flutter Authors. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:genui/genui.dart'; +import 'package:json_schema_builder/json_schema_builder.dart'; + +class _AddSyncFunction extends SynchronousClientFunction { + const _AddSyncFunction(); + + @override + String get name => 'addSync'; + + @override + String get description => 'Adds two numbers synchronously.'; + + @override + Schema get argumentSchema => + S.object(properties: {'a': S.number(), 'b': S.number()}); + + @override + ClientFunctionReturnType get returnType => ClientFunctionReturnType.number; + + @override + Object? executeSync(JsonMap args, ExecutionContext context) { + final num a = args['a'] as num? ?? 0; + final num b = args['b'] as num? ?? 0; + return a + b; + } +} + +class _FailSyncFunction extends SynchronousClientFunction { + const _FailSyncFunction(); + + @override + String get name => 'failSync'; + + @override + String get description => 'Throws synchronously.'; + + @override + Schema get argumentSchema => S.object(); + + @override + Object? executeSync(JsonMap args, ExecutionContext context) { + throw StateError('Sync failure'); + } +} + +class _FetchAsyncFunction extends AsynchronousClientFunction { + const _FetchAsyncFunction(); + + @override + String get name => 'fetchAsync'; + + @override + String get description => 'Fetches a message asynchronously.'; + + @override + Schema get argumentSchema => S.object(properties: {'prefix': S.string()}); + + @override + ClientFunctionReturnType get returnType => ClientFunctionReturnType.string; + + @override + Future executeAsync(JsonMap args, ExecutionContext context) async { + final String prefix = args['prefix'] as String? ?? ''; + return '$prefix processed async'; + } +} + +class _AsyncNullFunction extends AsynchronousClientFunction { + const _AsyncNullFunction(); + + @override + String get name => 'asyncNull'; + + @override + String get description => 'Returns null asynchronously.'; + + @override + Schema get argumentSchema => S.object(); + + @override + Future executeAsync(JsonMap args, ExecutionContext context) async { + return null; + } +} + +class _AsyncErrorFunction extends AsynchronousClientFunction { + const _AsyncErrorFunction(); + + @override + String get name => 'asyncError'; + + @override + String get description => 'Throws an error inside Future.'; + + @override + Schema get argumentSchema => S.object(); + + @override + Future executeAsync(JsonMap args, ExecutionContext context) async { + await Future.delayed(Duration.zero); + throw StateError('Async future error'); + } +} + +class _SyncThrowInAsyncFunction extends AsynchronousClientFunction { + const _SyncThrowInAsyncFunction(); + + @override + String get name => 'syncThrowInAsync'; + + @override + String get description => 'Throws synchronously before returning Future.'; + + @override + Schema get argumentSchema => S.object(); + + @override + Future executeAsync(JsonMap args, ExecutionContext context) { + throw ArgumentError('Sync throw before future'); + } +} + +class _LazyTestFunction extends AsynchronousClientFunction { + _LazyTestFunction(this.onExecute); + + final void Function() onExecute; + + @override + String get name => 'lazyTest'; + + @override + String get description => 'Tests lazy execution.'; + + @override + Schema get argumentSchema => S.object(); + + @override + Future executeAsync(JsonMap args, ExecutionContext context) async { + onExecute(); + return 'done'; + } +} + +void main() { + group('SynchronousClientFunction', () { + late DataModel dataModel; + late DataContext context; + + setUp(() { + dataModel = InMemoryDataModel(); + context = DataContext(dataModel, DataPath.root); + }); + + test('executes synchronously and emits value on stream', () async { + const func = _AddSyncFunction(); + final Stream stream = func.execute({'a': 2, 'b': 3}, context); + + expect(await stream.first, 5); + const Object obj = func; + expect(obj is ClientFunction, isTrue); + expect(obj is SynchronousClientFunction, isTrue); + expect(obj is AsynchronousClientFunction, isFalse); + }); + + test('catches synchronous exception and emits error on stream', () async { + const func = _FailSyncFunction(); + final Stream stream = func.execute({}, context); + + expect( + stream.first, + throwsA( + isA().having((e) => e.message, 'message', 'Sync failure'), + ), + ); + }); + }); + + group('AsynchronousClientFunction', () { + late DataModel dataModel; + late DataContext context; + + setUp(() { + dataModel = InMemoryDataModel(); + context = DataContext(dataModel, DataPath.root); + }); + + test('executes asynchronously and emits future result on stream', () async { + const func = _FetchAsyncFunction(); + final Stream stream = func.execute({'prefix': 'data:'}, context); + + expect(await stream.first, 'data: processed async'); + const Object obj = func; + expect(obj is ClientFunction, isTrue); + expect(obj is AsynchronousClientFunction, isTrue); + expect(obj is SynchronousClientFunction, isFalse); + }); + + test('emits null value on stream when executeAsync returns null', () async { + const func = _AsyncNullFunction(); + final Stream stream = func.execute({}, context); + + expect(await stream.first, isNull); + }); + + test('emits stream error when Future rejects asynchronously', () async { + const func = _AsyncErrorFunction(); + final Stream stream = func.execute({}, context); + + expect( + stream.first, + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Async future error', + ), + ), + ); + }); + + test( + 'catches synchronous throw before Future and emits stream error', + () async { + const func = _SyncThrowInAsyncFunction(); + final Stream stream = func.execute({}, context); + + expect( + stream.first, + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Sync throw before future', + ), + ), + ); + }, + ); + + test( + 'executeAsync is executed lazily only when stream is listened to', + () async { + var executed = false; + final func = _LazyTestFunction(() => executed = true); + + final Stream stream = func.execute({}, context); + expect(executed, isFalse); + + await stream.first; + expect(executed, isTrue); + }, + ); + }); + + group('Catalog and DataContext integration with Synchronous and Asynchronous ' + 'functions', () { + late DataModel dataModel; + late DataContext context; + late Catalog catalog; + + setUp(() { + catalog = const Catalog( + [], + functions: [_AddSyncFunction(), _FetchAsyncFunction()], + ); + + dataModel = InMemoryDataModel(); + context = DataContext( + dataModel, + DataPath.root, + functions: catalog.functions, + ); + }); + + test('Catalog accepts both sync and async functions', () { + expect(catalog.functions.length, 2); + expect(context.getFunction('addSync'), isNotNull); + expect(context.getFunction('fetchAsync'), isNotNull); + }); + + test('resolves asynchronous function call via DataContext', () async { + final Map input = { + 'call': 'fetchAsync', + 'args': {'prefix': 'Hello'}, + }; + + final Stream stream = context.resolve(input); + expect(await stream.first, 'Hello processed async'); + }); + + test('resolves sync function call via DataContext', () async { + final Map input = { + 'call': 'addSync', + 'args': {'a': 10, 'b': 25}, + }; + + final Stream stream = context.resolve(input); + expect(await stream.first, 35); + }); + }); +}