Skip to content

Commit 3403e65

Browse files
authored
Fix: Add missing ChatMessage[] handler to ChatProtocolExecutor (microsoft#1337)
- Added ChatMessage[] handler to ConfigureRoutes to support array dispatch - Workflow runtime can dispatch messages as either List<ChatMessage> or ChatMessage[] - Added 10 comprehensive unit tests validating message routing behavior - Tests ensure functionality and protect against future refactoring (issue microsoft#782) - Updated code comments to reflect exact-type-matching requirement Fixes issue where raw WorkflowBuilder with AIAgent nodes failed to receive initial messages due to missing array type handler.
1 parent 3f86d42 commit 3403e65

2 files changed

Lines changed: 268 additions & 0 deletions

File tree

‎dotnet/src/Microsoft.Agents.AI.Workflows/ChatProtocolExecutor.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,10 @@ protected override RouteBuilder ConfigureRoutes(RouteBuilder routeBuilder)
3333
routeBuilder = routeBuilder.AddHandler<string>((message, _, __) => this._pendingMessages.Add(new(this._stringMessageChatRole.Value, message)));
3434
}
3535

36+
// Routing requires exact type matches. The runtime may dispatch either List<ChatMessage> or ChatMessage[].
3637
return routeBuilder.AddHandler<ChatMessage>((message, _, __) => this._pendingMessages.Add(message))
3738
.AddHandler<List<ChatMessage>>((messages, _, __) => this._pendingMessages.AddRange(messages))
39+
.AddHandler<ChatMessage[]>((messages, _, __) => this._pendingMessages.AddRange(messages))
3840
.AddHandler<TurnToken>(this.TakeTurnAsync);
3941
}
4042

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using System.Threading;
7+
using System.Threading.Tasks;
8+
using FluentAssertions;
9+
using Microsoft.Agents.AI.Workflows.Checkpointing;
10+
using Microsoft.Extensions.AI;
11+
12+
namespace Microsoft.Agents.AI.Workflows.UnitTests;
13+
14+
/// <summary>
15+
/// Tests for <see cref="ChatProtocolExecutor"/> to verify message routing behavior.
16+
/// </summary>
17+
public class ChatProtocolExecutorTests
18+
{
19+
private sealed class TestChatProtocolExecutor : ChatProtocolExecutor
20+
{
21+
public List<ChatMessage> ReceivedMessages { get; } = [];
22+
public int TurnCount { get; private set; }
23+
24+
public TestChatProtocolExecutor(string id = "test-executor", ChatProtocolExecutorOptions? options = null)
25+
: base(id, options)
26+
{
27+
}
28+
29+
protected override async ValueTask TakeTurnAsync(
30+
List<ChatMessage> messages,
31+
IWorkflowContext context,
32+
bool? emitEvents,
33+
CancellationToken cancellationToken = default)
34+
{
35+
this.ReceivedMessages.AddRange(messages);
36+
this.TurnCount++;
37+
38+
// Send messages back to context so they can be collected
39+
await context.SendMessageAsync(messages, cancellationToken: cancellationToken);
40+
}
41+
}
42+
43+
private sealed class TestWorkflowContext : IWorkflowContext
44+
{
45+
public List<object> SentMessages { get; } = [];
46+
47+
public ValueTask AddEventAsync(WorkflowEvent workflowEvent, CancellationToken cancellationToken = default) =>
48+
default;
49+
50+
public ValueTask YieldOutputAsync(object output, CancellationToken cancellationToken = default) =>
51+
default;
52+
53+
public ValueTask RequestHaltAsync() =>
54+
default;
55+
56+
public ValueTask QueueClearScopeAsync(string? scopeName = null, CancellationToken cancellationToken = default) =>
57+
default;
58+
59+
public ValueTask QueueStateUpdateAsync<T>(string key, T? value, string? scopeName = null, CancellationToken cancellationToken = default) =>
60+
default;
61+
62+
public ValueTask<T?> ReadStateAsync<T>(string key, string? scopeName = null, CancellationToken cancellationToken = default) =>
63+
default;
64+
65+
public ValueTask<HashSet<string>> ReadStateKeysAsync(string? scopeName = null, CancellationToken cancellationToken = default) =>
66+
default;
67+
68+
public ValueTask SendMessageAsync(object message, string? targetId = null, CancellationToken cancellationToken = default)
69+
{
70+
this.SentMessages.Add(message);
71+
return default;
72+
}
73+
74+
public IReadOnlyDictionary<string, string>? TraceContext => null;
75+
}
76+
77+
[Fact]
78+
public async Task ChatProtocolExecutor_Handles_ListOfChatMessagesAsync()
79+
{
80+
// Arrange
81+
var executor = new TestChatProtocolExecutor();
82+
var context = new TestWorkflowContext();
83+
84+
List<ChatMessage> messages =
85+
[
86+
new ChatMessage(ChatRole.User, "Hello"),
87+
new ChatMessage(ChatRole.User, "World")
88+
];
89+
90+
// Act - Send List<ChatMessage> via ExecuteAsync
91+
await executor.ExecuteAsync(messages, new TypeId(typeof(List<ChatMessage>)), context);
92+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
93+
94+
// Assert
95+
executor.ReceivedMessages.Should().HaveCount(2);
96+
executor.ReceivedMessages[0].Text.Should().Be("Hello");
97+
executor.ReceivedMessages[1].Text.Should().Be("World");
98+
executor.TurnCount.Should().Be(1);
99+
}
100+
101+
[Fact]
102+
public async Task ChatProtocolExecutor_Handles_ArrayOfChatMessagesAsync()
103+
{
104+
// Arrange
105+
var executor = new TestChatProtocolExecutor();
106+
var context = new TestWorkflowContext();
107+
108+
ChatMessage[] messages =
109+
[
110+
new ChatMessage(ChatRole.System, "System message"),
111+
new ChatMessage(ChatRole.User, "User query"),
112+
new ChatMessage(ChatRole.Assistant, "Agent reply")
113+
];
114+
115+
// Act - Send as ChatMessage[]
116+
await executor.ExecuteAsync(messages, new TypeId(typeof(ChatMessage[])), context);
117+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
118+
119+
// Assert
120+
executor.ReceivedMessages.Should().HaveCount(3);
121+
executor.ReceivedMessages[0].Role.Should().Be(ChatRole.System);
122+
executor.ReceivedMessages[1].Role.Should().Be(ChatRole.User);
123+
executor.ReceivedMessages[2].Role.Should().Be(ChatRole.Assistant);
124+
executor.TurnCount.Should().Be(1);
125+
}
126+
127+
[Fact]
128+
public async Task ChatProtocolExecutor_Handles_SingleChatMessageAsync()
129+
{
130+
// Arrange
131+
var executor = new TestChatProtocolExecutor();
132+
var context = new TestWorkflowContext();
133+
134+
var message = new ChatMessage(ChatRole.User, "Single message");
135+
136+
// Act - Send as single ChatMessage
137+
await executor.ExecuteAsync(message, new TypeId(typeof(ChatMessage)), context);
138+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
139+
140+
// Assert
141+
executor.ReceivedMessages.Should().HaveCount(1);
142+
executor.ReceivedMessages[0].Text.Should().Be("Single message");
143+
executor.TurnCount.Should().Be(1);
144+
}
145+
146+
[Fact]
147+
public async Task ChatProtocolExecutor_AccumulatesAndClearsMessagesPerTurnAsync()
148+
{
149+
var executor = new TestChatProtocolExecutor();
150+
var context = new TestWorkflowContext();
151+
152+
// Send multiple message batches before taking a turn
153+
await executor.ExecuteAsync(new ChatMessage(ChatRole.User, "Message 1"), new TypeId(typeof(ChatMessage)), context);
154+
await executor.ExecuteAsync(new List<ChatMessage>
155+
{
156+
new(ChatRole.User, "Message 2"),
157+
new(ChatRole.User, "Message 3")
158+
}, new TypeId(typeof(List<ChatMessage>)), context);
159+
await executor.ExecuteAsync(new ChatMessage[] { new(ChatRole.User, "Message 4") }, new TypeId(typeof(ChatMessage[])), context);
160+
161+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
162+
163+
executor.ReceivedMessages.Should().HaveCount(4);
164+
executor.ReceivedMessages.Select(m => m.Text).Should().Equal("Message 1", "Message 2", "Message 3", "Message 4");
165+
executor.TurnCount.Should().Be(1);
166+
167+
executor.ReceivedMessages.Clear();
168+
169+
// Second turn should process new messages only
170+
await executor.ExecuteAsync(new List<ChatMessage>
171+
{
172+
new(ChatRole.User, "Second batch")
173+
}, new TypeId(typeof(List<ChatMessage>)), context);
174+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
175+
176+
executor.ReceivedMessages.Should().HaveCount(1);
177+
executor.ReceivedMessages[0].Text.Should().Be("Second batch");
178+
executor.TurnCount.Should().Be(2);
179+
}
180+
181+
[Fact]
182+
public async Task ChatProtocolExecutor_WithStringRole_ConvertsStringToMessageAsync()
183+
{
184+
var executor = new TestChatProtocolExecutor(
185+
options: new ChatProtocolExecutorOptions
186+
{
187+
StringMessageChatRole = ChatRole.User
188+
});
189+
var context = new TestWorkflowContext();
190+
191+
await executor.ExecuteAsync("String message", new TypeId(typeof(string)), context);
192+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
193+
194+
executor.ReceivedMessages.Should().HaveCount(1);
195+
executor.ReceivedMessages[0].Role.Should().Be(ChatRole.User);
196+
executor.ReceivedMessages[0].Text.Should().Be("String message");
197+
}
198+
199+
[Fact]
200+
public async Task ChatProtocolExecutor_EmptyCollection_HandledCorrectlyAsync()
201+
{
202+
var executor = new TestChatProtocolExecutor();
203+
var context = new TestWorkflowContext();
204+
205+
await executor.ExecuteAsync(new List<ChatMessage>(), new TypeId(typeof(List<ChatMessage>)), context);
206+
await executor.ExecuteAsync(Array.Empty<ChatMessage>(), new TypeId(typeof(ChatMessage[])), context);
207+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
208+
209+
executor.ReceivedMessages.Should().BeEmpty();
210+
executor.TurnCount.Should().Be(1);
211+
}
212+
213+
[Theory]
214+
[InlineData(typeof(List<ChatMessage>))]
215+
[InlineData(typeof(ChatMessage[]))]
216+
public async Task ChatProtocolExecutor_RoutesCollectionTypesAsync(Type collectionType)
217+
{
218+
var executor = new TestChatProtocolExecutor();
219+
var context = new TestWorkflowContext();
220+
221+
var sourceMessages = new[] { new ChatMessage(ChatRole.User, "Test message") };
222+
object messagesToSend = collectionType == typeof(List<ChatMessage>) ? sourceMessages.ToList() : sourceMessages;
223+
224+
await executor.ExecuteAsync(messagesToSend, new TypeId(collectionType), context);
225+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
226+
227+
executor.ReceivedMessages.Should().HaveCount(1);
228+
executor.ReceivedMessages[0].Text.Should().Be("Test message");
229+
}
230+
231+
[Fact]
232+
public async Task ChatProtocolExecutor_MultipleTurns_EachTurnProcessesSeparatelyAsync()
233+
{
234+
var executor = new TestChatProtocolExecutor();
235+
var context = new TestWorkflowContext();
236+
237+
await executor.ExecuteAsync(new List<ChatMessage> { new(ChatRole.User, "Turn 1") }, new TypeId(typeof(List<ChatMessage>)), context);
238+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
239+
240+
executor.ReceivedMessages.Should().HaveCount(1);
241+
242+
await executor.ExecuteAsync(new ChatMessage(ChatRole.User, "Turn 2"), new TypeId(typeof(ChatMessage)), context);
243+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
244+
245+
executor.ReceivedMessages.Should().HaveCount(2);
246+
executor.ReceivedMessages[0].Text.Should().Be("Turn 1");
247+
executor.ReceivedMessages[1].Text.Should().Be("Turn 2");
248+
executor.TurnCount.Should().Be(2);
249+
}
250+
251+
[Fact]
252+
public async Task ChatProtocolExecutor_InitialWorkflowMessages_RoutedCorrectlyAsync()
253+
{
254+
var executor = new TestChatProtocolExecutor();
255+
var context = new TestWorkflowContext();
256+
257+
List<ChatMessage> initialMessages = [new ChatMessage(ChatRole.User, "Kick off the workflow")];
258+
259+
await executor.ExecuteAsync(initialMessages, new TypeId(typeof(List<ChatMessage>)), context);
260+
await executor.TakeTurnAsync(new TurnToken(emitEvents: false), context);
261+
262+
executor.ReceivedMessages.Should().NotBeEmpty();
263+
executor.ReceivedMessages.Should().HaveCount(1);
264+
executor.ReceivedMessages[0].Text.Should().Be("Kick off the workflow");
265+
}
266+
}

0 commit comments

Comments
 (0)