-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtest_commands_and_elicitation.py
More file actions
659 lines (536 loc) · 23.2 KB
/
test_commands_and_elicitation.py
File metadata and controls
659 lines (536 loc) · 23.2 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
"""
Unit tests for Commands, UI Elicitation (client→server), and
onElicitationContext (server→client callback) features.
Mirrors the Node.js client.test.ts tests for these features.
"""
import asyncio
import pytest
from copilot import CopilotClient
from copilot.client import SubprocessConfig
from copilot.session import (
CommandContext,
CommandDefinition,
ElicitationContext,
ElicitationResult,
PermissionHandler,
)
from e2e.testharness import CLI_PATH
# ============================================================================
# Commands
# ============================================================================
class TestCommands:
@pytest.mark.asyncio
async def test_forwards_commands_in_session_create_rpc(self):
"""Verifies that commands (name + description) are serialized in session.create payload."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
captured: dict = {}
original_request = client._client.request
async def mock_request(method, params):
captured[method] = params
return await original_request(method, params)
client._client.request = mock_request
await client.create_session(
on_permission_request=PermissionHandler.approve_all,
commands=[
CommandDefinition(
name="deploy",
description="Deploy the app",
handler=lambda ctx: None,
),
CommandDefinition(
name="rollback",
handler=lambda ctx: None,
),
],
)
payload = captured["session.create"]
assert payload["commands"] == [
{"name": "deploy", "description": "Deploy the app"},
{"name": "rollback", "description": None},
]
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_forwards_commands_in_session_resume_rpc(self):
"""Verifies that commands are serialized in session.resume payload."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all
)
captured: dict = {}
async def mock_request(method, params):
captured[method] = params
if method == "session.resume":
return {"sessionId": params["sessionId"]}
raise RuntimeError(f"Unexpected method: {method}")
client._client.request = mock_request
await client.resume_session(
session.session_id,
on_permission_request=PermissionHandler.approve_all,
commands=[
CommandDefinition(
name="deploy",
description="Deploy",
handler=lambda ctx: None,
),
],
)
payload = captured["session.resume"]
assert payload["commands"] == [{"name": "deploy", "description": "Deploy"}]
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_routes_command_execute_event_to_correct_handler(self):
"""Verifies the command dispatch works for command.execute events."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
handler_calls: list[CommandContext] = []
async def deploy_handler(ctx: CommandContext) -> None:
handler_calls.append(ctx)
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
commands=[
CommandDefinition(name="deploy", handler=deploy_handler),
],
)
# Mock the RPC so handlePendingCommand doesn't fail
rpc_calls: list[tuple] = []
original_request = client._client.request
async def mock_request(method, params):
if method == "session.commands.handlePendingCommand":
rpc_calls.append((method, params))
return {"success": True}
return await original_request(method, params)
client._client.request = mock_request
# Simulate a command.execute broadcast event
from copilot.generated.session_events import (
Data,
SessionEvent,
SessionEventType,
)
event = SessionEvent(
data=Data(
request_id="req-1",
command="/deploy production",
command_name="deploy",
args="production",
),
id="evt-1",
timestamp="2025-01-01T00:00:00Z",
type=SessionEventType.COMMAND_EXECUTE,
ephemeral=True,
parent_id=None,
)
session._dispatch_event(event)
# Wait for async handler
await asyncio.sleep(0.2)
assert len(handler_calls) == 1
assert handler_calls[0].session_id == session.session_id
assert handler_calls[0].command == "/deploy production"
assert handler_calls[0].command_name == "deploy"
assert handler_calls[0].args == "production"
# Verify handlePendingCommand was called
assert len(rpc_calls) >= 1
assert rpc_calls[0][1]["requestId"] == "req-1"
# No error key means success
assert "error" not in rpc_calls[0][1] or rpc_calls[0][1].get("error") is None
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_sends_error_when_command_handler_throws(self):
"""Verifies error is sent via RPC when a command handler raises."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
def fail_handler(ctx: CommandContext) -> None:
raise RuntimeError("deploy failed")
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
commands=[
CommandDefinition(name="fail", handler=fail_handler),
],
)
rpc_calls: list[tuple] = []
original_request = client._client.request
async def mock_request(method, params):
if method == "session.commands.handlePendingCommand":
rpc_calls.append((method, params))
return {"success": True}
return await original_request(method, params)
client._client.request = mock_request
from copilot.generated.session_events import (
Data,
SessionEvent,
SessionEventType,
)
event = SessionEvent(
data=Data(
request_id="req-2",
command="/fail",
command_name="fail",
args="",
),
id="evt-2",
timestamp="2025-01-01T00:00:00Z",
type=SessionEventType.COMMAND_EXECUTE,
ephemeral=True,
parent_id=None,
)
session._dispatch_event(event)
await asyncio.sleep(0.2)
assert len(rpc_calls) >= 1
assert rpc_calls[0][1]["requestId"] == "req-2"
assert "deploy failed" in rpc_calls[0][1]["error"]
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_sends_error_for_unknown_command(self):
"""Verifies error is sent via RPC for an unrecognized command."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
commands=[
CommandDefinition(name="deploy", handler=lambda ctx: None),
],
)
rpc_calls: list[tuple] = []
original_request = client._client.request
async def mock_request(method, params):
if method == "session.commands.handlePendingCommand":
rpc_calls.append((method, params))
return {"success": True}
return await original_request(method, params)
client._client.request = mock_request
from copilot.generated.session_events import (
Data,
SessionEvent,
SessionEventType,
)
event = SessionEvent(
data=Data(
request_id="req-3",
command="/unknown",
command_name="unknown",
args="",
),
id="evt-3",
timestamp="2025-01-01T00:00:00Z",
type=SessionEventType.COMMAND_EXECUTE,
ephemeral=True,
parent_id=None,
)
session._dispatch_event(event)
await asyncio.sleep(0.2)
assert len(rpc_calls) >= 1
assert rpc_calls[0][1]["requestId"] == "req-3"
assert "Unknown command" in rpc_calls[0][1]["error"]
finally:
await client.force_stop()
# ============================================================================
# UI Elicitation (client → server)
# ============================================================================
class TestUiElicitation:
@pytest.mark.asyncio
async def test_reads_capabilities_from_session_create_response(self):
"""Verifies capabilities are parsed from session.create response."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
original_request = client._client.request
async def mock_request(method, params):
if method == "session.create":
result = await original_request(method, params)
return {**result, "capabilities": {"ui": {"elicitation": True}}}
return await original_request(method, params)
client._client.request = mock_request
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all
)
assert session.capabilities == {"ui": {"elicitation": True}}
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_defaults_capabilities_when_not_injected(self):
"""Verifies capabilities default to empty when server returns none."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all
)
# CLI returns actual capabilities; in headless mode, elicitation is
# either False or absent. Just verify we don't crash.
ui_caps = session.capabilities.get("ui", {})
assert ui_caps.get("elicitation") in (False, None, True)
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_elicitation_throws_when_capability_is_missing(self):
"""Verifies that UI methods throw when elicitation is not supported."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all
)
# Force capabilities to not support elicitation
session._set_capabilities({})
with pytest.raises(RuntimeError, match="not supported"):
await session.ui.elicitation(
{
"message": "Enter name",
"requestedSchema": {
"type": "object",
"properties": {"name": {"type": "string", "minLength": 1}},
"required": ["name"],
},
}
)
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_confirm_throws_when_capability_is_missing(self):
"""Verifies confirm throws when elicitation is not supported."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all
)
session._set_capabilities({})
with pytest.raises(RuntimeError, match="not supported"):
await session.ui.confirm("Deploy?")
finally:
await client.force_stop()
# ============================================================================
# onElicitationContext (server → client callback)
# ============================================================================
class TestOnElicitationContext:
@pytest.mark.asyncio
async def test_sends_request_elicitation_flag_when_handler_provided(self):
"""Verifies requestElicitation=true is sent when onElicitationContext is provided."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
captured: dict = {}
original_request = client._client.request
async def mock_request(method, params):
captured[method] = params
return await original_request(method, params)
client._client.request = mock_request
async def elicitation_handler(
context: ElicitationContext,
) -> ElicitationResult:
return {"action": "accept", "content": {}}
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
on_elicitation_request=elicitation_handler,
)
assert session is not None
payload = captured["session.create"]
assert payload["requestElicitation"] is True
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_does_not_send_request_elicitation_when_no_handler(self):
"""Verifies requestElicitation=false when no handler is provided."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
captured: dict = {}
original_request = client._client.request
async def mock_request(method, params):
captured[method] = params
return await original_request(method, params)
client._client.request = mock_request
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
)
assert session is not None
payload = captured["session.create"]
assert payload["requestElicitation"] is False
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_sends_cancel_when_elicitation_handler_throws(self):
"""Verifies auto-cancel when the elicitation handler raises."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
async def bad_handler(
context: ElicitationContext,
) -> ElicitationResult:
raise RuntimeError("handler exploded")
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
on_elicitation_request=bad_handler,
)
rpc_calls: list[tuple] = []
original_request = client._client.request
async def mock_request(method, params):
if method == "session.ui.handlePendingElicitation":
rpc_calls.append((method, params))
return {"success": True}
return await original_request(method, params)
client._client.request = mock_request
# Call _handle_elicitation_request directly (as Node.js test does)
await session._handle_elicitation_request(
{"session_id": session.session_id, "message": "Pick a color"}, "req-123"
)
assert len(rpc_calls) >= 1
cancel_call = next(
(call for call in rpc_calls if call[1].get("result", {}).get("action") == "cancel"),
None,
)
assert cancel_call is not None
assert cancel_call[1]["requestId"] == "req-123"
assert cancel_call[1]["result"]["action"] == "cancel"
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_dispatches_elicitation_requested_event_to_handler(self):
"""Verifies that an elicitation.requested event dispatches to the handler."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
handler_calls: list = []
async def elicitation_handler(
context: ElicitationContext,
) -> ElicitationResult:
handler_calls.append(context)
return {"action": "accept", "content": {"color": "blue"}}
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
on_elicitation_request=elicitation_handler,
)
rpc_calls: list[tuple] = []
original_request = client._client.request
async def mock_request(method, params):
if method == "session.ui.handlePendingElicitation":
rpc_calls.append((method, params))
return {"success": True}
return await original_request(method, params)
client._client.request = mock_request
from copilot.generated.session_events import (
Data,
SessionEvent,
SessionEventType,
)
event = SessionEvent(
data=Data(
request_id="req-elicit-1",
message="Pick a color",
),
id="evt-elicit-1",
timestamp="2025-01-01T00:00:00Z",
type=SessionEventType.ELICITATION_REQUESTED,
ephemeral=True,
parent_id=None,
)
session._dispatch_event(event)
await asyncio.sleep(0.2)
assert len(handler_calls) == 1
assert handler_calls[0]["message"] == "Pick a color"
assert len(rpc_calls) >= 1
assert rpc_calls[0][1]["requestId"] == "req-elicit-1"
assert rpc_calls[0][1]["result"]["action"] == "accept"
finally:
await client.force_stop()
@pytest.mark.asyncio
async def test_elicitation_handler_receives_full_schema(self):
"""Verifies that requestedSchema passes type, properties, and required to handler."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
handler_calls: list = []
async def elicitation_handler(
context: ElicitationContext,
) -> ElicitationResult:
handler_calls.append(context)
return {"action": "cancel"}
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all,
on_elicitation_request=elicitation_handler,
)
original_request = client._client.request
async def mock_request(method, params):
if method == "session.ui.handlePendingElicitation":
return {"success": True}
return await original_request(method, params)
client._client.request = mock_request
from copilot.generated.session_events import (
Data,
RequestedSchema,
RequestedSchemaType,
SessionEvent,
SessionEventType,
)
event = SessionEvent(
data=Data(
request_id="req-schema-1",
message="Fill in your details",
requested_schema=RequestedSchema(
type=RequestedSchemaType.OBJECT,
properties={
"name": {"type": "string"},
"age": {"type": "number"},
},
required=["name", "age"],
),
),
id="evt-schema-1",
timestamp="2025-01-01T00:00:00Z",
type=SessionEventType.ELICITATION_REQUESTED,
ephemeral=True,
parent_id=None,
)
session._dispatch_event(event)
await asyncio.sleep(0.2)
assert len(handler_calls) == 1
schema = handler_calls[0].get("requestedSchema")
assert schema is not None, "Expected requestedSchema in handler call"
assert schema["type"] == "object"
assert "name" in schema["properties"]
assert "age" in schema["properties"]
assert schema["required"] == ["name", "age"]
finally:
await client.force_stop()
# ============================================================================
# Capabilities changed event
# ============================================================================
class TestCapabilitiesChanged:
@pytest.mark.asyncio
async def test_capabilities_changed_event_updates_session(self):
"""Verifies that a capabilities.changed event updates session capabilities."""
client = CopilotClient(SubprocessConfig(cli_path=CLI_PATH))
await client.start()
try:
session = await client.create_session(
on_permission_request=PermissionHandler.approve_all
)
session._set_capabilities({})
from copilot.generated.session_events import (
UI,
Data,
SessionEvent,
SessionEventType,
)
event = SessionEvent(
data=Data(ui=UI(elicitation=True)),
id="evt-cap-1",
timestamp="2025-01-01T00:00:00Z",
type=SessionEventType.CAPABILITIES_CHANGED,
ephemeral=True,
parent_id=None,
)
session._dispatch_event(event)
assert session.capabilities.get("ui", {}).get("elicitation") is True
finally:
await client.force_stop()