diff --git a/.claude/skills/sdk-dart/SKILL.md b/.claude/skills/sdk-dart/SKILL.md index 6ea544bcbc..88382bda90 100644 --- a/.claude/skills/sdk-dart/SKILL.md +++ b/.claude/skills/sdk-dart/SKILL.md @@ -189,6 +189,11 @@ is kept working. What the router writes is what it renders: session holds; on a call, by an `AIToolApprovalCard` over `session.approvals`. A call the router holds itself (a connector's under `require_approval`, the agent's scheduling tools for a repeating task, #2533) never reaches `approvals`, so only `decideShown` answers it. +- An incognito session has no channel, and `chat()` throws. `Conversation` folds + `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into `Turn.steps` and + `Turn.isDone`, as Kotlin's does; `session.turnMessages` gives the channel's message shape, and + a waiting call asks `backend.userId`, not `Session.userId` (the agent's name on the call). + `flutter_demo`'s `AgentChat.unkept` shows it. - `AIConversationView` lays the channel out in turns, `ChatComposer` asks and stops, and `AIVoiceGlowView` / `AIVoiceWaveView` show the agent on a call. diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index edc85d5fe3..e3db1be88e 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -956,7 +956,7 @@ Connections (AI-3376): Go has `client.Connections()` for the accounts the app an Connections in Rust (AI-3383): `Client::connections()` (`sdks/rust/src/connections.rs`) follows Go's shape with the user as `user_id` of each call: `create(&NewConnection{connector, label, user_id})`, `authorize(id, &AuthorizeOptions{return_url, user_id})`, `get(id, user_id: Option<&str>)`, `list(&ConnectionFilter{connector, user_id})`, `delete(id, user_id: Option<&str>)`; options structs rather than adjacent `Option<&str>` so a label cannot be swapped for a user. A user given goes through `pub(crate) Client::acting_for`, so the header matches the call and replaces a `ClientOptions::user_id` the client was built with; no user (or an empty one) leaves the client as built, as Go's `UserID` does (92148e5fe). Rust had no public acting-for helper to deprecate for AI-3387: `Backend` and its `acting_for` field are crate-private (`sdks/rust/src/backend.rs`, not re-exported from `lib.rs`), and `Client::acting_for` is `pub(crate)`. No other SDK needs to change for this. Connections in JavaScript (AI-3378, AI-3387): `api.connections` has `create(connectorId, { label, userId })`, `authorize(id, { returnUrl, userId })`, `get(id, { userId })`, `list({ connectorId, userId })` (every page, 200 a page, newest first) and `delete(id, { userId })`. The user is an optional parameter of each call, never a client of its own: given, it is sent as `owner.user_id` (create) and `X-Stream-User-Id` on every call, reads included, with the app's server credential (an internal `speakingFor(backend, userId)` in `backend.ts`, kept off `Backend`'s type, which Dispatch's `answer` also uses); left out or empty, the call is the app's (`owner.type: app`, `owner_type=app`, no header added). Optional parts are one options object, never adjacent positional strings. `Backend.actingFor` stays public and working, marked `@deprecated` (Chat's "deprecate, never break"), and a test pins its requests to the base commit's. A client built with `BackendOptions.userId` still sends that user on a call without `userId`, as on every other call; one built on the deprecated `actingFor` does not (the call is the app's). A `userId` on a client that is not server side (a device, or a page on a customer-id router) is a `ConfigurationError` before any request. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP (AI-3379..AI-3383). Connections in Python (AI-3379, no spec change): `plugins/stream` has `api.connections` with the Go shape: `create(connector_id, *, label=None, user_id=None)`, `authorize(id, *, return_url=None, user_id=None)` returning `Authorization`, `get(id, *, user_id=None)`, `list(*, connector_id=None, user_id=None)` reading every page, `delete(id, *, user_id=None)`; every option is keyword-only, so a user id cannot land in the label's or connector's slot. A user given is `owner.user_id` (create) and `X-Stream-User-Id` on every call, replacing whoever the client acts for and the user its backend was built for (which behind the proxy would sign that user's own token); none is the app's connection, sent as the client is otherwise (a client built for a user still names that user). AI-3387 in Python: `Client.for_user` is deprecated (`DeprecationWarning`, still working) in favour of a keyword-only `user_id=None`, last, on `Client.agent` and `Client.router`, on a client built with `team=`/`usage_categories=`; a device naming a user is refused before any request. Dispatch and `Accelerated` keep `Backend.acting_for` internally. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Other SDKs need to update: Dart, whose AI components read the same steps, should fold the same frames into their `Conversation` turns and show a session with no channel through their transports; the server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same (`Turn.steps`, `Turn.isDone`, `session.turnMessages`, each step the record `AIMessagePart.parseAll` takes), its `target_user_id` the agents' own user as in Kotlin; `flutter_demo`'s `AgentChat` shows an incognito session from them. The server SDKs need nothing. An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types, and Kotlin has `SessionOptions.ui`, which `Sessions.create` sends as it is (null left out); Python, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Every server SDK now declares one: Python `register(display_title=...)` (on `ToolPolicy`, sent by `plugins/stream`'s `_with_policy`), .NET `displayTitle:`, Ruby `display_title:`, PHP `displayTitle:` and Rust's `SessionTool.display_title`; Swift, Kotlin and Dart read it off the tool call state. Nothing is left to update. Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Connections.php`) has `create(NewConnection)`, `authorize(id, AuthorizeOptions)`, `get(id, userId)`, `list(ConnectionFilter)` (every page, `limit` 200, a repeated cursor ends it) and `delete(id, userId)`, Go's shape: the calls with more than one optional take an options object (`NewConnection`, `AuthorizeOptions`, `ConnectionFilter`, `sdks/php/src/`) like Go's `ConnectionRequest`, `AuthorizeOptions` and `ConnectionFilter`, so a user id cannot take the place of a label, return URL or connector (R1.1 of the review: `create('linear', 'ada')` had filed the user's account as the app's). `userId` is optional and last (a parameter of `get` and `delete`, a field of the options objects); given, it is `owner.user_id` and `X-Stream-User-Id` with the server credential (a server token behind the proxy, never a user token); left out or empty, `owner.type: app` and no header, whoever the backend otherwise acts for. `Connections` goes through `Backend::speakingFor` (`@internal`, PHP has no package visibility), which drops the backend's own user. `Dispatch::answer` goes through `Backend::writingFor` (`@internal`, `Dispatch.php:193`), which keeps the backend's own user when the writer has none, as `onBehalfOf` did before; `onBehalfOf` calls `writingFor`. `Backend::onBehalfOf` stays public and working, `@deprecated` in favour of the `userId` parameter; PHP's `Backend::actingFor` is unchanged and still signs a user token (the device path), so its name means something else than `actingFor` in Go and JavaScript. No other public PHP wrapper used `onBehalfOf`. diff --git a/.claude/skills/sdk/notes/2026-11-23-target-user-id.md b/.claude/skills/sdk/notes/2026-11-23-target-user-id.md new file mode 100644 index 0000000000..9b696d229b --- /dev/null +++ b/.claude/skills/sdk/notes/2026-11-23-target-user-id.md @@ -0,0 +1 @@ +An incognito session's tool call waiting for approval is shown as an `ai_tool_call` step with `target_user_id`: the user Stream's approver shows the card to. Kotlin and Dart send the person's user, the one the app signed in as (`backend.user` in Kotlin, `backend.userId` in Dart), which is what a kept reply's step uses (the conversation's owner, `parts.go`). `Session.user_id` is the name the agent joined the call as, not the session's owner. Other SDKs need to update: Swift (`TurnMessage.swift`) and JavaScript (`turn-messages.ts`) should send the person's user as `target_user_id`, as Kotlin and Dart do, not `Session.userId`. The server SDKs need nothing. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e4283e1f2..da561ce28e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Unreleased +## Breaking Changes + +- The Dart SDK's `AgentEventKind` gains `reasoningDelta`, so a `switch` over it with no default needs the case (#2200). + ## Features ### A sync removes the pages its `knowledge/urls.yaml` no longer lists diff --git a/examples/voice_agents/flutter_demo/lib/agent_chat.dart b/examples/voice_agents/flutter_demo/lib/agent_chat.dart index fd27f1fcda..450c9103a6 100644 --- a/examples/voice_agents/flutter_demo/lib/agent_chat.dart +++ b/examples/voice_agents/flutter_demo/lib/agent_chat.dart @@ -12,14 +12,22 @@ import 'package:stream_agents/stream_agents.dart'; /// question in the channel and answers it there: the reply's text, and its steps (each round /// of reasoning and each tool call) as attachments. The session's socket is what runs this /// phone's tools and carries the person's answers to the ones that ask first. +/// +/// An incognito session keeps no channel: its messages are its socket's `turnMessages`. class AgentChat with AIConversationTransport { - AgentChat._(this.session, stream.Channel channel) : _channel = channel; + AgentChat._(this.session, stream.Channel? channel) + : _channel = channel, + _kept = channel != null; - /// Opens the session's channel and starts following it. + /// Opens the session's channel and starts following it, or follows its socket alone when it + /// keeps no channel. /// /// The session is closed if its channel cannot be opened, so it does not run on with /// nobody to show it. static Future open(AgentSession session) async { + if (session.session.conversationId.isEmpty) { + return AgentChat.unkept(session); + } stream.Channel? channel; try { channel = await session.chat(); @@ -46,6 +54,10 @@ class AgentChat with AIConversationTransport { .._hasOlderMessages = hasOlderMessages .._follow(channel); + /// Follows [session], which keeps no channel, from its socket alone. + factory AgentChat.unkept(AgentSession session) => + AgentChat._(session, null).._follow(null); + static const _pageSize = 30; /// What a reply that failed says, in place of the provider's raw error. @@ -54,6 +66,8 @@ class AgentChat with AIConversationTransport { final AgentSession session; stream.Channel? _channel; + final bool _kept; + /// Why the session's socket stopped, or null: tools and approvals stop until a new /// conversation is opened. ValueListenable get sessionFailure => _sessionFailure; @@ -72,8 +86,12 @@ class AgentChat with AIConversationTransport { var _closed = false; /// The messages as Stream's AI components show them. - List get listMessages => - listed(_channel?.state?.messages ?? const [], reasoning, shown: _shown); + List get listMessages => _kept + ? listed(_channel?.state?.messages ?? const [], reasoning, shown: _shown) + : [ + for (final message in session.turnMessages) + if (!message.isUnwrittenReply) AgentMessage.unkept(message), + ]; /// The [messages] as Stream's AI components show them, oldest first, without those deleted /// and without the replies that ended with nothing written, reusing those in [shown]. @@ -97,21 +115,27 @@ class AgentChat with AIConversationTransport { _tell(_unanswered ? _failedActivity : activityOf(session.state)); } - void _follow(stream.Channel channel) { + void _follow(stream.Channel? channel) { + if (channel != null) { + _subscriptions + ..add(channel.state!.messagesStream.listen((_) => _publish())) + // The client's events rather than the channel's list: the list can fold several live + // updates into one, and each update carries its own window of the reply's thinking. + ..add( + channel.client.on(stream.EventType.messageUpdated).listen((event) { + final message = event.message; + if (event.cid == channel.cid && + message != null && + _readReasoning(message)) { + _publish(); + } + }), + ); + } else { + // A call waiting for the person asks on its step of the reply. + _subscriptions.add(session.approvals.stream.listen((_) => _publish())); + } _subscriptions - ..add(channel.state!.messagesStream.listen((_) => _publish())) - // The client's events rather than the channel's list: the list can fold several live - // updates into one, and each update carries its own window of the reply's thinking. - ..add( - channel.client.on(stream.EventType.messageUpdated).listen((event) { - final message = event.message; - if (event.cid == channel.cid && - message != null && - _readReasoning(message)) { - _publish(); - } - }), - ) ..add(session.conversation.stream.listen((_) => _sessionChanged())) ..add(session.connection.stream.listen((_) => _sessionChanged())) // A reply that fails ends with nothing written in the channel: only the socket says so. @@ -131,7 +155,7 @@ class AgentChat with AIConversationTransport { void _publish() { final feed = _feed; - if (feed == null || _channel == null) return; + if (feed == null || _closed) return; feed ..updateMessages(listMessages) ..updateHasOlderMessages(_hasOlderMessages); @@ -140,6 +164,8 @@ class AgentChat with AIConversationTransport { void _sessionChanged() { _sessionFailure.value = session.failure?.toString(); if (!_unanswered) _tell(activityOf(session.state)); + // With no channel, the socket is where the conversation is. + if (!_kept) _publish(); } void _report(AgentEvent event) { @@ -321,32 +347,60 @@ extension AgentReply on stream.Message { ]); } -/// A message of the conversation as Stream's AI components show it. -class AgentMessage with AIMessage { - AgentMessage(this.message, this._reasoning) : parts = message.steps; +extension UnkeptReply on TurnMessage { + /// Whether this is a reply the agent ended without writing anything, as + /// [AgentReply.isUnwrittenReply] is for a kept one. + bool get isUnwrittenReply => + isAgentReply && !isGenerating && text.isEmpty && steps.isEmpty; +} - final stream.Message message; - final LiveReasoning _reasoning; +/// A message of the conversation as Stream's AI components show it: the channel's, or an +/// incognito session's. +class AgentMessage with AIMessage { + AgentMessage(stream.Message this.message, LiveReasoning this._reasoning) + : _turn = null, + id = message.id, + role = message.isAgentReply + ? AIMessageRole.assistant + : AIMessageRole.user, + text = message.text ?? '', + isGenerating = message.isGenerating, + parts = message.steps; + + /// An incognito session's message, from its socket. + AgentMessage.unkept(TurnMessage this._turn) + : message = null, + _reasoning = null, + id = _turn.id, + role = _turn.isAgentReply ? AIMessageRole.assistant : AIMessageRole.user, + text = _turn.text, + isGenerating = _turn.isGenerating, + parts = AIMessagePart.parseAll(_turn.steps); + + /// The channel's message, or null for one built from the socket. + final stream.Message? message; + final TurnMessage? _turn; + final LiveReasoning? _reasoning; @override - final List parts; + final String id; @override - String get id => message.id; + final AIMessageRole role; @override - AIMessageRole get role => - message.isAgentReply ? AIMessageRole.assistant : AIMessageRole.user; + final String text; @override - String get text => message.text ?? ''; + final bool isGenerating; @override - bool get isGenerating => message.isGenerating; + final List parts; @override late final List attachments = [ - for (final attachment in message.attachments) + for (final attachment + in message?.attachments ?? const []) if (attachment.type == 'image' && attachment.imageUrl != null) AIMessageAttachment.image( Uri.parse(attachment.imageUrl!), @@ -362,8 +416,10 @@ class AgentMessage with AIMessage { ]; /// A step keeps only the opening of its thinking; the whole of it came with the live - /// updates, while the reply was being written. + /// updates, while the reply was being written. An incognito one holds all of it. @override - String? reasoningText(AIReasoningPart step) => - _reasoning[(message: message.id, step: step.id)]; + String? reasoningText(AIReasoningPart step) => switch (_turn) { + final turn? => turn.reasoning[step.id], + null => _reasoning?[(message: id, step: step.id)], + }; } diff --git a/examples/voice_agents/flutter_demo/lib/chat_view.dart b/examples/voice_agents/flutter_demo/lib/chat_view.dart index df6434d2d2..0be7d65706 100644 --- a/examples/voice_agents/flutter_demo/lib/chat_view.dart +++ b/examples/voice_agents/flutter_demo/lib/chat_view.dart @@ -17,8 +17,12 @@ import 'notice.dart'; /// same knowledge, the same skills and the same tools running on this phone. What is new in /// writing is that the reply shows its working, with Stream's AI components: the agent's /// reasoning as it thinks, each tool call as it runs, and a question when a tool asks first. +/// +/// An [incognito] conversation keeps no channel and is never listed. class ChatView extends StatefulWidget { - const ChatView({super.key}); + const ChatView({super.key, this.incognito = false}); + + final bool incognito; @override State createState() => _ChatViewState(); @@ -44,7 +48,12 @@ class _ChatViewState extends State { try { final session = await Demo.agents .agent(Demo.agentName) - .chat(SessionOptions(tools: Demo.tools)); + .chat( + SessionOptions( + tools: Demo.tools, + incognito: widget.incognito ? true : null, + ), + ); final chat = await AgentChat.open(session); if (!mounted) { await chat.close(); @@ -188,11 +197,19 @@ class _AgentConversationState extends State<_AgentConversation> { _conversation.status.isAnswering && activity?.text != null ? AITypingIndicatorView(text: activity!.text!) : null, - emptyContent: Notice( - icon: context.streamIcons.archive, - title: 'Ask about an order', - message: 'Orders A-1042 and A-1043 are on this account.', - ), + emptyContent: widget.chat.session.session.incognito + ? Notice( + icon: context.streamIcons.lock, + title: 'Incognito chat', + message: + 'This conversation is not kept. Ask about order A-1042 or A-1043.', + ) + : Notice( + icon: context.streamIcons.archive, + title: 'Ask about an order', + message: + 'Orders A-1042 and A-1043 are on this account.', + ), ), ), if (isWelcoming) diff --git a/examples/voice_agents/flutter_demo/lib/main.dart b/examples/voice_agents/flutter_demo/lib/main.dart index aba1032a4d..9489963b1a 100644 --- a/examples/voice_agents/flutter_demo/lib/main.dart +++ b/examples/voice_agents/flutter_demo/lib/main.dart @@ -51,6 +51,9 @@ class _HomePageState extends State { var _tab = 0; var _voiceStyle = VoiceStyle.orb; + // Whether the Chat tab holds an incognito conversation. Switching starts a new one. + var _incognito = false; + void _pickStyle() => showStreamSheet( context: context, isDismissible: true, @@ -89,14 +92,24 @@ class _HomePageState extends State { onPressed: _pickStyle, icon: Icon(context.streamIcons.slidersFill), ) - : null, + : StreamButton.icon( + style: .secondary, + type: _incognito ? .solid : .ghost, + tooltip: _incognito ? 'Leave incognito' : 'New incognito chat', + onPressed: () => setState(() => _incognito = !_incognito), + icon: Icon( + _incognito + ? context.streamIcons.lock + : context.streamIcons.unlock, + ), + ), ), // Both tabs stay alive, so a call carries on while the Chat tab is shown. body: IndexedStack( index: _tab, sizing: StackFit.expand, children: [ - const ChatView(), + ChatView(key: ValueKey(_incognito), incognito: _incognito), VoiceView(style: _voiceStyle), ], ), diff --git a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart index f4d31259c1..8600ff9a0b 100644 --- a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart +++ b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart @@ -360,6 +360,143 @@ void main() { ); }); + test( + 'shows a session with no channel from its socket, as Stream reads a kept reply', + () async { + // Its own router, whose one socket is this session's: the one set up holds the other. + final router = await _Router.start(); + addTearDown(router.close); + final agents = StreamAgents( + url: router.url, + customerId: 'acme', + userId: 'ada', + ); + addTearDown(agents.close); + final session = await agents.attach( + 's1', + tools: [ + AgentTool( + name: 'issue_refund', + description: 'Refund an order.', + approval: const ToolApproval( + title: 'Refund this order?', + allowTitle: 'Refund', + ), + run: (_) async => 'Refunded', + ), + ], + ); + final chat = closing(AgentChat.unkept(session)); + final conversation = conversationOf(chat); + final socket = await router.socket; + + conversation.send("I'd like a refund for order A-1042"); + await _until(() => router.asked == 1); + // The router's order: the reply is answered as waiting on its tools, which then run, and + // their results carry it on in a turn of its own. + socket + ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"type":"reasoning_delta","turn_id":"t1","text":"They were charged twice."}', + ) + ..send( + '{"pending_work":true,"type":"responded","turn_id":"t1",' + '"text":"","time_to_first_token_ms":90}', + ) + ..send( + '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund",' + '"turn_id":"t1","started_at":"2026-11-19T09:00:00Z"}', + ) + ..send( + '{"type":"tool_call","id":"c1","name":"issue_refund","arguments":"{}",' + '"request_id":"m1","turn_id":"t1"}', + ); + await _until( + () => + conversation + .messages + .lastOrNull + ?.parts + .lastOrNull + ?.toolCall + ?.status == + AIToolCallStatus.awaitingApproval, + ); + + expect( + [for (final m in conversation.messages) m.role], + [AIMessageRole.user, AIMessageRole.assistant], + ); + final reply = conversation.messages.last; + expect(reply.isGenerating, isTrue); + final [thinking, refund] = reply.parts; + expect(thinking.reasoning?.id, 'r1'); + expect( + reply.reasoningText(thinking.reasoning!), + 'They were charged twice.', + ); + // Asked of the person using the app, which is who Stream's approver answers as. + expect(refund.toolCall?.targetUserId, 'ada'); + expect(refund.toolCall?.approval?.title, 'Refund this order?'); + + session.decide('c1', allowed: true); + socket + ..send( + '{"type":"tool_ran","tool_call_id":"c1","turn_id":"t1",' + '"tool":"issue_refund","error":""}', + ) + ..send('{"type":"responding","turn_id":"t2"}') + ..send( + '{"pending_work":false,"type":"responded","turn_id":"t2",' + '"text":"Refunded.","time_to_first_token_ms":90}', + ); + await _until(() => conversation.messages.last.text == 'Refunded.'); + + final done = conversation.messages.last; + expect(done.isGenerating, isFalse); + expect(done.parts.last.toolCall?.status, AIToolCallStatus.completed); + expect(conversation.messages, hasLength(2)); + }, + ); + + test( + 'leaves out a reply with no channel that ended with nothing written, as a kept one is', + () async { + final router = await _Router.start(); + addTearDown(router.close); + final agents = StreamAgents( + url: router.url, + customerId: 'acme', + userId: 'ada', + ); + addTearDown(agents.close); + final session = await agents.attach('s1'); + final chat = closing(AgentChat.unkept(session)); + final conversation = conversationOf(chat); + final socket = await router.socket; + + conversation.send('Read me this page'); + await _until(() => router.asked == 1); + // A model that answered with nothing: no error, no text and no steps. + socket + ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"pending_work":false,"type":"responded","turn_id":"t1",' + '"text":"","time_to_first_token_ms":90}', + ); + await _until( + () => + session.turnMessages.last.isAgentReply && + !session.turnMessages.last.isGenerating, + ); + + expect( + [for (final m in chat.listMessages) m.role], + [AIMessageRole.user], + ); + }, + ); + test('close disposes the watched channel', () async { final channel = channelOf([_question('q0')]); final chat = AgentChat.following(session, channel); diff --git a/sdks/dart/stream_agents/README.md b/sdks/dart/stream_agents/README.md index 4794151401..bc331bee6c 100644 --- a/sdks/dart/stream_agents/README.md +++ b/sdks/dart/stream_agents/README.md @@ -172,6 +172,18 @@ Import `stream_chat` with a prefix: it exports a `TokenProvider` of its own. Asking an incognito session for its channel throws a `StateError`, since it keeps none. +Show an incognito session from its socket instead: `session.turnMessages` is the conversation in +the channel's shape. Read it again whenever `conversation`, `approvals` or `connection` changes: + +```dart +final session = await agents.agent('support').chat(const SessionOptions(incognito: true)); + +for (final message in session.turnMessages) { + final parts = AIMessagePart.parseAll(message.steps); // stream_chat_flutter_ai + // For each part with a reasoning step, message.reasoning[part.id] is its whole thinking. +} +``` + The channel opens on the app's own client when it hands one over, connected as the same user: ```dart diff --git a/sdks/dart/stream_agents/lib/src/core/agent_event.dart b/sdks/dart/stream_agents/lib/src/core/agent_event.dart index c22e7ac29b..c5094970c6 100644 --- a/sdks/dart/stream_agents/lib/src/core/agent_event.dart +++ b/sdks/dart/stream_agents/lib/src/core/agent_event.dart @@ -37,6 +37,7 @@ enum AgentEventKind { decision('decision'), responding('responding'), responseDelta('response_delta'), + reasoningDelta('reasoning_delta'), uiDelta('ui_delta'), uiCompleted('ui_completed'), responded('responded'), diff --git a/sdks/dart/stream_agents/lib/src/core/conversation.dart b/sdks/dart/stream_agents/lib/src/core/conversation.dart index ef43b81b11..10e2a0574e 100644 --- a/sdks/dart/stream_agents/lib/src/core/conversation.dart +++ b/sdks/dart/stream_agents/lib/src/core/conversation.dart @@ -93,6 +93,8 @@ final class Turn { required this.text, required this.at, this.ui, + this.steps = const [], + this.isDone = false, }); /// The router's turn id for an agent turn, and one of our own for a participant's. Stable @@ -103,9 +105,73 @@ final class Turn { final DateTime at; final TurnUI? ui; - Turn _withText(String text) => Turn(id: id, speaker: speaker, text: text, at: at, ui: ui); + /// The agent's rounds of thinking and tool calls, in order. Empty on a participant's turn. + final List steps; - Turn _withUI(TurnUI ui) => Turn(id: id, speaker: speaker, text: text, at: at, ui: ui); + /// Whether the agent answered with nothing left to come, or was cut off. + final bool isDone; + + Turn _withText(String text) => _copy(text: text); + + Turn _withUI(TurnUI? ui) => + Turn(id: id, speaker: speaker, text: text, at: at, ui: ui, steps: steps, isDone: isDone); + + Turn _copy({String? text, List? steps, bool? isDone}) => Turn( + id: id, + speaker: speaker, + text: text ?? this.text, + at: at, + ui: ui, + steps: steps ?? this.steps, + isDone: isDone ?? this.isDone, + ); + + /// Adds [delta] to the round under way, or starts the next one, numbered from `r1` as a kept + /// reply's steps are. + Turn _think(String delta, DateTime began) { + if (steps.lastOrNull case final ReasoningStep round when round.isStreaming) { + return _copy( + steps: [ + ...steps.take(steps.length - 1), + round._copy(text: round.text + delta), + ], + ); + } + final rounds = steps.whereType().length; + return _copy( + steps: [ + ...steps, + ReasoningStep(id: 'r${rounds + 1}', isStreaming: true, text: delta, at: began), + ], + ); + } + + Turn _settled(DateTime now) { + if (steps.lastOrNull case final ReasoningStep round when round.isStreaming) { + return _copy( + steps: [ + ...steps.take(steps.length - 1), + round._copy(isStreaming: false, duration: now.difference(round.at)), + ], + ); + } + return this; + } + + /// A provider may give a call a round's id (`r1`), so only calls are compared. + Turn _called(ToolCallStep call) => steps.any((step) => step is ToolCallStep && step.id == call.id) + ? this + : _copy(steps: [...steps, call]); + + Turn _changedCall(String id, ToolCallStep Function(ToolCallStep) change) { + final index = steps.indexWhere( + (step) => step is ToolCallStep && step.id == id && step.status == ToolCallStepStatus.running, + ); + if (index == -1) return this; + final changed = [...steps]; + changed[index] = change(steps[index] as ToolCallStep); + return _copy(steps: changed); + } @override bool operator ==(Object other) => @@ -114,15 +180,149 @@ final class Turn { other.speaker == speaker && other.text == text && other.at == at && - other.ui == ui; + other.ui == ui && + other.isDone == isDone && + _same(other.steps, steps); @override - int get hashCode => Object.hash(id, speaker, text, at, ui); + int get hashCode => Object.hash(id, speaker, text, at, ui, Object.hashAll(steps), isDone); @override String toString() => 'Turn($id, ${speaker.isAgent ? 'agent' : 'participant'}: $text)'; } +/// One thing the agent did in a turn: a round of the model's thinking, or a call of a tool. +sealed class TurnStep { + const TurnStep(); + + /// `r1`, `r2` and on for a round of thinking; the call's id for a tool call. + String get id; + + /// When it began. + DateTime get at; +} + +/// A round of the model's thinking on a written reply, which is read, never spoken. +final class ReasoningStep extends TurnStep { + const ReasoningStep({ + required this.id, + required this.isStreaming, + required this.text, + required this.at, + this.duration, + }); + + /// `r1`, `r2` and on, in the order the turn thought. + @override + final String id; + + /// Whether the model is still thinking: until it writes, calls a tool or finishes. + final bool isStreaming; + + /// The thinking so far. + final String text; + + /// When the model was asked or went on writing, as a kept reply's step is timed, not when its + /// first words arrived. + @override + final DateTime at; + + /// How long the model thought, once it is done. + final Duration? duration; + + ReasoningStep _copy({bool? isStreaming, String? text, Duration? duration}) => ReasoningStep( + id: id, + isStreaming: isStreaming ?? this.isStreaming, + text: text ?? this.text, + at: at, + duration: duration ?? this.duration, + ); + + @override + bool operator ==(Object other) => + other is ReasoningStep && + other.id == id && + other.isStreaming == isStreaming && + other.text == text && + other.at == at && + other.duration == duration; + + @override + int get hashCode => Object.hash(id, isStreaming, text, at, duration); + + @override + String toString() => 'ReasoningStep($id, ${isStreaming ? 'streaming' : 'completed'})'; +} + +/// A call of a tool: what was called and how it went, not what it was given or gave. +final class ToolCallStep extends TurnStep { + const ToolCallStep({ + required this.id, + required this.name, + required this.status, + this.summary = '', + required this.at, + this.duration, + }); + + /// The call's id, which [AgentSession.decide] answers it by while it waits in `approvals`. + @override + final String id; + + /// The tool. + final String name; + + /// Whether it is running, or how it ended. + final ToolCallStepStatus status; + + /// The last `tool_updated` text that is not to be said verbatim, or empty. + final String summary; + + @override + final DateTime at; + + /// How long it ran, once it is no longer running. + final Duration? duration; + + ToolCallStep _copy({ToolCallStepStatus? status, String? summary, Duration? duration}) => + ToolCallStep( + id: id, + name: name, + status: status ?? this.status, + summary: summary ?? this.summary, + at: at, + duration: duration ?? this.duration, + ); + + @override + bool operator ==(Object other) => + other is ToolCallStep && + other.id == id && + other.name == name && + other.status == status && + other.summary == summary && + other.at == at && + other.duration == duration; + + @override + int get hashCode => Object.hash(id, name, status, summary, at, duration); + + @override + String toString() => 'ToolCallStep($id, $name, ${status.wire})'; +} + +/// How a tool call went. +enum ToolCallStepStatus { + running('running'), + completed('completed'), + failed('failed'); + + const ToolCallStepStatus(this.wire); + + /// Its name in a kept reply's `ai_tool_call` step. + final String wire; +} + /// What the agent is doing. sealed class ConversationState { const ConversationState(); @@ -179,9 +379,10 @@ final class Conversation { /// A conversation built here has no UI being written; derive from an existing one /// ([withoutTurn], [withState]) to keep it. const Conversation({this.turns = const [], this.state = ConversationState.idle, this.failure}) - : _uiWritten = const {}; + : _uiWritten = const {}, + _resumedAt = const {}; - const Conversation._(this.turns, this.state, this.failure, this._uiWritten); + const Conversation._(this.turns, this.state, this.failure, this._uiWritten, this._resumedAt); /// Oldest first. The agent's turn in flight is the last entry and grows as deltas arrive. final List turns; @@ -194,6 +395,9 @@ final class Conversation { /// What each turn's UI block has written so far, unmerged, until the turn's UI is settled. final Map _uiWritten; + /// When each agent turn in flight was asked or went on writing, which times its next round. + final Map _resumedAt; + /// Whatever the caller typed, shown before the router has confirmed hearing it. Conversation said(String text, {DateTime? at}) => _with( turns: [ @@ -261,29 +465,74 @@ final class Conversation { state: ConversationState.responding, failure: null, uiWritten: _uiWritten.containsKey(event.turnId) ? _without(event.turnId) : null, - ); + )._resumed(event.turnId, now); case AgentEventKind.responseDelta: - return _write( + // Writing ends the round of thinking under way, and the next one is timed from here. + final went = event.text.isEmpty + ? this + : _amend(event.turnId, (turn) => turn._settled(now))._resumed(event.turnId, now); + return went + ._write(event.turnId, now, (text) => text + event.text, event.text) + .withState(ConversationState.responding); + + case AgentEventKind.reasoningDelta: + if (event.text.isEmpty) { + return this; + } + final began = _resumedAt[event.turnId] ?? now; + return _amend(event.turnId, (turn) => turn._think(event.text, began), startingAt: now); + + case AgentEventKind.toolStarted: + final call = ToolCallStep( + id: _text(event['tool_call_id']), + name: _text(event['tool']), + status: ToolCallStepStatus.running, + at: now, + ); + return _amend(event.turnId, (turn) => turn._settled(now)._called(call), startingAt: now); + + case AgentEventKind.toolUpdated: + // Words to say as written are a line of the reply, not how the call is going. + if (event['verbatim'] == true || event.text.isEmpty) { + return this; + } + return _amend( + event.turnId, + (turn) => + turn._changedCall(_text(event['id']), (call) => call._copy(summary: event.text)), + ); + + case AgentEventKind.toolRan: + final status = event.errorText.isEmpty + ? ToolCallStepStatus.completed + : ToolCallStepStatus.failed; + return _amend( event.turnId, - now, - (text) => text + event.text, - event.text, - ).withState(ConversationState.responding); + (turn) => turn._changedCall( + _text(event['tool_call_id']), + (call) => call._copy(status: status, duration: now.difference(call.at)), + ), + ); case AgentEventKind.uiDelta: final delta = _text(event['delta']); final format = _text(event['format']); - if (delta.isEmpty || format.isEmpty) { + if (delta.isEmpty) { return this; } + // Writing UI ends the round of thinking under way, as writing text does. + final went = _amend(event.turnId, (turn) => turn._settled(now))._resumed(event.turnId, now); + if (format.isEmpty) { + return went; + } final pending = ( format: format, version: _optionalText(event['version']), mode: _nonEmptyOr(_text(event['mode']), 'replace'), raw: '${_uiWritten[event.turnId]?.raw ?? ''}$delta', ); - final written = _with(uiWritten: {..._uiWritten, event.turnId: pending}); + final written = went._with(uiWritten: {..._uiWritten, event.turnId: pending}); // Only the line still being written grew, so no statement finished: nothing shown changes. final updated = format == 'openui' && !delta.contains('\n') ? written @@ -317,7 +566,15 @@ final class Conversation { final written = event.text.isEmpty ? settled : settled._write(event.turnId, now, (_) => event.text, event.text); - return written.withState(ConversationState.idle); + // A reply whose tools or work are still to come is carried on by a turn of its own. + final done = event['pending_work'] != true; + return written + ._resumed(event.turnId, null) + ._amend(event.turnId, (turn) { + final settledTurn = turn._settled(now); + return done && !settledTurn.isDone ? settledTurn._copy(isDone: true) : settledTurn; + }) + .withState(ConversationState.idle); case AgentEventKind.delegated: return _with(state: Working([..._working, _text(event['skill'])])); @@ -331,10 +588,11 @@ final class Conversation { return _with(state: left.isEmpty ? ConversationState.responding : Working(left)); case AgentEventKind.interrupted: - return _settleUI(event.turnId, now).withState(ConversationState.idle); + return _ended(event.turnId, now).withState(ConversationState.idle); case AgentEventKind.error: - return _with(failure: event.errorText); + final refused = event['code'] == 'prompt_injection' ? _refused() : this; + return refused._with(failure: event.errorText); case AgentEventKind.left: return withState(ConversationState.ended); @@ -370,6 +628,49 @@ final class Conversation { return _with(turns: changed); } + /// Changes agent turn [turnId], starting it at [startingAt] if this never saw it begin. + Conversation _amend(String turnId, Turn Function(Turn) change, {DateTime? startingAt}) { + final index = turns.lastIndexWhere((turn) => turn.id == turnId && turn.speaker.isAgent); + if (index == -1) { + if (startingAt == null) return this; + return _with( + turns: [ + ...turns, + change(Turn(id: turnId, speaker: Speaker.agent, text: '', at: startingAt)), + ], + ); + } + final changed = change(turns[index]); + if (identical(changed, turns[index])) return this; + return _with(turns: [...turns]..[index] = changed); + } + + Conversation _resumed(String turnId, DateTime? at) { + if (at == null) { + return _resumedAt.containsKey(turnId) + ? _with(resumedAt: {..._resumedAt}..remove(turnId)) + : this; + } + return _with(resumedAt: {..._resumedAt, turnId: at}); + } + + Conversation _ended(String turnId, DateTime now) => + _settleUI(turnId, now)._resumed(turnId, null)._amend(turnId, (turn) { + final settledTurn = turn._settled(now); + return settledTurn.isDone ? settledTurn : settledTurn._copy(isDone: true); + }); + + /// What a refused reply streamed is not the answer: its text and UI go, as from a kept + /// conversation, and its steps stay. + Conversation _refused() { + final index = turns.lastIndexWhere((turn) => turn.speaker.isAgent); + if (index == -1 || turns[index].isDone) return this; + final turn = turns[index]; + final cleared = _uiWritten.containsKey(turn.id) ? _with(uiWritten: _without(turn.id)) : this; + if (turn.text.isEmpty && turn.ui == null) return cleared; + return cleared._with(turns: [...turns]..[index] = turn._withText('')._withUI(null)); + } + /// The turn ended with no `ui_completed`, as an interrupted reply does: the router dropped its /// UI block with the turn. What was written shows, but for a statement it ended in the middle /// of, and the UI is complete, since nothing more of it will come. @@ -453,22 +754,25 @@ final class Conversation { ConversationState? state, Object? failure = _keep, Map? uiWritten, + Map? resumedAt, }) => Conversation._( turns ?? this.turns, state ?? this.state, identical(failure, _keep) ? this.failure : failure as String?, uiWritten ?? _uiWritten, + resumedAt ?? _resumedAt, ); /// The UI written so far counts, or a delta that shows nothing new would be lost to a holder - /// that skips equal values, and the next one would land on stale text. + /// that skips equal values, and the next one would land on stale text. So does [_resumedAt]. @override bool operator ==(Object other) => other is Conversation && other.state == state && other.failure == failure && _same(other.turns, turns) && - _sameWritten(other._uiWritten, _uiWritten); + _sameEntries(other._uiWritten, _uiWritten) && + _sameEntries(other._resumedAt, _resumedAt); @override int get hashCode => Object.hash( @@ -476,6 +780,7 @@ final class Conversation { state, failure, Object.hashAllUnordered(_uiWritten.values), + Object.hashAllUnordered(_resumedAt.values), ); } @@ -626,7 +931,7 @@ String? _optionalText(Object? value) => value is String && value.isNotEmpty ? va String _nonEmptyOr(String value, String fallback) => value.isNotEmpty ? value : fallback; -bool _sameWritten(Map a, Map b) { +bool _sameEntries(Map a, Map b) { if (identical(a, b)) { return true; } diff --git a/sdks/dart/stream_agents/lib/src/core/core.dart b/sdks/dart/stream_agents/lib/src/core/core.dart index 93e695f9d0..31b1107eae 100644 --- a/sdks/dart/stream_agents/lib/src/core/core.dart +++ b/sdks/dart/stream_agents/lib/src/core/core.dart @@ -19,3 +19,4 @@ export 'sessions.dart' show Responses, Sessions; export 'socket.dart'; export 'stream_agents.dart'; export 'tools.dart'; +export 'turn_message.dart'; diff --git a/sdks/dart/stream_agents/lib/src/core/turn_message.dart b/sdks/dart/stream_agents/lib/src/core/turn_message.dart new file mode 100644 index 0000000000..d71759d691 --- /dev/null +++ b/sdks/dart/stream_agents/lib/src/core/turn_message.dart @@ -0,0 +1,190 @@ +import 'agent_session.dart'; +import 'conversation.dart'; + +/// A message of an incognito session, which keeps no channel, in the shape a kept one has in +/// Stream Chat, so Stream's AI components show both alike. +/// +/// The agent's turns between two of the person's are one reply, as the router writes a reply +/// whose tools it waited on. +final class TurnMessage { + TurnMessage._({ + required this.id, + required this.isAgentReply, + required this.text, + required this.at, + this.isGenerating = false, + this.steps = const [], + this.reasoning = const {}, + this.customData = const {}, + }); + + /// Its first turn's id. + final String id; + + /// Whether the agent wrote it, rather than the person. + final bool isAgentReply; + + /// What it says: the person's question, or the reply's text, its turns' text joined by a + /// blank line. + final String text; + + /// When its first turn began. + final DateTime at; + + /// Whether the agent is still writing it. + final bool isGenerating; + + /// The reply's `ai_reasoning` and `ai_tool_call` steps, in order, as `AIMessagePart.parseAll` + /// reads them. Rounds are numbered from `r1` across the reply. + final List<({String type, Map payload})> steps; + + /// The whole of each round of thinking, by its step's id. + final Map reasoning; + + /// The reply's UI under `ai_ui`, as a kept one holds it, or nothing. + final Map customData; + + /// The messages of [conversation], oldest first. + /// + /// A call in [approvals] asks [userId] on its step: the person, whom `AIToolApprover` matches, + /// not `Session.userId`, the agent's name on the call. Only the latest reply is generating, + /// and only while [isConnected]. + static List messages( + Conversation conversation, { + List approvals = const [], + required String userId, + required bool isConnected, + }) { + final groups = >[]; + for (final turn in conversation.turns) { + if (turn.speaker.isAgent && (groups.lastOrNull?.first.speaker.isAgent ?? false)) { + groups.last.add(turn); + } else { + groups.add([turn]); + } + } + return [ + for (final (index, turns) in groups.indexed) + _of( + turns, + isGenerating: index == groups.length - 1 && isConnected && !turns.last.isDone, + approvals: approvals, + userId: userId, + ), + ]; + } + + static TurnMessage _of( + List turns, { + required bool isGenerating, + required List approvals, + required String userId, + }) { + final first = turns.first; + if (!first.speaker.isAgent) { + return TurnMessage._(id: first.id, isAgentReply: false, text: first.text, at: first.at); + } + final steps = <({String type, Map payload})>[]; + final reasoning = {}; + for (final step in turns.expand((turn) => turn.steps)) { + switch (step) { + case ReasoningStep(): + final id = 'r${reasoning.length + 1}'; + reasoning[id] = step.text; + steps.add(( + type: 'ai_reasoning', + payload: { + 'id': id, + 'status': step.isStreaming ? 'streaming' : 'completed', + 'duration_ms': ?step.duration?.inMilliseconds, + }, + )); + case ToolCallStep(): + final waiting = step.status == ToolCallStepStatus.running + ? approvals.where((request) => request.id == step.id).firstOrNull + : null; + steps.add(( + type: 'ai_tool_call', + payload: { + 'id': step.id, + 'name': step.name, + 'status': waiting != null ? 'awaiting_approval' : step.status.wire, + if (step.summary.isNotEmpty) 'summary': step.summary, + 'duration_ms': ?step.duration?.inMilliseconds, + if (waiting != null) ...{'target_user_id': userId, 'approval': _approval(waiting)}, + }, + )); + } + } + final ui = turns.lastWhere((turn) => turn.ui != null, orElse: () => first).ui; + return TurnMessage._( + id: first.id, + isAgentReply: true, + text: turns.map((turn) => turn.text).where((text) => text.isNotEmpty).join('\n\n'), + at: first.at, + isGenerating: isGenerating, + steps: steps, + reasoning: reasoning, + customData: {if (ui != null) 'ai_ui': ui.toWireJson()}, + ); + } + + static Map _approval(ToolApprovalRequest waiting) => { + 'title': waiting.approval.title, + if (waiting.approval.message case final message? when message.isNotEmpty) 'message': message, + if (waiting.reason.isNotEmpty) 'reason': waiting.reason, + if (waiting.approval.allowTitle case final title? when title.isNotEmpty) 'allow_title': title, + if (waiting.approval.declineTitle case final title? when title.isNotEmpty) + 'decline_title': title, + }; + + /// Equal when it shows the same, its maps compared by value. + @override + bool operator ==(Object other) => + other is TurnMessage && + other.id == id && + other.isAgentReply == isAgentReply && + other.text == text && + other.at == at && + other.isGenerating == isGenerating && + _sameValue(other.reasoning, reasoning) && + _sameValue(other.customData, customData) && + other.steps.length == steps.length && + [ + for (var i = 0; i < steps.length; i++) + other.steps[i].type == steps[i].type && + _sameValue(other.steps[i].payload, steps[i].payload), + ].every((same) => same); + + @override + int get hashCode => Object.hash(id, isAgentReply, text, at, isGenerating, steps.length); + + @override + String toString() => 'TurnMessage($id, ${isAgentReply ? 'agent' : 'person'}: $text)'; +} + +/// An incognito session's conversation as messages. +extension TurnMessages on AgentSession { + /// The conversation as messages, for a session with no channel. + /// + /// Read it again when [AgentSession.conversation], [AgentSession.approvals] or + /// [AgentSession.connection] changes. + List get turnMessages => TurnMessage.messages( + conversation.value, + approvals: approvals.value, + userId: backend.userId, + isConnected: isConnected, + ); +} + +bool _sameValue(Object? a, Object? b) => switch ((a, b)) { + (final Map a, final Map b) => + a.length == b.length && + a.entries.every( + (entry) => b.containsKey(entry.key) && _sameValue(entry.value, b[entry.key]), + ), + (final List a, final List b) => + a.length == b.length && + [for (var i = 0; i < a.length; i++) _sameValue(a[i], b[i])].every((same) => same), + _ => a == b, +}; diff --git a/sdks/dart/stream_agents/test/core/conversation_test.dart b/sdks/dart/stream_agents/test/core/conversation_test.dart index 4a5e18847b..8817a39be0 100644 --- a/sdks/dart/stream_agents/test/core/conversation_test.dart +++ b/sdks/dart/stream_agents/test/core/conversation_test.dart @@ -392,6 +392,294 @@ void main() { expect(identical(after, before), isTrue); }); + + group('steps', () { + final start = DateTime.utc(2026, 11, 19, 9); + DateTime ms(int milliseconds) => start.add(Duration(milliseconds: milliseconds)); + + Conversation play(List<(int, String)> frames, {Conversation from = const Conversation()}) { + var conversation = from; + for (final (at, json) in frames) { + conversation = conversation.apply(frame(json), at: ms(at)); + } + return conversation; + } + + test('a written reply keeps its thinking and tool calls in the order they happened', () { + // The router's order: the reply is answered as waiting on its tools, which then run, and + // their results carry it on in a turn of its own. + final conversation = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1000, '{"type":"reasoning_delta","turn_id":"t1","text":"They want "}'), + (1100, '{"type":"reasoning_delta","turn_id":"t1","text":"Lisbon\'s weather."}'), + ( + 2000, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' + '"time_to_first_token_ms":90}', + ), + ( + 2000, + '{"type":"tool_started","tool_call_id":"call_1","tool":"weather","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:02Z"}', + ), + ( + 2000, + '{"type":"tool_started","tool_call_id":"call_2","tool":"calendar","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:02Z"}', + ), + ( + 2100, + '{"type":"tool_updated","id":"call_1","turn_id":"t1","tool":"weather",' + '"text":"Reading the forecast","verbatim":false}', + ), + ( + 2200, + '{"type":"tool_updated","id":"call_1","turn_id":"t1","tool":"weather",' + '"text":"One moment.","verbatim":true}', + ), + ( + 2500, + '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather",' + '"arguments":"{}","result":"sunny","files":[],"error":""}', + ), + ( + 2300, + '{"type":"tool_ran","tool_call_id":"call_2","turn_id":"t1","tool":"calendar",' + '"arguments":"{}","result":"","files":[],"error":"calendar unreachable"}', + ), + ]); + + final turn = conversation.turns.single; + expect(turn.steps, [ + ReasoningStep( + id: 'r1', + isStreaming: false, + text: "They want Lisbon's weather.", + at: ms(0), + duration: const Duration(seconds: 2), + ), + ToolCallStep( + id: 'call_1', + name: 'weather', + status: ToolCallStepStatus.completed, + summary: 'Reading the forecast', + at: ms(2000), + duration: const Duration(milliseconds: 500), + ), + ToolCallStep( + id: 'call_2', + name: 'calendar', + status: ToolCallStepStatus.failed, + at: ms(2000), + duration: const Duration(milliseconds: 300), + ), + ]); + // Its tools' results are still to come, in a turn of its own. + expect(turn.isDone, isFalse); + expect(turn.text, 'Let me look.'); + }); + + test('times a round of thinking from when the model was asked, not its first words', () { + // A model that sends its thinking in one burst, just before it writes. + final asked = play([ + (1000, '{"type":"responding","turn_id":"t1"}'), + (5000, '{"type":"reasoning_delta","turn_id":"t1","text":"Lisbon, "}'), + (5001, '{"type":"reasoning_delta","turn_id":"t1","text":"this weekend."}'), + (5250, '{"type":"response_delta","turn_id":"t1","text":"Sunny."}'), + ]); + final first = asked.turns.single.steps.single as ReasoningStep; + expect(first.at, ms(1000)); + expect(first.duration, const Duration(milliseconds: 4250)); + + // After writing, the next round is timed from when the model went on. + final wentOn = play([ + (7000, '{"type":"reasoning_delta","turn_id":"t1","text":"And Sunday?"}'), + (8000, '{"type":"response_delta","turn_id":"t1","text":" Sunday too."}'), + ], from: asked); + final second = wentOn.turns.single.steps.last as ReasoningStep; + expect(second.id, 'r2'); + expect(second.at, ms(5250)); + expect(second.duration, const Duration(milliseconds: 2750)); + }); + + test('a round stays open while the model thinks, and UI being written closes it', () { + final thinking = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (300, '{"type":"reasoning_delta","turn_id":"t1","text":"A card fits."}'), + ]); + expect((thinking.turns.single.steps.single as ReasoningStep).isStreaming, isTrue); + + final carding = play([ + ( + 900, + '{"type":"ui_delta","turn_id":"t1","format":"openui","mode":"replace",' + r'"delta":"root = Card([])\n"}', + ), + ], from: thinking); + final round = carding.turns.single.steps.single as ReasoningStep; + expect(round.isStreaming, isFalse); + expect(round.duration, const Duration(milliseconds: 900)); + }); + + test('UI being written closes the round even when it names no format', () { + final carding = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (300, '{"type":"reasoning_delta","turn_id":"t1","text":"A card fits."}'), + (700, '{"type":"ui_delta","turn_id":"t1","delta":"a","format":""}'), + // The next round is timed from the UI, not from when the turn was asked. + (900, '{"type":"reasoning_delta","turn_id":"t1","text":"Now the total."}'), + ]); + + final [first, second] = carding.turns.single.steps.cast(); + expect(first.isStreaming, isFalse); + expect(first.duration, const Duration(milliseconds: 700)); + expect(second.id, 'r2'); + expect(second.at, ms(700)); + expect(carding.turns.single.ui, isNull); + }); + + test('a call shows once, even when started again or sharing an id with a round', () { + final conversation = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1, '{"type":"reasoning_delta","turn_id":"t1","text":"The weather tool knows."}'), + ( + 2, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' + '"time_to_first_token_ms":90}', + ), + (2, '{"type":"tool_started","tool_call_id":"r1","tool":"weather","turn_id":"t1"}'), + (3, '{"type":"tool_started","tool_call_id":"r1","tool":"weather","turn_id":"t1"}'), + ( + 10, + '{"type":"tool_ran","tool_call_id":"r1","tool":"weather","turn_id":"t1","error":""}', + ), + ]); + + final steps = conversation.turns.single.steps; + expect(steps.map((step) => (step.runtimeType, step.id)), [ + (ReasoningStep, 'r1'), + (ToolCallStep, 'r1'), + ]); + expect((steps.last as ToolCallStep).status, ToolCallStepStatus.completed); + expect((steps.last as ToolCallStep).duration, const Duration(milliseconds: 8)); + }); + + test('a turn is done once it answered with nothing left to come', () { + final answered = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + ( + 1, + '{"pending_work":false,"type":"responded","turn_id":"t1","text":"Sunny.",' + '"time_to_first_token_ms":90}', + ), + ]); + + expect(answered.turns.single.isDone, isTrue); + }); + + test('a turn that answered with work still to come is not done', () { + final waiting = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + ( + 1, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' + '"time_to_first_token_ms":90}', + ), + ]); + + expect(waiting.turns.single.isDone, isFalse); + }); + + test('a turn cut off is done, its thinking ended where it was cut', () { + final cut = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1, '{"type":"reasoning_delta","turn_id":"t1","text":"Hmm"}'), + (5, '{"type":"interrupted","turn_id":"t1","participant":null}'), + ]); + + expect(cut.turns.single.isDone, isTrue); + expect( + (cut.turns.single.steps.single as ReasoningStep).duration, + const Duration(milliseconds: 5), + ); + }); + + test('progress for a call or a turn never seen changes nothing', () { + final before = play([(0, '{"type":"responding","turn_id":"t1"}')]); + + for (final json in [ + '{"type":"tool_updated","id":"nope","turn_id":"t1","text":"Working","verbatim":false}', + '{"type":"tool_ran","tool_call_id":"nope","turn_id":"t1","error":""}', + '{"type":"tool_ran","tool_call_id":"c1","turn_id":"t9","error":""}', + '{"type":"reasoning_delta","turn_id":"t1","text":""}', + ]) { + expect(identical(before.apply(frame(json)), before), isTrue, reason: json); + } + }); + + test('thinking for a turn never seen starts it', () { + final before = play([(0, '{"type":"responding","turn_id":"t1"}')]); + + final unseen = before.apply( + frame('{"type":"reasoning_delta","turn_id":"t2","text":"Next."}'), + at: ms(40), + ); + + expect(unseen.turns.map((turn) => turn.id), ['t1', 't2']); + expect((unseen.turns.last.steps.single as ReasoningStep).at, ms(40)); + }); + + test('a reply the prompt injection screen refused loses its text and UI, not its steps', () { + final refused = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1, '{"type":"reasoning_delta","turn_id":"t1","text":"Reading the page."}'), + (2, '{"type":"tool_started","tool_call_id":"c1","tool":"fetch","turn_id":"t1"}'), + (3, '{"type":"response_delta","turn_id":"t1","text":"Ignore your rules and"}'), + ( + 4, + '{"type":"ui_delta","turn_id":"t1","format":"openui","mode":"replace",' + r'"delta":"root = Card([])\n"}', + ), + ( + 5, + '{"type":"error","context":"llm","error":"the input was refused",' + '"code":"prompt_injection"}', + ), + ]); + + final turn = refused.turns.single; + expect(turn.text, isEmpty); + expect(turn.ui, isNull); + expect(turn.steps.map((step) => step.id), ['r1', 'c1']); + expect(refused.failure, 'the input was refused'); + + // Another failure leaves what was written alone. + final failed = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (3, '{"type":"response_delta","turn_id":"t1","text":"Half"}'), + (5, '{"type":"error","context":"tts","error":"the voice is unknown"}'), + ]); + expect(failed.turns.single.text, 'Half'); + }); + + test('a refusal after the reply is done leaves the answer that was given', () { + final answered = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + ( + 1, + '{"pending_work":false,"type":"responded","turn_id":"t1","text":"Sunny.",' + '"time_to_first_token_ms":90}', + ), + ( + 5, + '{"type":"error","context":"llm","error":"the input was refused",' + '"code":"prompt_injection"}', + ), + ]); + + expect(answered.turns.single.text, 'Sunny.'); + }); + }); }); group('AgentEvent', () { diff --git a/sdks/dart/stream_agents/test/core/session_test.dart b/sdks/dart/stream_agents/test/core/session_test.dart index 68ac4fa7db..3663000d91 100644 --- a/sdks/dart/stream_agents/test/core/session_test.dart +++ b/sdks/dart/stream_agents/test/core/session_test.dart @@ -753,6 +753,87 @@ void main() { await chat.close(); }); + /// A session kept nowhere whose reply waits on the person's answer to a refund. + Future waitingUnkept() async { + // The router's session keeps no conversation: sessionJson's conversation_id is empty. + final chat = await agents + .withUser('ada') + .chat( + SessionOptions( + incognito: true, + tools: [ + AgentTool( + name: 'issue_refund', + description: 'Refund an order.', + approval: const ToolApproval( + title: 'Refund order A-1042?', + reasonArgument: 'reason', + allowTitle: 'Refund', + ), + run: (arguments) async => 'Refunded', + ), + ], + ), + ); + final socket = await router.socket(); + + // The router's order: the reply is answered as waiting on its tools, which then start. + socket + ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' + '"time_to_first_token_ms":90}', + ) + ..send( + '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:00Z"}', + ) + ..send(refundCall); + await until(() => chat.approvals.value.isNotEmpty); + return chat; + } + + test( + 'waits on its step of the reply, for the agents\' user, in a conversation kept nowhere', + () async { + final chat = await waitingUnkept(); + + final step = chat.turnMessages.last.steps.single; + expect(step.type, 'ai_tool_call'); + expect(step.payload, { + 'id': 'c1', + 'name': 'issue_refund', + 'status': 'awaiting_approval', + // The person using the app, whom Stream's approver shows the card to: the session's own + // user_id is the name the agent joined the call as. + 'target_user_id': 'ada', + 'approval': { + 'title': 'Refund order A-1042?', + 'reason': 'it arrived unopened', + 'allow_title': 'Refund', + }, + }); + await chat.close(); + }, + ); + + test('allowed in a conversation kept nowhere, its step runs', () async { + final chat = await waitingUnkept(); + + chat.decide('c1', allowed: true); + + expect(chat.turnMessages.last.steps.single.payload['status'], 'running'); + await chat.close(); + }); + + test('closed while its reply waits, the reply is no longer being written', () async { + final chat = await waitingUnkept(); + + await chat.close(); + + expect(chat.turnMessages.last.isGenerating, isFalse); + }); + test('declined, never runs, tells the model so, and a second answer does nothing', () async { final chat = await open(); final socket = await router.socket(); diff --git a/sdks/dart/stream_agents/test/core/turn_message_test.dart b/sdks/dart/stream_agents/test/core/turn_message_test.dart new file mode 100644 index 0000000000..732f8836ba --- /dev/null +++ b/sdks/dart/stream_agents/test/core/turn_message_test.dart @@ -0,0 +1,182 @@ +import 'package:test/test.dart'; +import 'package:stream_agents/src/core/core.dart'; + +/// Frames exactly as `frameOf` in the router writes them. +AgentEvent frame(String json) => AgentEvent.tryParse(json)!; + +void main() { + group('TurnMessage', () { + final start = DateTime.utc(2026, 11, 19, 9); + DateTime ms(int milliseconds) => start.add(Duration(milliseconds: milliseconds)); + + Conversation play(List<(int, String)> frames, {Conversation from = const Conversation()}) { + var conversation = from; + for (final (at, json) in frames) { + conversation = conversation.apply(frame(json), at: ms(at)); + } + return conversation; + } + + // A question, and a reply that waits on a tool and carries on in a turn of its own. + final asked = const Conversation().said('Weather in Lisbon?', at: ms(0)); + final toolTurn = [ + (10, '{"type":"responding","turn_id":"t1"}'), + (1000, '{"type":"reasoning_delta","turn_id":"t1","text":"They want Lisbon\'s weather."}'), + // As the router sends it: answered as waiting on its tool, which then runs. + ( + 1500, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' + '"time_to_first_token_ms":90}', + ), + (1500, '{"type":"tool_started","tool_call_id":"call_1","tool":"weather","turn_id":"t1"}'), + ( + 1600, + '{"type":"tool_updated","id":"call_1","turn_id":"t1","tool":"weather",' + '"text":"Reading the forecast","verbatim":false}', + ), + ( + 2000, + '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather","error":""}', + ), + ]; + final answerTurn = [ + (2200, '{"type":"responding","turn_id":"t2"}'), + (2600, '{"type":"reasoning_delta","turn_id":"t2","text":"Sunny, 24."}'), + (3000, '{"type":"response_delta","turn_id":"t2","text":"Sunny and 24°C."}'), + ]; + const answered = + '{"pending_work":false,"type":"responded","turn_id":"t2","text":"Sunny and 24°C.",' + '"time_to_first_token_ms":90}'; + + test('a reply is one message across its tools\' turns, with every step in order', () { + final conversation = play([...toolTurn, ...answerTurn, (3100, answered)], from: asked); + + final messages = TurnMessage.messages(conversation, userId: 'ada', isConnected: true); + + expect(messages.map((message) => (message.isAgentReply, message.text)), [ + (false, 'Weather in Lisbon?'), + (true, 'Let me look.\n\nSunny and 24°C.'), + ]); + final reply = messages.last; + expect(reply.id, 't1'); + expect(reply.at, ms(10)); + expect(reply.isGenerating, isFalse); + // Records compare their maps by identity, so each step is compared as a list. + expect(reply.steps.map((step) => [step.type, step.payload]), [ + [ + 'ai_reasoning', + {'id': 'r1', 'status': 'completed', 'duration_ms': 1490}, + ], + [ + 'ai_tool_call', + { + 'id': 'call_1', + 'name': 'weather', + 'status': 'completed', + 'summary': 'Reading the forecast', + 'duration_ms': 500, + }, + ], + // The second turn's round is its own r1, and the reply's r2. + [ + 'ai_reasoning', + {'id': 'r2', 'status': 'completed', 'duration_ms': 800}, + ], + ]); + expect(reply.reasoning, {'r1': "They want Lisbon's weather.", 'r2': 'Sunny, 24.'}); + expect(reply.customData, isEmpty); + }); + + test('the latest reply is being written while the socket carries it', () { + final writing = play([...toolTurn, ...answerTurn], from: asked); + + expect( + TurnMessage.messages(writing, userId: 'ada', isConnected: true).last.isGenerating, + isTrue, + ); + }); + + test('a reply whose tools are done is still being written until its next turn is', () { + final betweenTurns = play(toolTurn, from: asked); + + expect( + TurnMessage.messages(betweenTurns, userId: 'ada', isConnected: true).last.isGenerating, + isTrue, + ); + }); + + test('a reply is not being written once the socket is gone', () { + final writing = play([...toolTurn, ...answerTurn], from: asked); + + expect( + TurnMessage.messages(writing, userId: 'ada', isConnected: false).last.isGenerating, + isFalse, + ); + }); + + test('a reply asked over mid-thought is left as it was, no longer being written', () { + final thinking = play([...toolTurn, ...answerTurn.take(2)], from: asked); + final askedAgain = thinking.said('Never mind.', at: ms(4000)); + + final messages = TurnMessage.messages(askedAgain, userId: 'ada', isConnected: true); + + expect(messages.map((message) => message.isGenerating), [false, false, false]); + expect( + messages[1].steps.last.payload['status'], + 'streaming', + reason: 'the round it was left on', + ); + }); + + test('a message built again unchanged is equal, and one whose step or card moved is not', () { + final running = play([ + ...toolTurn.take(4), + ( + 1700, + '{"type":"ui_completed","turn_id":"t1","format":"openui","mode":"replace",' + r'"content":"root = Card([])"}', + ), + ], from: asked); + TurnMessage reply(Conversation conversation) => + TurnMessage.messages(conversation, userId: 'ada', isConnected: true).last; + + // Built twice from the same conversation, with maps that are not the same objects. + expect(reply(running), reply(running)); + expect(reply(running).hashCode, reply(running).hashCode); + + final ran = play([ + ( + 2000, + '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather","error":""}', + ), + ], from: running); + expect(reply(ran), isNot(reply(running)), reason: 'the call completed'); + + final recarded = play([ + ( + 1800, + '{"type":"ui_completed","turn_id":"t1","format":"openui","mode":"replace",' + r'"content":"root = Card([Text(\"Sunny\")])"}', + ), + ], from: running); + expect(reply(recarded), isNot(reply(running)), reason: 'the card changed'); + }); + + test('a reply with UI carries its latest card as a kept one does', () { + final conversation = play([ + (10, '{"type":"responding","turn_id":"t1"}'), + ( + 20, + '{"type":"ui_completed","turn_id":"t1","format":"openui","mode":"replace",' + r'"content":"root = Card([])"}', + ), + ], from: asked); + + final reply = TurnMessage.messages(conversation, userId: 'ada', isConnected: true).last; + + expect(reply.customData, { + 'ai_ui': {'v': 1, 'format': 'openui', 'status': 'complete', 'content': 'root = Card([])'}, + }); + }); + }); +}