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
3 changes: 3 additions & 0 deletions docs/contributing/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`)

Expand Down
6 changes: 6 additions & 0 deletions packages/genui/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
34 changes: 34 additions & 0 deletions packages/genui/lib/src/model/client_function.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down Expand Up @@ -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;
Comment thread
gspencergoog marked this conversation as resolved.
Resolved

@override
Stream<Object?> execute(JsonMap args, ExecutionContext context) {
try {
Expand All @@ -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;
Comment thread
gspencergoog marked this conversation as resolved.
Resolved

@override
Stream<Object?> execute(JsonMap args, ExecutionContext context) async* {
yield await executeAsync(args, context);
}
Comment thread
gspencergoog marked this conversation as resolved.
Resolved

/// Executes the function asynchronously.
Future<Object?> executeAsync(JsonMap args, ExecutionContext context);
}
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.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
Expand Down
306 changes: 306 additions & 0 deletions packages/genui/test/model/client_function_test.dart
Original file line number Diff line number Diff line change
@@ -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<Object?> 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<Object?> 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<Object?> executeAsync(JsonMap args, ExecutionContext context) async {
await Future<void>.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<Object?> 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<Object?> 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<Object?> 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<Object?> stream = func.execute({}, context);

expect(
stream.first,
throwsA(
isA<StateError>().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<Object?> 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<Object?> stream = func.execute({}, context);

expect(await stream.first, isNull);
});

test('emits stream error when Future rejects asynchronously', () async {
const func = _AsyncErrorFunction();
final Stream<Object?> stream = func.execute({}, context);

expect(
stream.first,
throwsA(
isA<StateError>().having(
(e) => e.message,
'message',
'Async future error',
),
),
);
});

test(
'catches synchronous throw before Future and emits stream error',
() async {
const func = _SyncThrowInAsyncFunction();
final Stream<Object?> stream = func.execute({}, context);

expect(
stream.first,
throwsA(
isA<ArgumentError>().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<Object?> 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<String, Object> input = {
'call': 'fetchAsync',
'args': {'prefix': 'Hello'},
};

final Stream<Object?> stream = context.resolve(input);
expect(await stream.first, 'Hello processed async');
});

test('resolves sync function call via DataContext', () async {
final Map<String, Object> input = {
'call': 'addSync',
'args': {'a': 10, 'b': 25},
};

final Stream<Object?> stream = context.resolve(input);
expect(await stream.first, 35);
});
});
}
Loading