-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathSessionE2ETests.cs
More file actions
980 lines (824 loc) · 35.8 KB
/
Copy pathSessionE2ETests.cs
File metadata and controls
980 lines (824 loc) · 35.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using GitHub.Copilot.Rpc;
using GitHub.Copilot.Test.Harness;
using Microsoft.Extensions.AI;
using System.Collections.Concurrent;
using System.ComponentModel;
using Xunit;
using Xunit.Abstractions;
namespace GitHub.Copilot.Test.E2E;
public class SessionE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "session", output)
{
[Fact]
public async Task ShouldCreateAndDisconnectSessions()
{
var session = await CreateSessionAsync(new SessionConfig { Model = "claude-sonnet-4.5" });
Assert.Matches(@"^[a-f0-9-]+$", session.SessionId);
var messages = await session.GetEventsAsync();
Assert.NotEmpty(messages);
var startEvent = Assert.IsType<SessionStartEvent>(messages[0]);
Assert.Equal(session.SessionId, startEvent.Data.SessionId);
await session.DisposeAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(() => session.GetEventsAsync());
}
[Fact]
public async Task Should_Have_Stateful_Conversation()
{
await using var session = await CreateSessionAsync();
var assistantMessage = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 1+1?" });
Assert.NotNull(assistantMessage);
Assert.Contains("2", assistantMessage!.Data.Content);
var secondMessage = await session.SendAndWaitAsync(new MessageOptions { Prompt = "Now if you double that, what do you get?" });
Assert.NotNull(secondMessage);
Assert.Contains("4", secondMessage!.Data.Content);
}
[Fact]
public async Task Should_Create_A_Session_With_Appended_SystemMessage_Config()
{
var systemMessageSuffix = "End each response with the phrase 'Have a nice day!'";
var session = await CreateSessionAsync(new SessionConfig
{
SystemMessage = new SystemMessageConfig { Mode = SystemMessageMode.Append, Content = systemMessageSuffix }
});
await session.SendAsync(new MessageOptions { Prompt = "What is your full name?" });
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
var content = assistantMessage!.Data.Content ?? string.Empty;
Assert.Contains("GitHub", content);
Assert.Contains("Have a nice day!", content);
var traffic = await Ctx.GetExchangesAsync();
Assert.NotEmpty(traffic);
var systemMessage = GetSystemMessage(traffic[0]);
Assert.Contains("GitHub", systemMessage);
Assert.Contains(systemMessageSuffix, systemMessage);
}
[Fact]
public async Task Should_Create_A_Session_With_Replaced_SystemMessage_Config()
{
var testSystemMessage = "You are an assistant called Testy McTestface. Reply succinctly.";
var session = await CreateSessionAsync(new SessionConfig
{
SystemMessage = new SystemMessageConfig { Mode = SystemMessageMode.Replace, Content = testSystemMessage }
});
await session.SendAsync(new MessageOptions { Prompt = "What is your full name?" });
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
var content = assistantMessage!.Data.Content ?? string.Empty;
Assert.DoesNotContain("GitHub", content);
Assert.Contains("Testy", content);
var traffic = await Ctx.GetExchangesAsync();
Assert.NotEmpty(traffic);
Assert.Equal(testSystemMessage, GetSystemMessage(traffic[0]));
}
[Fact]
public async Task Should_Create_A_Session_With_Customized_SystemMessage_Config()
{
var customTone = "Respond in a warm, professional tone. Be thorough in explanations.";
var appendedContent = "Always mention quarterly earnings.";
var session = await CreateSessionAsync(new SessionConfig
{
SystemMessage = new SystemMessageConfig
{
Mode = SystemMessageMode.Customize,
Sections = new Dictionary<SystemMessageSection, SectionOverride>
{
[SystemMessageSection.Tone] = new() { Action = SectionOverrideAction.Replace, Content = customTone },
[SystemMessageSection.CodeChangeRules] = new() { Action = SectionOverrideAction.Remove },
},
Content = appendedContent
}
});
try
{
await session.SendAsync(new MessageOptions { Prompt = "Who are you?" });
var traffic = await WaitForExchangesAsync();
var systemMessage = GetSystemMessage(traffic[0]);
Assert.Contains(customTone, systemMessage);
Assert.Contains(appendedContent, systemMessage);
Assert.DoesNotContain("<code_change_instructions>", systemMessage);
}
finally
{
await session.DisposeAsync();
}
}
[Fact]
public async Task Should_Create_A_Session_With_AvailableTools()
{
var session = await CreateSessionAsync(new SessionConfig
{
AvailableTools = ["view", "edit"]
});
try
{
var traffic = await SendAndWaitForExchangesAsync(
session,
new MessageOptions { Prompt = "What is 1+1?" });
var toolNames = GetToolNames(traffic[0]);
Assert.Equal(2, toolNames.Count);
Assert.Contains("view", toolNames);
Assert.Contains("edit", toolNames);
}
finally
{
await session.DisposeAsync();
}
}
[Fact]
public async Task Should_Create_A_Session_With_ExcludedTools()
{
var session = await CreateSessionAsync(new SessionConfig
{
ExcludedTools = ["view"]
});
try
{
var traffic = await SendAndWaitForExchangesAsync(
session,
new MessageOptions { Prompt = "What is 1+1?" });
var toolNames = GetToolNames(traffic[0]);
Assert.DoesNotContain("view", toolNames);
Assert.Contains("edit", toolNames);
Assert.Contains("grep", toolNames);
}
finally
{
await session.DisposeAsync();
}
}
[Fact]
public async Task Should_Create_A_Session_With_DefaultAgent_ExcludedTools()
{
var session = await CreateSessionAsync(new SessionConfig
{
Tools =
[
AIFunctionFactory.Create(
(string input) => "SECRET",
"secret_tool",
"A secret tool hidden from the default agent"),
],
DefaultAgent = new DefaultAgentConfig
{
ExcludedTools = ["secret_tool"],
},
});
try
{
var traffic = await SendAndWaitForExchangesAsync(
session,
new MessageOptions { Prompt = "What is 1+1?" });
var toolNames = GetToolNames(traffic[0]);
Assert.DoesNotContain("secret_tool", toolNames);
}
finally
{
await session.DisposeAsync();
}
}
[Fact]
public async Task Should_Create_Session_With_Custom_Tool()
{
var session = await CreateSessionAsync(new SessionConfig
{
Tools =
[
AIFunctionFactory.Create(async ([Description("Key")] string key) => {
await Task.Yield();
return key == "ALPHA" ? 54321 : 0;
}, "get_secret_number", "Gets the secret number"),
]
});
await session.SendAsync(new MessageOptions { Prompt = "What is the secret number for key ALPHA?" });
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.NotNull(assistantMessage);
Assert.Contains("54321", assistantMessage!.Data.Content ?? string.Empty);
}
[Fact]
public async Task Should_Reject_Resuming_Active_Session_Using_The_Same_Client()
{
var session1 = await CreateSessionAsync();
var sessionId = session1.SessionId;
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() =>
Client.ResumeSessionAsync(sessionId, new ResumeSessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
}));
Assert.Contains(sessionId, exception.Message);
}
[Fact]
public async Task Should_Resume_A_Session_Using_A_New_Client()
{
var session1 = await CreateSessionAsync();
var sessionId = session1.SessionId;
await session1.SendAsync(new MessageOptions { Prompt = "What is 1+1?" });
var answer = await TestHelper.GetFinalAssistantMessageAsync(session1);
Assert.NotNull(answer);
Assert.Contains("2", answer!.Data.Content ?? string.Empty);
using var newClient = Ctx.CreateClient();
var session2 = await newClient.ResumeSessionAsync(sessionId, new ResumeSessionConfig
{
ContinuePendingWork = true,
OnPermissionRequest = PermissionHandler.ApproveAll,
});
Assert.Equal(sessionId, session2.SessionId);
var messages = await session2.GetEventsAsync();
Assert.Contains(messages, m => m is UserMessageEvent);
var resumeEvent = Assert.Single(messages.OfType<SessionResumeEvent>());
Assert.True(resumeEvent.Data.ContinuePendingWork);
// Can continue the conversation statefully
var answer2 = await session2.SendAndWaitAsync(new MessageOptions { Prompt = "Now if you double that, what do you get?" });
Assert.NotNull(answer2);
Assert.Contains("4", answer2!.Data.Content ?? string.Empty);
}
[Fact]
public async Task Should_Throw_Error_When_Resuming_Non_Existent_Session()
{
await Assert.ThrowsAsync<IOException>(() =>
ResumeSessionAsync("non-existent-session-id"));
}
[Fact]
public async Task Should_Abort_A_Session()
{
var session = await CreateSessionAsync();
// Set up wait for tool execution to start BEFORE sending
var toolStartTask = TestHelper.GetNextEventOfTypeAsync<ToolExecutionStartEvent>(session);
var sessionIdleTask = TestHelper.GetNextEventOfTypeAsync<SessionIdleEvent>(session);
// Send a message that will take some time to process
await session.SendAsync(new MessageOptions
{
Prompt = "run the shell command 'sleep 100' (note this works on both bash and PowerShell)"
});
// Wait for tool execution to start
await toolStartTask;
// Abort the session
await session.AbortAsync();
await sessionIdleTask;
// The session should still be alive and usable after abort
var messages = await session.GetEventsAsync();
Assert.NotEmpty(messages);
// Verify an abort event exists in messages
Assert.Contains(messages, m => m is AbortEvent);
// We should be able to send another message
var answer = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2+2?" });
Assert.NotNull(answer);
Assert.Contains("4", answer!.Data.Content ?? string.Empty);
}
[Fact]
public async Task Should_Receive_Session_Events()
{
// Use OnEvent to capture events dispatched during session creation.
// session.start is emitted during the session.create RPC; if the session
// weren't registered in the sessions map before the RPC, it would be dropped.
var earlyEvents = new List<SessionEvent>();
var sessionStartReceived = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var session = await CreateSessionAsync(new SessionConfig
{
OnEvent = evt =>
{
earlyEvents.Add(evt);
if (evt is SessionStartEvent)
sessionStartReceived.TrySetResult(true);
},
});
// session.start is dispatched asynchronously via the event channel.
await sessionStartReceived.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Contains(earlyEvents, evt => evt is SessionStartEvent);
var receivedEvents = new List<SessionEvent>();
var receivedEventsLock = new object();
var idleReceived = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var concurrentCount = 0;
var maxConcurrent = 0;
session.On<SessionEvent>(evt =>
{
// Track concurrent handler invocations to verify serial dispatch.
var current = Interlocked.Increment(ref concurrentCount);
try
{
var seenMax = Volatile.Read(ref maxConcurrent);
if (current > seenMax)
Interlocked.CompareExchange(ref maxConcurrent, current, seenMax);
// Keep the handler active long enough that concurrent dispatch would
// overlap deterministically, without using sleep-based synchronization.
Thread.SpinWait(100_000);
}
finally
{
Interlocked.Decrement(ref concurrentCount);
}
lock (receivedEventsLock)
{
receivedEvents.Add(evt);
}
if (evt is SessionIdleEvent)
{
idleReceived.TrySetResult(true);
}
});
// Send a message to trigger events
await session.SendAsync(new MessageOptions { Prompt = "What is 100+200?" });
// Wait for session to become idle (indicating message processing is complete)
await idleReceived.Task.WaitAsync(TimeSpan.FromSeconds(60));
// Should have received multiple events (user message, assistant message, idle, etc.)
List<SessionEvent> observedEvents;
lock (receivedEventsLock)
{
observedEvents = [.. receivedEvents];
}
Assert.NotEmpty(observedEvents);
Assert.Contains(observedEvents, evt => evt is UserMessageEvent);
Assert.Contains(observedEvents, evt => evt is AssistantMessageEvent);
Assert.Contains(observedEvents, evt => evt is SessionIdleEvent);
// Events must be dispatched serially — never more than one handler invocation at a time.
Assert.Equal(1, maxConcurrent);
// Verify the assistant response contains the expected answer.
// session.idle is ephemeral and not in getEvents(), but we already
// confirmed idle via the live event handler above.
var assistantMessage = await TestHelper.GetFinalAssistantMessageAsync(session, alreadyIdle: true);
Assert.NotNull(assistantMessage);
Assert.Contains("300", assistantMessage!.Data.Content);
await session.DisposeAsync();
}
[Fact]
public async Task Send_Returns_Immediately_While_Events_Stream_In_Background()
{
var session = await CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
});
var events = new ConcurrentQueue<string>();
session.On<SessionEvent>(evt => events.Enqueue(evt.Type));
// Use a slow command so we can verify SendAsync() returns before completion
await session.SendAsync(new MessageOptions { Prompt = "Run 'sleep 2 && echo done'" });
// SendAsync() should return before turn completes (no session.idle yet)
Assert.DoesNotContain("session.idle", events);
// Wait for turn to complete
var message = await TestHelper.GetFinalAssistantMessageAsync(session);
Assert.Contains("done", message?.Data.Content ?? string.Empty);
Assert.Contains("session.idle", events);
Assert.Contains("assistant.message", events);
}
[Fact]
public async Task SendAndWait_Blocks_Until_Session_Idle_And_Returns_Final_Assistant_Message()
{
var session = await CreateSessionAsync();
var events = new ConcurrentQueue<string>();
session.On<SessionEvent>(evt => events.Enqueue(evt.Type));
var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2+2?" });
Assert.NotNull(response);
Assert.Equal("assistant.message", response!.Type);
Assert.Contains("4", response.Data.Content ?? string.Empty);
Assert.Contains("session.idle", events);
Assert.Contains("assistant.message", events);
}
[Fact]
public async Task Should_List_Sessions_With_Context()
{
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions { Prompt = "Say OK." });
SessionMetadata? ourSession = null;
await TestHelper.WaitForConditionAsync(
async () =>
{
var sessions = await Client.ListSessionsAsync();
ourSession = sessions.FirstOrDefault(s => s.SessionId == session.SessionId);
return ourSession is not null;
},
timeout: TimeSpan.FromSeconds(10),
timeoutMessage: "Timed out waiting for the current session to appear in ListSessionsAsync().");
Assert.NotNull(ourSession);
var allSessions = await Client.ListSessionsAsync();
Assert.NotEmpty(allSessions);
// Context may be present on sessions that have been persisted with workspace.yaml
if (ourSession.Context != null)
{
Assert.False(string.IsNullOrEmpty(ourSession.Context.WorkingDirectory), "Expected context.WorkingDirectory to be non-empty when context is present");
}
}
[Fact]
public async Task Should_Get_Session_Metadata_By_Id()
{
var session = await CreateSessionAsync();
// Send a message to persist the session to disk
await session.SendAndWaitAsync(new MessageOptions { Prompt = "Say hello" });
SessionMetadata? metadata = null;
await TestHelper.WaitForConditionAsync(
async () =>
{
metadata = await Client.GetSessionMetadataAsync(session.SessionId);
return metadata is not null;
},
timeout: TimeSpan.FromSeconds(10),
timeoutMessage: "Timed out waiting for GetSessionMetadataAsync() to return the persisted session.");
Assert.NotNull(metadata);
Assert.Equal(session.SessionId, metadata.SessionId);
Assert.NotEqual(default, metadata.StartTime);
Assert.NotEqual(default, metadata.ModifiedTime);
// Verify non-existent session returns null
var notFound = await Client.GetSessionMetadataAsync("non-existent-session-id");
Assert.Null(notFound);
}
[Fact]
public async Task SendAndWait_Throws_On_Timeout()
{
var session = await CreateSessionAsync();
var sessionIdleTask = TestHelper.GetNextEventOfTypeAsync<SessionIdleEvent>(session);
// Use a slow command to ensure timeout triggers before completion
var ex = await Assert.ThrowsAsync<TimeoutException>(() =>
session.SendAndWaitAsync(new MessageOptions { Prompt = "Run 'sleep 2 && echo done'" }, TimeSpan.FromMilliseconds(100)));
Assert.Contains("timed out", ex.Message);
// The timeout only cancels the client-side wait; abort the agent and wait for idle
// so leftover requests don't leak into subsequent tests.
await session.AbortAsync();
await sessionIdleTask;
}
[Fact]
public async Task SendAndWait_Throws_OperationCanceledException_When_Token_Cancelled()
{
var session = await CreateSessionAsync();
// Set up wait for tool execution to start BEFORE sending
var toolStartTask = TestHelper.GetNextEventOfTypeAsync<ToolExecutionStartEvent>(session);
var sessionIdleTask = TestHelper.GetNextEventOfTypeAsync<SessionIdleEvent>(session);
using var cts = new CancellationTokenSource();
// Start SendAndWaitAsync - don't await it yet
var sendTask = session.SendAndWaitAsync(
new MessageOptions { Prompt = "run the shell command 'sleep 10' (note this works on both bash and PowerShell)" },
cancellationToken: cts.Token);
// Wait for the tool to begin executing before cancelling
await toolStartTask;
// Cancel the token
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sendTask);
// Cancelling the token only cancels the client-side wait, not the server-side agent loop.
// Explicitly abort so the agent stops, then wait for idle to ensure we're not still
// running this agent's operations in the context of a subsequent test.
await session.AbortAsync();
await sessionIdleTask;
}
[Fact]
public async Task Should_Create_Session_With_Custom_Config_Dir()
{
var customConfigDir = Path.Join(Ctx.HomeDir, "custom-config");
var session = await CreateSessionAsync(new SessionConfig { ConfigDirectory = customConfigDir });
Assert.Matches(@"^[a-f0-9-]+$", session.SessionId);
try
{
// Session should work normally with custom config dir.
var assistantMessage = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 1+1?" });
Assert.NotNull(assistantMessage);
Assert.Contains("2", assistantMessage!.Data.Content);
}
finally
{
await session.DisposeAsync();
}
}
[Fact]
public async Task Should_Set_Model_On_Existing_Session()
{
var session = await CreateSessionAsync();
// Subscribe for the model change event before calling SetModelAsync
var modelChangedTask = TestHelper.GetNextEventOfTypeAsync<SessionModelChangeEvent>(session);
await session.SetModelAsync("gpt-4.1");
// Verify a model_change event was emitted with the new model
var modelChanged = await modelChangedTask;
Assert.Equal("gpt-4.1", modelChanged.Data.NewModel);
}
[Fact]
public async Task Should_Set_Model_With_ReasoningEffort()
{
var session = await CreateSessionAsync();
var modelChangedTask = TestHelper.GetNextEventOfTypeAsync<SessionModelChangeEvent>(session);
await session.SetModelAsync("gpt-4.1", "high");
var modelChanged = await modelChangedTask;
Assert.Equal("gpt-4.1", modelChanged.Data.NewModel);
Assert.Equal("high", modelChanged.Data.ReasoningEffort);
}
[Fact]
public async Task Should_Log_Messages_At_Various_Levels()
{
var session = await CreateSessionAsync();
var events = new List<SessionEvent>();
var eventsLock = new object();
session.On<SessionEvent>(evt =>
{
lock (eventsLock)
{
events.Add(evt);
}
});
await session.LogAsync("Info message");
await session.LogAsync("Warning message", level: SessionLogLevel.Warning);
await session.LogAsync("Error message", level: SessionLogLevel.Error);
await session.LogAsync("Ephemeral message", ephemeral: true);
// Poll until all 4 notification events arrive
await TestHelper.WaitForConditionAsync(
() =>
{
List<SessionEvent> snapshot;
lock (eventsLock)
{
snapshot = [.. events];
}
var notifications = snapshot.Where(e =>
e is SessionInfoEvent info && info.Data.InfoType == "notification" ||
e is SessionWarningEvent warn && warn.Data.WarningType == "notification" ||
e is SessionErrorEvent err && err.Data.ErrorType == "notification"
).ToList();
return notifications.Count >= 4;
},
timeout: TimeSpan.FromSeconds(10),
timeoutMessage: "Timed out waiting for all four notification log events to be observed.");
List<SessionEvent> observedEvents;
lock (eventsLock)
{
observedEvents = [.. events];
}
var infoEvent = observedEvents.OfType<SessionInfoEvent>().First(e => e.Data.Message == "Info message");
Assert.Equal("notification", infoEvent.Data.InfoType);
var warningEvent = observedEvents.OfType<SessionWarningEvent>().First(e => e.Data.Message == "Warning message");
Assert.Equal("notification", warningEvent.Data.WarningType);
var errorEvent = observedEvents.OfType<SessionErrorEvent>().First(e => e.Data.Message == "Error message");
Assert.Equal("notification", errorEvent.Data.ErrorType);
var ephemeralEvent = observedEvents.OfType<SessionInfoEvent>().First(e => e.Data.Message == "Ephemeral message");
Assert.Equal("notification", ephemeralEvent.Data.InfoType);
}
[Fact]
public async Task Handler_Exception_Does_Not_Halt_Event_Delivery()
{
var session = await CreateSessionAsync();
var eventCount = 0;
var gotIdle = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
session.On<SessionEvent>(evt =>
{
eventCount++;
// Throw on the first event to verify the loop keeps going.
if (eventCount == 1)
throw new InvalidOperationException("boom");
if (evt is SessionIdleEvent)
gotIdle.TrySetResult();
});
await session.SendAsync(new MessageOptions { Prompt = "What is 1+1?" });
await gotIdle.Task.WaitAsync(TimeSpan.FromSeconds(30));
// Handler saw more than just the first (throwing) event.
Assert.True(eventCount > 1);
}
[Fact]
public async Task DisposeAsync_From_Handler_Does_Not_Deadlock()
{
var session = await CreateSessionAsync();
var disposed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
session.On<SessionEvent>(evt =>
{
if (evt is SessionInfoEvent)
{
// Call DisposeAsync from within a handler — must not deadlock.
session.DisposeAsync().AsTask().ContinueWith(_ => disposed.TrySetResult());
}
});
await session.LogAsync("Dispose from handler trigger");
// If this times out, we deadlocked.
await disposed.Task.WaitAsync(TimeSpan.FromSeconds(10));
await Client.ForceStopAsync();
}
[Fact]
public async Task Should_Accept_Blob_Attachments()
{
var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
await File.WriteAllBytesAsync(Path.Join(Ctx.WorkDir, "test-pixel.png"), Convert.FromBase64String(pngBase64));
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "Describe this image",
Attachments =
[
new AttachmentBlob
{
Data = pngBase64,
MimeType = "image/png",
DisplayName = "test-pixel.png",
},
],
});
await session.DisposeAsync();
}
[Fact]
public async Task Should_Send_With_File_Attachment()
{
var filePath = Path.Join(Ctx.WorkDir, "attached-file.txt");
await File.WriteAllTextAsync(filePath, "FILE_ATTACHMENT_SENTINEL");
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "Read the attached file and reply with its contents.",
Attachments =
[
new AttachmentFile
{
DisplayName = "attached-file.txt",
Path = filePath,
LineRange = new AttachmentFileLineRange { Start = 1, End = 1 },
},
],
});
var userMessage = (await session.GetEventsAsync()).OfType<UserMessageEvent>().Last();
var attachment = Assert.IsType<AttachmentFile>(Assert.Single(userMessage.Data.Attachments!));
Assert.Equal("attached-file.txt", attachment.DisplayName);
Assert.Equal(filePath, attachment.Path);
Assert.Equal(1, attachment.LineRange!.Start);
Assert.Equal(1, attachment.LineRange.End);
}
[Fact]
public async Task Should_Send_With_Directory_Attachment()
{
var directoryPath = Path.Join(Ctx.WorkDir, "attached-directory");
Directory.CreateDirectory(directoryPath);
await File.WriteAllTextAsync(Path.Join(directoryPath, "readme.txt"), "DIRECTORY_ATTACHMENT_SENTINEL");
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "List the attached directory.",
Attachments =
[
new AttachmentDirectory
{
DisplayName = "attached-directory",
Path = directoryPath,
},
],
});
var userMessage = (await session.GetEventsAsync()).OfType<UserMessageEvent>().Last();
var attachment = Assert.IsType<AttachmentDirectory>(Assert.Single(userMessage.Data.Attachments!));
Assert.Equal("attached-directory", attachment.DisplayName);
Assert.Equal(directoryPath, attachment.Path);
}
[Fact]
public async Task Should_Send_With_Selection_Attachment()
{
var filePath = Path.Join(Ctx.WorkDir, "selected-file.cs");
await File.WriteAllTextAsync(filePath, "class C { string Value = \"SELECTION_SENTINEL\"; }");
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "Summarize the selected code.",
Attachments =
[
new AttachmentSelection
{
DisplayName = "selected-file.cs",
FilePath = filePath,
Text = "string Value = \"SELECTION_SENTINEL\";",
Selection = new AttachmentSelectionDetails
{
Start = new AttachmentSelectionDetailsStart { Line = 1, Character = 10 },
End = new AttachmentSelectionDetailsEnd { Line = 1, Character = 45 },
},
},
],
});
var userMessage = (await session.GetEventsAsync()).OfType<UserMessageEvent>().Last();
var attachment = Assert.IsType<AttachmentSelection>(Assert.Single(userMessage.Data.Attachments!));
Assert.Equal("selected-file.cs", attachment.DisplayName);
Assert.Equal(filePath, attachment.FilePath);
Assert.Equal("string Value = \"SELECTION_SENTINEL\";", attachment.Text);
Assert.Equal(1, attachment.Selection.Start.Line);
Assert.Equal(10, attachment.Selection.Start.Character);
Assert.Equal(1, attachment.Selection.End.Line);
Assert.Equal(45, attachment.Selection.End.Character);
}
[Fact]
public async Task Should_Send_With_GitHub_Reference_Attachment()
{
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "Using only the GitHub reference metadata in this message, summarize the reference. Do not call any tools.",
Attachments =
[
new AttachmentGitHubReference
{
Number = 1234,
ReferenceType = AttachmentGitHubReferenceType.Issue,
State = "open",
Title = "Add E2E attachment coverage",
Url = "https://github.com/github/copilot-sdk/issues/1234",
},
],
});
var userMessage = (await session.GetEventsAsync()).OfType<UserMessageEvent>().Last();
var attachment = Assert.IsType<AttachmentGitHubReference>(Assert.Single(userMessage.Data.Attachments!));
Assert.Equal(1234, attachment.Number);
Assert.Equal(AttachmentGitHubReferenceType.Issue, attachment.ReferenceType);
Assert.Equal("open", attachment.State);
Assert.Equal("Add E2E attachment coverage", attachment.Title);
Assert.Equal("https://github.com/github/copilot-sdk/issues/1234", attachment.Url);
}
[Fact]
public async Task Should_Send_With_Mode_Property()
{
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "Say mode ok.",
AgentMode = AgentMode.Plan,
});
var userMessage = (await session.GetEventsAsync()).OfType<UserMessageEvent>().Last();
Assert.Equal("Say mode ok.", userMessage.Data.Content);
Assert.Equal(UserMessageAgentMode.Plan, userMessage.Data.AgentMode);
}
[Fact]
public async Task Should_Send_With_Custom_RequestHeaders()
{
var session = await CreateSessionAsync();
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "What is 1+1?",
RequestHeaders = new Dictionary<string, string>
{
["x-copilot-sdk-test-header"] = "csharp-request-headers",
},
});
var exchanges = await Ctx.GetExchangesAsync();
Assert.NotEmpty(exchanges);
var headers = exchanges.Last().RequestHeaders ?? [];
Assert.Contains(
headers,
pair => string.Equals(pair.Key, "x-copilot-sdk-test-header", StringComparison.OrdinalIgnoreCase) &&
pair.Value.ToString().Contains("csharp-request-headers", StringComparison.Ordinal));
}
[Fact]
public async Task Should_Create_Session_With_Custom_Provider()
{
var session = await CreateSessionAsync(new SessionConfig
{
Provider = new ProviderConfig
{
Type = "openai",
BaseUrl = "https://api.openai.com/v1",
ApiKey = "fake-key",
},
});
Assert.False(string.IsNullOrEmpty(session.SessionId));
try
{
await session.DisposeAsync();
}
catch (Exception)
{
// disconnect may fail since the provider is fake
}
}
[Fact]
public async Task Should_Create_Session_With_Azure_Provider()
{
var session = await CreateSessionAsync(new SessionConfig
{
Provider = new ProviderConfig
{
Type = "azure",
BaseUrl = "https://my-resource.openai.azure.com",
ApiKey = "fake-key",
Azure = new AzureOptions
{
ApiVersion = "2024-02-15-preview",
},
},
});
Assert.False(string.IsNullOrEmpty(session.SessionId));
try
{
await session.DisposeAsync();
}
catch (Exception)
{
// disconnect may fail since the provider is fake
}
}
[Fact]
public async Task Should_Resume_Session_With_Custom_Provider()
{
var session = await CreateSessionAsync();
var sessionId = session.SessionId;
var session2 = await ResumeSessionAsync(sessionId, new ResumeSessionConfig
{
Provider = new ProviderConfig
{
Type = "openai",
BaseUrl = "https://api.openai.com/v1",
ApiKey = "fake-key",
},
});
Assert.Equal(sessionId, session2.SessionId);
try
{
await session2.DisposeAsync();
}
catch (Exception)
{
// disconnect may fail since the provider is fake
}
await session.DisposeAsync();
}
}