@@ -163,6 +163,42 @@ public async Task MultiTurnConversationPreservesAllMessagesInSessionAsync()
163163 secondResponse . Messages [ 0 ] . Text . Should ( ) . Be ( "Hello from fake agent!" ) ;
164164 }
165165
166+ [ Fact ]
167+ public async Task ChatClientConversationId_RestoresServerSessionAcrossRequestsAsync ( )
168+ {
169+ // Arrange
170+ await this . SetupTestServerAsync ( useStatefulMemoryAgent : true ) ;
171+ var chatClient = new AGUIChatClient ( this . _client ! , "" , null ) ;
172+ var chatOptions = new ChatOptions ( ) ;
173+
174+ // Act
175+ ChatResponse firstResponse = await chatClient . GetResponseAsync ( [ new ChatMessage ( ChatRole . User , "My name is Alice" ) ] , chatOptions ) ;
176+ chatOptions . ConversationId = firstResponse . ConversationId ;
177+ ChatResponse secondResponse = await chatClient . GetResponseAsync ( [ new ChatMessage ( ChatRole . User , "What is my name?" ) ] , chatOptions ) ;
178+
179+ // Assert
180+ firstResponse . ConversationId . Should ( ) . NotBeNullOrEmpty ( ) ;
181+ secondResponse . Text . Should ( ) . Contain ( "Alice" ) ;
182+ }
183+
184+ [ Fact ]
185+ public async Task AsAIAgentSession_RestoresServerSessionAcrossRunsAsync ( )
186+ {
187+ // Arrange
188+ await this . SetupTestServerAsync ( useStatefulMemoryAgent : true ) ;
189+ var chatClient = new AGUIChatClient ( this . _client ! , "" , null ) ;
190+ AIAgent agent = chatClient . AsAIAgent ( instructions : null , name : "assistant" , description : "Stateful assistant" , tools : [ ] ) ;
191+ AgentSession session = await agent . CreateSessionAsync ( ) ;
192+
193+ // Act
194+ AgentResponse firstResponse = await agent . RunAsync ( "My name is Alice" , session , new AgentRunOptions ( ) , CancellationToken . None ) ;
195+ AgentResponse secondResponse = await agent . RunAsync ( "What is my name?" , session , new AgentRunOptions ( ) , CancellationToken . None ) ;
196+
197+ // Assert
198+ firstResponse . Text . Should ( ) . Contain ( "Alice" ) ;
199+ secondResponse . Text . Should ( ) . Contain ( "Alice" ) ;
200+ }
201+
166202 [ Fact ]
167203 public async Task AgentSendsMultipleMessagesInOneTurnAsync ( )
168204 {
@@ -231,14 +267,18 @@ public async Task UserSendsMultipleMessagesAtOnceAsync()
231267 response . Messages [ 0 ] . Text . Should ( ) . Be ( "Hello from fake agent!" ) ;
232268 }
233269
234- private async Task SetupTestServerAsync ( bool useMultiMessageAgent = false )
270+ private async Task SetupTestServerAsync ( bool useMultiMessageAgent = false , bool useStatefulMemoryAgent = false )
235271 {
236272 WebApplicationBuilder builder = WebApplication . CreateBuilder ( ) ;
237273 builder . WebHost . UseTestServer ( ) ;
238274
239275 builder . Services . AddAGUI ( ) ;
240276
241- if ( useMultiMessageAgent )
277+ if ( useStatefulMemoryAgent )
278+ {
279+ builder . Services . AddSingleton < FakeStatefulMemoryAgent > ( ) ;
280+ }
281+ else if ( useMultiMessageAgent )
242282 {
243283 builder . Services . AddSingleton < FakeMultiMessageAgent > ( ) ;
244284 }
@@ -249,9 +289,11 @@ private async Task SetupTestServerAsync(bool useMultiMessageAgent = false)
249289
250290 this . _app = builder . Build ( ) ;
251291
252- AIAgent agent = useMultiMessageAgent
253- ? this . _app . Services . GetRequiredService < FakeMultiMessageAgent > ( )
254- : this . _app . Services . GetRequiredService < FakeChatClientAgent > ( ) ;
292+ AIAgent agent = useStatefulMemoryAgent
293+ ? this . _app . Services . GetRequiredService < FakeStatefulMemoryAgent > ( )
294+ : useMultiMessageAgent
295+ ? this . _app . Services . GetRequiredService < FakeMultiMessageAgent > ( )
296+ : this . _app . Services . GetRequiredService < FakeChatClientAgent > ( ) ;
255297
256298 this . _app . MapAGUI ( "/agent" , agent ) ;
257299
@@ -441,3 +483,98 @@ public FakeAgentSession(AgentSessionStateBag stateBag) : base(stateBag)
441483
442484 public override object ? GetService ( Type serviceType , object ? serviceKey = null ) => null ;
443485}
486+
487+ [ SuppressMessage ( "Performance" , "CA1812:Avoid uninstantiated internal classes" , Justification = "Instantiated via dependency injection" ) ]
488+ internal sealed class FakeStatefulMemoryAgent : AIAgent
489+ {
490+ private const string NameStateKey = "remembered-name" ;
491+
492+ protected override string ? IdCore => "fake-stateful-memory-agent" ;
493+
494+ public override string ? Description => "A fake agent that stores simple memory in the session" ;
495+
496+ protected override ValueTask < AgentSession > CreateSessionCoreAsync ( CancellationToken cancellationToken = default ) =>
497+ new ( new FakeAgentSession ( ) ) ;
498+
499+ protected override ValueTask < AgentSession > DeserializeSessionCoreAsync ( JsonElement serializedState , JsonSerializerOptions ? jsonSerializerOptions = null , CancellationToken cancellationToken = default ) =>
500+ new ( serializedState . Deserialize < FakeAgentSession > ( jsonSerializerOptions ) ! ) ;
501+
502+ protected override ValueTask < JsonElement > SerializeSessionCoreAsync ( AgentSession session , JsonSerializerOptions ? jsonSerializerOptions = null , CancellationToken cancellationToken = default )
503+ {
504+ if ( session is not FakeAgentSession typedSession )
505+ {
506+ throw new InvalidOperationException ( $ "The provided session type '{ session . GetType ( ) . Name } ' is not compatible with this agent. Only sessions of type '{ nameof ( FakeAgentSession ) } ' can be serialized by this agent.") ;
507+ }
508+
509+ return new ( JsonSerializer . SerializeToElement ( typedSession , jsonSerializerOptions ) ) ;
510+ }
511+
512+ protected override async Task < AgentResponse > RunCoreAsync (
513+ IEnumerable < ChatMessage > messages ,
514+ AgentSession ? session = null ,
515+ AgentRunOptions ? options = null ,
516+ CancellationToken cancellationToken = default )
517+ {
518+ List < AgentResponseUpdate > updates = [ ] ;
519+ await foreach ( AgentResponseUpdate update in this . RunStreamingAsync ( messages , session , options , cancellationToken ) . ConfigureAwait ( false ) )
520+ {
521+ updates . Add ( update ) ;
522+ }
523+
524+ return updates . ToAgentResponse ( ) ;
525+ }
526+
527+ protected override async IAsyncEnumerable < AgentResponseUpdate > RunCoreStreamingAsync (
528+ IEnumerable < ChatMessage > messages ,
529+ AgentSession ? session = null ,
530+ AgentRunOptions ? options = null ,
531+ [ EnumeratorCancellation ] CancellationToken cancellationToken = default )
532+ {
533+ if ( session is not FakeAgentSession typedSession )
534+ {
535+ throw new InvalidOperationException ( $ "The provided session type '{ session ? . GetType ( ) . Name ?? "null" } ' is not compatible with this agent. Only sessions of type '{ nameof ( FakeAgentSession ) } ' can be used by this agent.") ;
536+ }
537+
538+ string lastUserInput = messages . Last ( m => m . Role == ChatRole . User ) . Text ?? string . Empty ;
539+ string responseText ;
540+
541+ if ( lastUserInput . StartsWith ( "My name is " , StringComparison . OrdinalIgnoreCase ) )
542+ {
543+ string rememberedName = lastUserInput [ 11 .. ] . Trim ( ) ;
544+ typedSession . StateBag . SetValue ( NameStateKey , rememberedName ) ;
545+ responseText = $ "Nice to meet you { rememberedName } .";
546+ }
547+ else if ( lastUserInput . Equals ( "What is my name?" , StringComparison . OrdinalIgnoreCase ) )
548+ {
549+ string ? rememberedName = typedSession . StateBag . GetValue < string > ( NameStateKey ) ;
550+ responseText = rememberedName is null
551+ ? "I do not know your name yet."
552+ : $ "Your name is { rememberedName } .";
553+ }
554+ else
555+ {
556+ responseText = "I can remember your name if you tell me 'My name is ...'." ;
557+ }
558+
559+ yield return new AgentResponseUpdate
560+ {
561+ MessageId = Guid . NewGuid ( ) . ToString ( "N" ) ,
562+ Role = ChatRole . Assistant ,
563+ Contents = [ new TextContent ( responseText ) ]
564+ } ;
565+
566+ await Task . Yield ( ) ;
567+ }
568+
569+ private sealed class FakeAgentSession : AgentSession
570+ {
571+ public FakeAgentSession ( )
572+ {
573+ }
574+
575+ [ JsonConstructor ]
576+ public FakeAgentSession ( AgentSessionStateBag stateBag ) : base ( stateBag )
577+ {
578+ }
579+ }
580+ }
0 commit comments