-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathRpcTasksAndHandlersE2ETests.cs
More file actions
355 lines (297 loc) · 15.1 KB
/
Copy pathRpcTasksAndHandlersE2ETests.cs
File metadata and controls
355 lines (297 loc) · 15.1 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using GitHub.Copilot.Rpc;
using GitHub.Copilot.Test.Harness;
using System.Text.Json;
using Xunit;
using Xunit.Abstractions;
namespace GitHub.Copilot.Test.E2E;
public class RpcTasksAndHandlersE2ETests(E2ETestFixture fixture, ITestOutputHelper output)
: E2ETestBase(fixture, "rpc_tasks_and_handlers", output)
{
private static async Task AssertImplementedFailureAsync(Func<Task> action, string method)
{
var ex = await Assert.ThrowsAnyAsync<Exception>(action);
Assert.DoesNotContain($"Unhandled method {method}", ex.ToString(), StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task Should_List_Task_State_And_Return_False_For_Missing_Task_Operations()
{
var session = await CreateSessionAsync();
var tasks = await session.Rpc.Tasks.ListAsync();
Assert.NotNull(tasks.Tasks);
Assert.Empty(tasks.Tasks);
var refresh = await session.Rpc.Tasks.RefreshAsync();
Assert.NotNull(refresh);
using var waitCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var waitForPending = await session.Rpc.Tasks.WaitForPendingAsync(waitCts.Token);
Assert.NotNull(waitForPending);
var progress = await session.Rpc.Tasks.GetProgressAsync("missing-task");
Assert.Null(progress.Progress);
var currentPromotable = await session.Rpc.Tasks.GetCurrentPromotableAsync();
Assert.Null(currentPromotable.Task);
var promote = await session.Rpc.Tasks.PromoteToBackgroundAsync("missing-task");
Assert.False(promote.Promoted);
var promoteCurrent = await session.Rpc.Tasks.PromoteCurrentToBackgroundAsync();
Assert.Null(promoteCurrent.Task);
var cancel = await session.Rpc.Tasks.CancelAsync("missing-task");
Assert.False(cancel.Cancelled);
var remove = await session.Rpc.Tasks.RemoveAsync("missing-task");
Assert.False(remove.Removed);
var sendMessage = await session.Rpc.Tasks.SendMessageAsync("missing-task", "hello from the SDK E2E test");
Assert.False(sendMessage.Sent);
Assert.False(string.IsNullOrWhiteSpace(sendMessage.Error));
}
[Fact]
public async Task Should_Report_Implemented_Error_For_Missing_Task_Agent_Type()
{
var session = await CreateSessionAsync();
await AssertImplementedFailureAsync(
() => session.Rpc.Tasks.StartAgentAsync(
agentType: "missing-agent-type",
prompt: "Say hi",
name: "sdk-test-task"),
"session.tasks.startAgent");
}
[Fact]
public async Task Should_Report_Implemented_Error_For_Invalid_Task_Agent_Model()
{
var session = await CreateSessionAsync();
await AssertImplementedFailureAsync(
() => session.Rpc.Tasks.StartAgentAsync(
agentType: "general-purpose",
prompt: "Say hi",
name: "sdk-test-task",
description: "SDK task agent validation",
model: "not-a-real-model"),
"session.tasks.startAgent");
var tasks = await session.Rpc.Tasks.ListAsync();
Assert.Empty(tasks.Tasks);
}
[Fact]
public async Task Should_Start_Background_Agent_And_Report_Task_Details()
{
var session = await CreateSessionAsync();
var ready = await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "Reply with TASK_AGENT_READY exactly.",
});
Assert.Contains("TASK_AGENT_READY", ready?.Data.Content ?? string.Empty, StringComparison.Ordinal);
var taskCompletionNotification =
new TaskCompletionSource<AssistantMessageEvent>(TaskCreationOptions.RunContinuationsAsynchronously);
using var subscription = session.On<SessionEvent>(evt =>
{
switch (evt)
{
case AssistantMessageEvent assistantMessage
when assistantMessage.Data.Content?.Contains("TASK_AGENT_DONE", StringComparison.Ordinal) == true:
taskCompletionNotification.TrySetResult(assistantMessage);
break;
case SessionErrorEvent error:
taskCompletionNotification.TrySetException(new Exception(error.Data.Message ?? "session error"));
break;
}
});
var started = await session.Rpc.Tasks.StartAgentAsync(
agentType: "general-purpose",
prompt: "Reply with TASK_AGENT_DONE exactly.",
name: "sdk-background-agent",
description: "SDK background agent coverage");
Assert.False(string.IsNullOrWhiteSpace(started.AgentId));
TaskInfoAgent? task = null;
await TestHelper.WaitForConditionAsync(
async () =>
{
task = await FindAgentTaskAsync(session, started.AgentId);
return task is not null;
},
timeout: TimeSpan.FromSeconds(30),
timeoutMessage: $"Background agent task '{started.AgentId}' did not appear in session.tasks.list.");
Assert.NotNull(task);
Assert.Equal(started.AgentId, task.Id);
Assert.Equal("general-purpose", task.AgentType);
Assert.Equal("Reply with TASK_AGENT_DONE exactly.", task.Prompt);
Assert.Equal("SDK background agent coverage", task.Description);
Assert.Equal(GitHub.Copilot.Rpc.TaskExecutionMode.Background, task.ExecutionMode);
Assert.False(task.CanPromoteToBackground.GetValueOrDefault());
Assert.NotEqual(default, task.StartedAt);
var promote = await session.Rpc.Tasks.PromoteToBackgroundAsync(started.AgentId);
Assert.False(promote.Promoted);
await TestHelper.WaitForConditionAsync(
async () =>
{
task = await FindAgentTaskAsync(session, started.AgentId);
return task?.LatestResponse?.Contains("TASK_AGENT_DONE", StringComparison.Ordinal) == true
|| task?.Result?.Contains("TASK_AGENT_DONE", StringComparison.Ordinal) == true
|| task?.Status == GitHub.Copilot.Rpc.TaskStatus.Completed
|| task?.Status == GitHub.Copilot.Rpc.TaskStatus.Failed;
},
timeout: TimeSpan.FromSeconds(60),
timeoutMessage: $"Background agent task '{started.AgentId}' did not produce a final observable state.");
Assert.NotNull(task);
Assert.Contains("TASK_AGENT_DONE", task.LatestResponse ?? task.Result ?? string.Empty);
await taskCompletionNotification.Task.WaitAsync(TimeSpan.FromSeconds(30));
if (task.Status == GitHub.Copilot.Rpc.TaskStatus.Idle)
{
var cancel = await session.Rpc.Tasks.CancelAsync(started.AgentId);
Assert.True(cancel.Cancelled);
}
var remove = await session.Rpc.Tasks.RemoveAsync(started.AgentId);
Assert.True(remove.Removed);
var afterRemove = await session.Rpc.Tasks.ListAsync();
Assert.DoesNotContain(afterRemove.Tasks.OfType<TaskInfoAgent>(), t => string.Equals(t.Id, started.AgentId, StringComparison.Ordinal));
}
[Fact]
public async Task Should_Return_Expected_Results_For_Missing_Pending_Handler_RequestIds()
{
var session = await CreateSessionAsync();
var tool = await session.Rpc.Tools.HandlePendingToolCallAsync(
requestId: "missing-tool-request",
result: JsonDocument.Parse("\"tool result\"").RootElement.Clone());
Assert.False(tool.Success);
var command = await session.Rpc.Commands.HandlePendingCommandAsync(
requestId: "missing-command-request",
error: "command error");
Assert.True(command.Success);
var elicitation = await session.Rpc.Ui.HandlePendingElicitationAsync(
requestId: "missing-elicitation-request",
result: new UIElicitationResponse { Action = UIElicitationResponseAction.Cancel });
Assert.False(elicitation.Success);
var userInput = await session.Rpc.Ui.HandlePendingUserInputAsync(
requestId: "missing-user-input-request",
response: new UIUserInputResponse { Answer = "typed answer", WasFreeform = true });
Assert.False(userInput.Success);
var sampling = await session.Rpc.Ui.HandlePendingSamplingAsync(
requestId: "missing-sampling-request",
response: new UIHandlePendingSamplingResponse());
Assert.False(sampling.Success);
var autoModeSwitch = await session.Rpc.Ui.HandlePendingAutoModeSwitchAsync(
requestId: "missing-auto-mode-switch-request",
response: UIAutoModeSwitchResponse.No);
Assert.False(autoModeSwitch.Success);
var sessionLimits = await session.Rpc.Ui.HandlePendingSessionLimitsExhaustedAsync(
requestId: "missing-session-limits-exhausted-request",
response: new UISessionLimitsExhaustedResponse
{
Action = UISessionLimitsExhaustedResponseAction.Cancel,
});
Assert.False(sessionLimits.Success);
var exitPlanMode = await session.Rpc.Ui.HandlePendingExitPlanModeAsync(
requestId: "missing-exit-plan-mode-request",
response: new UIExitPlanModeResponse
{
Approved = false,
Feedback = "No pending plan approval",
SelectedAction = UIExitPlanModeAction.ExitOnly,
});
Assert.False(exitPlanMode.Success);
var permission = await session.Rpc.Permissions.HandlePendingPermissionRequestAsync(
requestId: "missing-permission-request",
result: new PermissionDecisionReject { Feedback = "not approved" });
Assert.False(permission.Success);
var permanentPermission = await session.Rpc.Permissions.HandlePendingPermissionRequestAsync(
requestId: "missing-permanent-permission-request",
result: new PermissionDecisionApprovePermanently { Domain = "example.com" });
Assert.False(permanentPermission.Success);
var sessionApproval = await session.Rpc.Permissions.HandlePendingPermissionRequestAsync(
requestId: "missing-session-approval-request",
result: new PermissionDecisionApproveForSession
{
Approval = new PermissionDecisionApproveForSessionApprovalCustomTool
{
ToolName = "missing-tool",
},
});
Assert.False(sessionApproval.Success);
var locationApproval = await session.Rpc.Permissions.HandlePendingPermissionRequestAsync(
requestId: "missing-location-approval-request",
result: new PermissionDecisionApproveForLocation
{
Approval = new PermissionDecisionApproveForLocationApprovalCustomTool
{
ToolName = "missing-tool",
},
LocationKey = "missing-location",
});
Assert.False(locationApproval.Success);
var missingHeaders = await session.Rpc.Mcp.Headers.HandlePendingHeadersRefreshRequestAsync(
requestId: "missing-headers-refresh-request",
result: new McpHeadersHandlePendingHeadersRefreshRequestHeaders
{
Headers = new Dictionary<string, string> { ["X-SDK-Test"] = "missing" },
});
Assert.False(missingHeaders.Success);
var missingNoHeaders = await session.Rpc.Mcp.Headers.HandlePendingHeadersRefreshRequestAsync(
requestId: "missing-headers-refresh-none-request",
result: new McpHeadersHandlePendingHeadersRefreshRequestNone());
Assert.False(missingNoHeaders.Success);
}
[Fact]
public async Task Should_Round_Trip_Rpc_Elicitation_Through_Config_Handler()
{
var handlerContext = new TaskCompletionSource<ElicitationContext>(TaskCreationOptions.RunContinuationsAsynchronously);
var session = await CreateSessionAsync(new SessionConfig
{
OnElicitationRequest = context =>
{
handlerContext.TrySetResult(context);
return Task.FromResult(new ElicitationResult
{
Action = UIElicitationResponseAction.Accept,
Content = new Dictionary<string, object>
{
["answer"] = "from handler",
["confirmed"] = true,
},
});
},
});
var schema = new UIElicitationSchema
{
Type = "object",
Properties = new Dictionary<string, JsonElement>
{
["answer"] = ParseJsonElement("""{"type":"string"}"""),
["confirmed"] = ParseJsonElement("""{"type":"boolean"}"""),
},
Required = ["answer"],
};
var response = await session.Rpc.Ui.ElicitationAsync("Need details", schema);
var context = await handlerContext.Task.WaitAsync(TimeSpan.FromSeconds(30));
Assert.Equal(session.SessionId, context.SessionId);
Assert.Equal("Need details", context.Message);
Assert.NotNull(context.RequestedSchema);
Assert.Equal("object", context.RequestedSchema.Type);
Assert.Contains("answer", context.RequestedSchema.Properties.Keys);
Assert.Contains("confirmed", context.RequestedSchema.Properties.Keys);
Assert.Equal(["answer"], context.RequestedSchema.Required);
Assert.Equal(UIElicitationResponseAction.Accept, response.Action);
Assert.NotNull(response.Content);
Assert.Equal("from handler", response.Content["answer"].GetString());
Assert.True(response.Content["confirmed"].GetBoolean());
}
[Fact]
public async Task Should_Register_And_Unregister_Direct_Auto_Mode_Switch_Handler()
{
var session = await CreateSessionAsync();
var missing = await session.Rpc.Ui.UnregisterDirectAutoModeSwitchHandlerAsync("missing-direct-auto-mode-handle");
Assert.False(missing.Unregistered);
var registration = await session.Rpc.Ui.RegisterDirectAutoModeSwitchHandlerAsync();
Assert.False(string.IsNullOrWhiteSpace(registration.Handle));
var unregister = await session.Rpc.Ui.UnregisterDirectAutoModeSwitchHandlerAsync(registration.Handle);
Assert.True(unregister.Unregistered);
var unregisterAgain = await session.Rpc.Ui.UnregisterDirectAutoModeSwitchHandlerAsync(registration.Handle);
Assert.False(unregisterAgain.Unregistered);
}
private static async Task<TaskInfoAgent?> FindAgentTaskAsync(CopilotSession session, string agentId)
{
var tasks = await session.Rpc.Tasks.ListAsync();
return tasks.Tasks.OfType<TaskInfoAgent>().SingleOrDefault(t => string.Equals(t.Id, agentId, StringComparison.Ordinal));
}
private static JsonElement ParseJsonElement(string json)
{
using var document = JsonDocument.Parse(json);
return document.RootElement.Clone();
}
}