Skip to content
Open
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
5 changes: 4 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,10 @@ cd ../runtime
npm run record:a2ui -- --runtime-dir ../runtime-1.91
```

Pass `--case <name>` to record one case. The recorder starts the runtime
Pass `--case <name>` to record one case. The `item_refresh` case is the
example app's A2UI flow, with its own catalog and agent id, and goes to
`example/test/fixtures/a2ui/<runtime version>/` instead, where
`example/test/a2ui/widgets/a2ui_page_test.dart` replays it. The recorder starts the runtime
on a free local port for each case and posts the requests the Flutter
client sends. Each file starts with a `{"fixture": {...}}` header (the
runtime and middleware versions and what the case does), then the
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ Send these prompts to see each part of the SDK:
appears; the agent continues with your answer.
- **App context:** "Where do I live?" The agent answers from the current user
that the app shares as context (Ada, from Lima).
- **A2UI with a custom catalog:** Tap the A2UI button in the app bar, then
"Show me three suggestions under $30." The agent renders cards from the
app's own catalog; pin two, tap refresh on the third, and only that card
changes. See [A2UI](example/README.md#a2ui) and the
[A2UI quickstart](packages/copilotkit_flutter/README.md#quickstart-a-custom-catalog).
- **Stop:** Tap the stop button while a reply streams. The partial reply stays,
and you can send the next message.

Expand Down
25 changes: 18 additions & 7 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,17 +366,28 @@ with its features in `lib/` instead of `lib/src/`:

- `main.dart` reads the runtime URL and runs `App`, which provides the
`CopilotKit` client to the widget tree.
- Each feature (`app`, `chat`, `demo`) has a barrel and only the folders it
needs: `models/` for the app's JSON models, logic classes like
`WeatherService` at its root, and `widgets/`. Features import each other
only through their barrels.
- Each feature (`app`, `chat`, `demo`, `a2ui`, ...) has a barrel and only
the folders it needs: `models/` for the app's JSON models, logic classes
like `WeatherService` at its root, and `widgets/`. Features import each
other only through their barrels, without cycles: `app` puts the `a2ui`
feature's button in the chat's app bar, and `a2ui` reuses the chat's
message list and composer.
- `a2ui` is the A2UI reference: its catalog (`ItemCatalog`) and a class per
component (`ItemCardComponent`, with its schema and builder) at its root,
and the components' plain Flutter widgets in `widgets/`.
- A page provides what its view reads: `ChatPage` wraps `ChatView` in a
`CopilotChatProvider`.
- It imports the SDK only through the `copilotkit_flutter` barrel, and `ack`
to build tool schemas. It doesn't declare `copilotkit` in its
`pubspec.yaml`.
- It imports the SDK only through the `copilotkit_flutter` barrel, `ack`
to build tool schemas, and `a2ui_flutter`, `a2ui_core` and
`json_schema_builder` to build its A2UI catalog. It doesn't declare
`copilotkit` in its `pubspec.yaml`.
- Tests mirror `lib/`: `lib/demo/weather_service.dart` is covered by
`test/demo/weather_service_test.dart`.
`test/a2ui/widgets/a2ui_page_test.dart` replays the A2UI flow recorded in
`test/fixtures/a2ui/` through the real client and page, the way
`copilotkit_flutter`'s recorded fixture test does, and
`test/a2ui_live_test.dart` runs it against a real runtime, skipped unless
`COPILOTKIT_LIVE_RUNTIME_URL` is set.

## Following the architecture

Expand Down
83 changes: 83 additions & 0 deletions example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,75 @@ Without a valid `RUNTIME_URL`, the app shows a **Runtime URL missing** screen
instead of the chat. The app logs errors through `dart:developer`, so check the
debug console when something fails.

## A2UI

The **A2UI** button in the chat's app bar opens a chat with the runtime's
`a2ui` agent (`tool/runtime/a2ui_agent.ts`), which builds its UI from the
app's own A2UI catalog. It is the reference for an app that renders A2UI
with custom components:

- `lib/a2ui/item_catalog.dart`: the catalog. Three components,
`ItemList`, `ItemCard` and `RangeFilter`, next to the basic `Column`,
`Row`, `Text` and `Divider`. Each component is a class with a schema and
a builder (`item_card_component.dart` and the others), and its widget is
plain Flutter (`widgets/item_card.dart` and the others).
- `lib/a2ui/widgets/a2ui_page.dart`: `CopilotA2ui` advertises the catalog
and renders the agent's surfaces in the chat below it.
- `tool/runtime/server.ts`: `a2ui: { injectA2UITool: true, agents: ["a2ui"] }`
turns the runtime's A2UI middleware on for that agent only, and
`refresh_item`, a server tool with a fixed schema, answers a refresh with
one `updateDataModel` of `/items/<index>`.

The flow it shows:

1. The agent renders an `ItemList` of `ItemCard`s, each bound to its own
`/items/<index>`, and a `RangeFilter` bound to `/filter/max`.
2. Pinning a card and moving the filter only change the surface's data:
pins go to `/pinnedIds`, the filter to `/filter/max`. Nothing is sent.
3. Refresh on a card sends its `refresh_item` action. Its context,
`{itemIndex, pinnedIds, filterMax}`, reads that local state.
4. The agent calls `refresh_item`, and only that card changes.

### Protocol version

The runtime pins CopilotKit 1.79, whose A2UI middleware (0.0.10) only
generates A2UI v0.9, so `A2uiPage.protocol` is `A2uiProtocol.v0_9` and the
catalog is a v0.9 catalog. To use A2UI 1.0 on CopilotKit 1.91 or later:

1. Set `@copilotkit/runtime` to `1.91.0` in `tool/runtime/package.json` and
run `npm install` there. Change the `version: "v0.9"` of the
`refresh_item` envelope in `tool/runtime/a2ui_agent.ts` to `"1.0"`.
2. Write the components' schemas with `CommonSchemasV1` and a `$ref` to
`common_types.json` for the action, in a catalog with
`protocolVersion: A2uiProtocolVersion.v1_0` and only the three item
components, and pass it with the v1.0 basic catalog:
`[itemCatalogV1_0, basicCatalog()]`. A v1.0 surface draws on several
catalogs, so it doesn't copy the basic components.
3. Set `A2uiPage.protocol` to `A2uiProtocol.v1_0`.

See the `a2ui_flutter` README, "Defining Custom Components", for a v1.0
component.

### Tests

`test/a2ui/widgets/a2ui_page_test.dart` replays the flow recorded from
runtimes 1.79 and 1.91 (`test/fixtures/a2ui/`) through the real client and
page, and checks that the action carries the pins and the filter and that
only the third card rebuilds. `npm run record:a2ui -- --case item_refresh`
in `tool/runtime` records it again (see "Re-recording A2UI fixtures" in
`CONTRIBUTING.md`).

`test/a2ui_live_test.dart` runs the same flow against a real runtime and
model. It is skipped unless `COPILOTKIT_LIVE_RUNTIME_URL` is set, so it never
runs on CI:

```sh
./tool/start_runtime.sh # in one terminal, with a model key
cd example
COPILOTKIT_LIVE_RUNTIME_URL=http://localhost:8200/api/copilotkit \
flutter test test/a2ui_live_test.dart
```

## Troubleshooting

When a message fails in the app, the chat only shows **Something went wrong.
Expand Down Expand Up @@ -246,6 +315,20 @@ into its shared state.
- Edit a word in the document, then ask "Add one sentence at the end". The
new version keeps your edit.

### A2UI

These checks cover the A2UI screen (see [A2UI](#a2ui)).

- Tap the A2UI button in the app bar, then tap **Show me three suggestions
under $30.** A building row shows, then a filter set to $30 and three
cards, each priced at $30 or less.
- Pin the first two cards and move the filter to $25. Nothing is sent.
- Tap refresh on the third card. A pending row shows under the surface, then
only the third card changes, to an item at $25 or less. The first two keep
their pins, and the agent replies in one sentence.
- The chat shows no `render_a2ui`, `refresh_item` or `log_a2ui_event` rows
besides the agent's reply.

### Learning capture

Run the app with `--dart-define=LEARNING=true` against an Intelligence
Expand Down
3 changes: 3 additions & 0 deletions example/lib/a2ui/a2ui.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export 'item_catalog.dart';
export 'widgets/a2ui_button.dart';
export 'widgets/a2ui_page.dart';
72 changes: 72 additions & 0 deletions example/lib/a2ui/item_card_component.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import 'package:a2ui_core/a2ui_core.dart';
import 'package:a2ui_flutter/a2ui_flutter.dart';
import 'package:example/a2ui/widgets/item_card.dart';
import 'package:flutter/widgets.dart';
import 'package:json_schema_builder/json_schema_builder.dart' show Schema;

/// The `ItemCard` A2UI component: one item, rendered as an [ItemCard].
///
/// Its props are `itemId`, `title`, `subtitle` and `price`, `pinnedIds`, and
/// the `onRefresh` action. The agent binds each value to the item's own
/// path, like `/items/2/title`, so an update of `/items/2` rebuilds this
/// card and no other.
///
/// Pinning is the user's local state: the card is pinned while
/// `pinnedIds`, bound to a list such as `/pinnedIds`, holds its `itemId`, and
/// tapping the pin adds or removes it there. Nothing goes to the agent
/// until an action's context reads the list.
class const ItemCardComponent() {
/// Creates the `ItemCard` component.
this;

/// The component's name in the catalog.
static const name = 'ItemCard';

/// The component's schema, in the A2UI v0.9 common types.
Schema get schema => Schema.object(
description:
'One item as a card with a pin and a refresh button. Bind every '
'value to the item\'s own path, e.g. {"path": "/items/2/title"}, so '
'an update of /items/2 changes only this card.',
properties: {
'itemId': CommonSchemas.dynamicString,
'title': CommonSchemas.dynamicString,
'subtitle': CommonSchemas.dynamicString,
'price': CommonSchemas.dynamicNumber,
'pinnedIds': CommonSchemas.dynamicStringList,
'onRefresh': CommonSchemas.action,
},
required: ['itemId', 'title'],
);

/// The component with its Flutter implementation, for a catalog.
ComponentImplementation get implementation =>
ComponentImplementation(name: name, schema: schema, builder: call);

/// Builds the [ItemCard] for [props].
Widget call(
BuildContext context,
ComponentNode<ComponentImplementation> node,
ComponentProps props,
ChildWidgetBuilder buildChild,
) {
final id = props.string('itemId');
final pinnedIds = props.list('pinnedIds').whereType<String>().toList();
final pinned = pinnedIds.contains(id);
final binding = props.writable('pinnedIds');
return ItemCard(
title: props.string('title') ?? '',
subtitle: props.string('subtitle'),
price: props.number('price'),
pinned: pinned,
onTogglePin: id == null || binding == null
? null
: () => binding.set([
for (final pinnedId in pinnedIds)
if (pinnedId != id) pinnedId,
if (!pinned) id,
]),
onRefresh: props.action('onRefresh'),
);
}
}
43 changes: 43 additions & 0 deletions example/lib/a2ui/item_catalog.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import 'package:a2ui_flutter/a2ui_flutter.dart';
import 'package:a2ui_flutter/v0_9/basic_catalog.dart' as v0_9;
import 'package:example/a2ui/item_card_component.dart';
import 'package:example/a2ui/item_list_component.dart';
import 'package:example/a2ui/range_filter_component.dart';

/// The example's A2UI catalog: `ItemList`, `ItemCard` and `RangeFilter`,
/// with the basic `Column`, `Row`, `Text` and `Divider` to lay them out.
///
/// It is an A2UI v0.9 catalog, the version the example runtime's
/// CopilotKit 1.79 generates. A v0.9 surface draws on one catalog, so the
/// basic components it needs go in this one, under the example's own id,
/// and the agent is told about these eight components only: the whole basic
/// catalog would add about 40 KB to every run.
class const ItemCatalog({
final ItemListComponent _list = const ItemListComponent(),
final ItemCardComponent _card = const ItemCardComponent(),
final RangeFilterComponent _filter = const RangeFilterComponent(),
}) {
/// Creates the example's catalog.
this;

/// The catalog's id, which the runtime stamps on the surfaces it creates.
static const id =
'https://github.com/VGVentures/copilotkit_flutter_sdk/example/item_catalog/v0_9.json';

/// The catalog, with the Flutter implementation of each component.
CatalogImplementation get catalog => CatalogImplementation(
id: id,
components: [
v0_9.BasicComponents.column,
v0_9.BasicComponents.row,
v0_9.BasicComponents.text,
v0_9.BasicComponents.divider,
_list.implementation,
_card.implementation,
_filter.implementation,
],
themeSchema: v0_9.BasicComponents.api.themeSchema,
protocolVersion: v0_9.BasicComponents.api.protocolVersion,
definitions: v0_9.BasicComponents.api.definitions,
);
}
41 changes: 41 additions & 0 deletions example/lib/a2ui/item_list_component.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'package:a2ui_core/a2ui_core.dart';
import 'package:a2ui_flutter/a2ui_flutter.dart';
import 'package:example/a2ui/widgets/item_list.dart';
import 'package:flutter/widgets.dart';
import 'package:json_schema_builder/json_schema_builder.dart' show Schema;

/// The `ItemList` A2UI component: its `items`, one card per item, rendered
/// as an [ItemList].
///
/// `items` lists the cards' component ids, one `ItemCard` per index bound
/// to `/items/<index>`. A template (`{"componentId", "path"}`) renders too,
/// but its cards read paths relative to the list, so the agent can't give
/// each card's action its own index.
class const ItemListComponent() {
/// Creates the `ItemList` component.
this;

/// The component's name in the catalog.
static const name = 'ItemList';

/// The component's schema, in the A2UI v0.9 common types.
Schema get schema => Schema.object(
description:
'A vertical list of ItemCards. List one ItemCard id per item, e.g. '
'["card-0", "card-1", "card-2"], each bound to /items/<index>.',
properties: {'items': CommonSchemas.childList},
required: ['items'],
);

/// The component with its Flutter implementation, for a catalog.
ComponentImplementation get implementation =>
ComponentImplementation(name: name, schema: schema, builder: call);

/// Builds the [ItemList] of the `items` of [props].
Widget call(
BuildContext context,
ComponentNode<ComponentImplementation> node,
ComponentProps props,
ChildWidgetBuilder buildChild,
) => ItemList(children: props.children('items').map(buildChild).toList());
}
56 changes: 56 additions & 0 deletions example/lib/a2ui/range_filter_component.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import 'package:a2ui_core/a2ui_core.dart';
import 'package:a2ui_flutter/a2ui_flutter.dart';
import 'package:example/a2ui/widgets/range_filter.dart';
import 'package:flutter/widgets.dart';
import 'package:json_schema_builder/json_schema_builder.dart' show Schema;

/// The `RangeFilter` A2UI component: a [RangeFilter] whose `value` is
/// two-way bound, like `/filter/max`.
///
/// Each move of the slider writes the new whole value to the bound path,
/// where an action's context reads it. A literal `value` renders the slider
/// disabled.
class const RangeFilterComponent() {
/// Creates the `RangeFilter` component.
this;

/// The component's name in the catalog.
static const name = 'RangeFilter';

/// The component's schema, in the A2UI v0.9 common types.
Schema get schema => Schema.object(
description:
'A slider for an upper bound, such as a maximum price. Bind value to '
'a data path, e.g. {"path": "/filter/max"}: the user\'s moves are '
'written there.',
properties: {
'label': CommonSchemas.dynamicString,
'value': CommonSchemas.dynamicNumber,
'min': Schema.number(description: 'The lowest bound. Defaults to 0.'),
'max': Schema.number(description: 'The highest bound. Defaults to 100.'),
},
required: ['value'],
);

/// The component with its Flutter implementation, for a catalog.
ComponentImplementation get implementation =>
ComponentImplementation(name: name, schema: schema, builder: call);

/// Builds the [RangeFilter] for [props].
Widget call(
BuildContext context,
ComponentNode<ComponentImplementation> node,
ComponentProps props,
ChildWidgetBuilder buildChild,
) {
final max = props.number('max') ?? 100;
final binding = props.writable('value');
return RangeFilter(
label: props.string('label') ?? 'Up to',
value: props.number('value') ?? max,
min: props.number('min') ?? 0,
max: max,
onChanged: binding == null ? null : (value) => binding.set(value.round()),
);
}
}
21 changes: 21 additions & 0 deletions example/lib/a2ui/widgets/a2ui_button.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:copilotkit_flutter/copilotkit_flutter.dart';
import 'package:example/a2ui/widgets/a2ui_page.dart';
import 'package:flutter/material.dart';

/// An app bar button that opens the [A2uiPage] on the nearest `CopilotKit`
/// client.
class const A2uiButton({super.key}) extends StatelessWidget {
@override
Widget build(BuildContext context) => IconButton(
key: const Key('open_a2ui'),
tooltip: 'A2UI',
icon: const Icon(Icons.dashboard_customize_outlined),
onPressed: () => Navigator.of(context).push<void>(
MaterialPageRoute(
// Named, so learning capture records which screen opened.
settings: const RouteSettings(name: '/a2ui'),
builder: (_) => A2uiPage(client: CopilotKit.of(context)),
),
),
);
}
Loading