forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_rpc_tasks_and_handlers_e2e.py
More file actions
277 lines (241 loc) · 10.7 KB
/
Copy pathtest_rpc_tasks_and_handlers_e2e.py
File metadata and controls
277 lines (241 loc) · 10.7 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
"""
E2E coverage for ``session.tasks.*`` and pending-handler RPCs.
Mirrors ``dotnet/test/RpcTasksAndHandlersTests.cs`` (snapshot category
``rpc_tasks_and_handlers``).
"""
from __future__ import annotations
import asyncio
import pytest
from copilot.generated.rpc import (
CommandsHandlePendingCommandRequest,
HandlePendingToolCallRequest,
PermissionDecisionApproveForLocation,
PermissionDecisionApproveForLocationApprovalCustomTool,
PermissionDecisionApproveForSession,
PermissionDecisionApproveForSessionApprovalCustomTool,
PermissionDecisionApprovePermanently,
PermissionDecisionReject,
PermissionDecisionRequest,
TasksCancelRequest,
TasksPromoteToBackgroundRequest,
TasksRemoveRequest,
TasksStartAgentRequest,
UIElicitationResponse,
UIElicitationResponseAction,
UIHandlePendingElicitationRequest,
)
from copilot.session import PermissionHandler
from .testharness import E2ETestContext
pytestmark = pytest.mark.asyncio(loop_scope="module")
async def _find_agent_task(session, task_id: str):
task_list = await session.rpc.tasks.list()
return next((t for t in (task_list.tasks or []) if t.id == task_id), None)
async def _wait_for_agent_task(session, task_id: str, predicate, timeout: float, message: str):
deadline = asyncio.get_running_loop().time() + timeout
last_task = None
while True:
last_task = await _find_agent_task(session, task_id)
if predicate(last_task):
return last_task
if asyncio.get_running_loop().time() >= deadline:
pytest.fail(f"{message}; last observed task: {last_task!r}")
await asyncio.sleep(0.25)
async def _assert_implemented_failure(awaitable, method: str) -> None:
with pytest.raises(Exception) as excinfo:
_ = await awaitable
assert f"Unhandled method {method}".lower() not in str(excinfo.value).lower()
class TestRpcTasksAndHandlers:
async def test_should_list_task_state_and_return_false_for_missing_task_operations(
self, ctx: E2ETestContext
):
session = await ctx.client.create_session(
on_permission_request=PermissionHandler.approve_all,
)
try:
tasks = await session.rpc.tasks.list()
assert tasks.tasks is not None
assert len(tasks.tasks) == 0
promote = await session.rpc.tasks.promote_to_background(
TasksPromoteToBackgroundRequest(id="missing-task")
)
assert promote.promoted is False
cancel = await session.rpc.tasks.cancel(TasksCancelRequest(id="missing-task"))
assert cancel.cancelled is False
remove = await session.rpc.tasks.remove(TasksRemoveRequest(id="missing-task"))
assert remove.removed is False
finally:
await session.disconnect()
async def test_should_report_implemented_error_for_missing_task_agent_type(
self, ctx: E2ETestContext
):
session = await ctx.client.create_session(
on_permission_request=PermissionHandler.approve_all,
)
try:
await _assert_implemented_failure(
session.rpc.tasks.start_agent(
TasksStartAgentRequest(
agent_type="missing-agent-type",
prompt="Say hi",
name="sdk-test-task",
)
),
"session.tasks.startAgent",
)
finally:
await session.disconnect()
async def test_should_return_expected_results_for_missing_pending_handler_request_ids(
self, ctx: E2ETestContext
):
session = await ctx.client.create_session(
on_permission_request=PermissionHandler.approve_all,
)
try:
tool = await session.rpc.tools.handle_pending_tool_call(
HandlePendingToolCallRequest(
request_id="missing-tool-request",
result="tool result",
)
)
assert tool.success is False
command = await session.rpc.commands.handle_pending_command(
CommandsHandlePendingCommandRequest(
request_id="missing-command-request",
error="command error",
)
)
assert command.success is True
elicitation = await session.rpc.ui.handle_pending_elicitation(
UIHandlePendingElicitationRequest(
request_id="missing-elicitation-request",
result=UIElicitationResponse(action=UIElicitationResponseAction.CANCEL),
)
)
assert elicitation.success is False
permission = await session.rpc.permissions.handle_pending_permission_request(
PermissionDecisionRequest(
request_id="missing-permission-request",
result=PermissionDecisionReject(feedback="not approved"),
)
)
assert permission.success is False
permanent = await session.rpc.permissions.handle_pending_permission_request(
PermissionDecisionRequest(
request_id="missing-permanent-permission-request",
result=PermissionDecisionApprovePermanently(domain="example.com"),
)
)
assert permanent.success is False
session_approval = await session.rpc.permissions.handle_pending_permission_request(
PermissionDecisionRequest(
request_id="missing-session-approval-request",
result=PermissionDecisionApproveForSession(
approval=PermissionDecisionApproveForSessionApprovalCustomTool(
tool_name="missing-tool",
),
),
)
)
assert session_approval.success is False
location_approval = await session.rpc.permissions.handle_pending_permission_request(
PermissionDecisionRequest(
request_id="missing-location-approval-request",
result=PermissionDecisionApproveForLocation(
location_key="missing-location",
approval=PermissionDecisionApproveForLocationApprovalCustomTool(
tool_name="missing-tool",
),
),
)
)
assert location_approval.success is False
finally:
await session.disconnect()
async def test_should_report_implemented_error_for_invalid_task_agent_model(
self, ctx: E2ETestContext
):
"""Invalid model name for agent task returns an error without 'Unhandled method'."""
session = await ctx.client.create_session(
on_permission_request=PermissionHandler.approve_all,
)
try:
with pytest.raises(Exception) as excinfo:
await session.rpc.tasks.start_agent(
TasksStartAgentRequest(
agent_type="general-purpose",
prompt="Say hi",
name="sdk-test-invalid-model",
model="not-a-real-model",
)
)
text = str(excinfo.value).lower()
assert "unhandled method session.tasks.startagent" not in text
tasks = await session.rpc.tasks.list()
assert tasks.tasks is not None
assert len(tasks.tasks) == 0, "Task list should be empty after invalid start"
finally:
await session.disconnect()
async def test_should_start_background_agent_and_report_task_details(self, ctx: E2ETestContext):
"""Start a background agent task and verify task details then remove it."""
from copilot.generated.rpc import TaskAgentInfo, TaskInfoExecutionMode, TaskInfoStatus
session = await ctx.client.create_session(
on_permission_request=PermissionHandler.approve_all,
)
try:
ready = await session.send_and_wait(
"Reply with TASK_AGENT_READY exactly.",
timeout=60.0,
)
assert ready is not None
assert "TASK_AGENT_READY" in (ready.data.content or "")
start_result = await session.rpc.tasks.start_agent(
TasksStartAgentRequest(
agent_type="general-purpose",
prompt="Reply with TASK_AGENT_DONE exactly.",
name="sdk-background-agent",
description="SDK background agent coverage",
)
)
task_id = start_result.agent_id
assert task_id, "Expected a task ID from start_agent"
found_task = await _wait_for_agent_task(
session,
task_id,
lambda task: task is not None,
30.0,
f"Task {task_id} not found in tasks list",
)
assert found_task.id == task_id
assert found_task.description == "SDK background agent coverage"
assert isinstance(found_task, TaskAgentInfo)
assert found_task.agent_type == "general-purpose"
assert found_task.execution_mode == TaskInfoExecutionMode.BACKGROUND
assert found_task.prompt == "Reply with TASK_AGENT_DONE exactly."
found_task = await _wait_for_agent_task(
session,
task_id,
lambda task: (
task is None
or task.status
in (
TaskInfoStatus.COMPLETED,
TaskInfoStatus.FAILED,
TaskInfoStatus.CANCELLED,
TaskInfoStatus.IDLE,
)
),
60.0,
f"Task {task_id} did not produce a final observable state",
)
assert found_task is not None, f"Task {task_id} disappeared before it completed"
assert "TASK_AGENT_DONE" in (found_task.latest_response or found_task.result or "")
if found_task.status == TaskInfoStatus.IDLE:
cancel = await session.rpc.tasks.cancel(TasksCancelRequest(id=task_id))
assert cancel.cancelled is True
# Remove the task
remove = await session.rpc.tasks.remove(TasksRemoveRequest(id=task_id))
assert remove.removed is True
after_remove = await session.rpc.tasks.list()
assert not any(t.id == task_id for t in (after_remove.tasks or []))
finally:
await session.disconnect()