forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_steering.py
More file actions
563 lines (442 loc) · 17.3 KB
/
Copy pathtest_steering.py
File metadata and controls
563 lines (442 loc) · 17.3 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
"""
Unit tests for the steering module.
"""
import asyncio
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock
import pytest
from copilot.steering import (
ConversationManager,
MessageQueue,
Priority,
QueuedMessage,
QueueFullError,
ShutdownSentinel,
StreamingInputGenerator,
SHUTDOWN_SENTINEL,
)
class TestPriority:
def test_priority_ordering(self):
"""Test that priority values are ordered correctly."""
assert Priority.LOW.value == 0
assert Priority.NORMAL.value == 1
assert Priority.HIGH.value == 2
assert Priority.URGENT.value == 3
assert Priority.URGENT > Priority.HIGH > Priority.NORMAL > Priority.LOW
class TestQueuedMessage:
def test_creation(self):
"""Test basic message creation."""
msg = QueuedMessage(
request_id="test-1",
content="Hello",
priority=Priority.NORMAL,
session_id="session-1",
)
assert msg.request_id == "test-1"
assert msg.content == "Hello"
assert msg.priority == Priority.NORMAL
assert msg.session_id == "session-1"
assert isinstance(msg.queued_at, datetime)
def test_priority_comparison(self):
"""Test that higher priority messages sort first."""
low = QueuedMessage(
request_id="low",
content="Low",
priority=Priority.LOW,
session_id="s",
sequence_number=1,
)
normal = QueuedMessage(
request_id="normal",
content="Normal",
priority=Priority.NORMAL,
session_id="s",
sequence_number=2,
)
urgent = QueuedMessage(
request_id="urgent",
content="Urgent",
priority=Priority.URGENT,
session_id="s",
sequence_number=3,
)
# Higher priority should sort first (be "less than")
assert urgent < normal < low
assert not low < urgent
def test_fifo_within_same_priority(self):
"""Test FIFO ordering for messages with same priority."""
first = QueuedMessage(
request_id="first",
content="First",
priority=Priority.NORMAL,
session_id="s",
sequence_number=1,
)
second = QueuedMessage(
request_id="second",
content="Second",
priority=Priority.NORMAL,
session_id="s",
sequence_number=2,
)
# Earlier sequence should sort first
assert first < second
assert not second < first
def test_comparison_with_sentinel(self):
"""Test that messages sort before shutdown sentinel."""
msg = QueuedMessage(
request_id="msg",
content="Test",
priority=Priority.URGENT,
session_id="s",
)
assert msg < SHUTDOWN_SENTINEL
assert not SHUTDOWN_SENTINEL < msg
class TestShutdownSentinel:
def test_singleton(self):
"""Test that SHUTDOWN_SENTINEL is used consistently."""
assert isinstance(SHUTDOWN_SENTINEL, ShutdownSentinel)
def test_comparison_with_messages(self):
"""Test sentinel always sorts last."""
msg = QueuedMessage(
request_id="msg",
content="Test",
priority=Priority.LOW,
session_id="s",
)
assert msg < SHUTDOWN_SENTINEL
assert SHUTDOWN_SENTINEL > msg
assert not SHUTDOWN_SENTINEL < msg
def test_comparison_with_itself(self):
"""Test sentinel comparison with itself."""
sentinel1 = ShutdownSentinel()
sentinel2 = ShutdownSentinel()
assert not sentinel1 < sentinel2
assert sentinel1 <= sentinel2
assert sentinel1 >= sentinel2
class TestMessageQueue:
@pytest.mark.asyncio
async def test_put_and_get(self):
"""Test basic put and get operations."""
queue = MessageQueue(max_depth=10)
msg = QueuedMessage(
request_id="test",
content="Hello",
priority=Priority.NORMAL,
session_id="session-1",
)
await queue.put(msg)
assert queue.qsize() == 1
result = await queue.get()
assert result == msg
assert queue.qsize() == 0
@pytest.mark.asyncio
async def test_priority_ordering(self):
"""Test that messages are returned in priority order."""
queue = MessageQueue(max_depth=10)
low = QueuedMessage(
request_id="low",
content="Low",
priority=Priority.LOW,
session_id="s",
)
urgent = QueuedMessage(
request_id="urgent",
content="Urgent",
priority=Priority.URGENT,
session_id="s",
)
normal = QueuedMessage(
request_id="normal",
content="Normal",
priority=Priority.NORMAL,
session_id="s",
)
# Add in arbitrary order
await queue.put(low)
await queue.put(urgent)
await queue.put(normal)
# Should come out in priority order
assert (await queue.get()).request_id == "urgent"
assert (await queue.get()).request_id == "normal"
assert (await queue.get()).request_id == "low"
@pytest.mark.asyncio
async def test_queue_full_error(self):
"""Test that QueueFullError is raised when queue is full."""
queue = MessageQueue(max_depth=2)
msg1 = QueuedMessage(
request_id="1", content="1", priority=Priority.NORMAL, session_id="s"
)
msg2 = QueuedMessage(
request_id="2", content="2", priority=Priority.NORMAL, session_id="s"
)
msg3 = QueuedMessage(
request_id="3", content="3", priority=Priority.NORMAL, session_id="s"
)
await queue.put(msg1)
await queue.put(msg2)
with pytest.raises(QueueFullError):
await queue.put(msg3)
@pytest.mark.asyncio
async def test_shutdown_signal(self):
"""Test shutdown signaling."""
queue = MessageQueue()
assert not queue.is_shutdown()
queue.signal_shutdown()
assert queue.is_shutdown()
# Should be able to get the sentinel
result = await queue.get()
assert isinstance(result, ShutdownSentinel)
@pytest.mark.asyncio
async def test_empty_and_full(self):
"""Test empty and full properties."""
queue = MessageQueue(max_depth=2)
assert queue.empty()
assert not queue.full()
msg = QueuedMessage(
request_id="1", content="1", priority=Priority.NORMAL, session_id="s"
)
await queue.put(msg)
assert not queue.empty()
assert not queue.full()
msg2 = QueuedMessage(
request_id="2", content="2", priority=Priority.NORMAL, session_id="s"
)
await queue.put(msg2)
assert queue.full()
class TestStreamingInputGenerator:
@pytest.mark.asyncio
async def test_yields_messages(self):
"""Test that generator yields messages in correct format."""
queue = MessageQueue()
generator = StreamingInputGenerator(queue)
msg = QueuedMessage(
request_id="test-1",
content="Hello world",
priority=Priority.NORMAL,
session_id="session-123",
metadata={"custom": "value"},
)
await queue.put(msg)
queue.signal_shutdown()
messages = []
async for message in generator:
messages.append(message)
assert len(messages) == 1
assert messages[0]["type"] == "user"
assert messages[0]["message"]["role"] == "user"
assert messages[0]["message"]["content"] == "Hello world"
assert messages[0]["metadata"]["request_id"] == "test-1"
assert messages[0]["metadata"]["priority"] == "NORMAL"
assert messages[0]["metadata"]["session_id"] == "session-123"
assert messages[0]["metadata"]["custom"] == "value"
@pytest.mark.asyncio
async def test_stops_on_shutdown(self):
"""Test that generator stops when shutdown sentinel is received."""
queue = MessageQueue()
generator = StreamingInputGenerator(queue)
msg1 = QueuedMessage(
request_id="1", content="First", priority=Priority.NORMAL, session_id="s"
)
msg2 = QueuedMessage(
request_id="2", content="Second", priority=Priority.NORMAL, session_id="s"
)
await queue.put(msg1)
await queue.put(msg2)
queue.signal_shutdown()
messages = []
async for message in generator:
messages.append(message)
assert len(messages) == 2
@pytest.mark.asyncio
async def test_priority_order_preserved(self):
"""Test that messages come out in priority order."""
queue = MessageQueue()
generator = StreamingInputGenerator(queue)
low = QueuedMessage(
request_id="low", content="Low", priority=Priority.LOW, session_id="s"
)
urgent = QueuedMessage(
request_id="urgent",
content="Urgent",
priority=Priority.URGENT,
session_id="s",
)
await queue.put(low)
await queue.put(urgent)
queue.signal_shutdown()
messages = []
async for message in generator:
messages.append(message)
assert messages[0]["metadata"]["request_id"] == "urgent"
assert messages[1]["metadata"]["request_id"] == "low"
class TestConversationManager:
@pytest.mark.asyncio
async def test_queue_message(self):
"""Test queuing messages."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
mock_session.send = AsyncMock(return_value="msg-id")
manager = ConversationManager(mock_session)
request_id = await manager.queue_message("Hello", Priority.NORMAL)
assert request_id == "req-1"
assert manager.is_started
assert manager.queue_size >= 0 # May have been processed already
await manager.stop()
@pytest.mark.asyncio
async def test_auto_start(self):
"""Test that manager auto-starts on first message."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
mock_session.send = AsyncMock(return_value="msg-id")
manager = ConversationManager(mock_session)
assert not manager.is_started
await manager.queue_message("Hello", Priority.NORMAL)
assert manager.is_started
await manager.stop()
@pytest.mark.asyncio
async def test_custom_request_id(self):
"""Test using custom request ID."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
mock_session.send = AsyncMock(return_value="msg-id")
manager = ConversationManager(mock_session)
request_id = await manager.queue_message(
"Hello", Priority.NORMAL, request_id="custom-123"
)
assert request_id == "custom-123"
await manager.stop()
@pytest.mark.asyncio
async def test_stop_without_start(self):
"""Test that stop() works even if never started."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
manager = ConversationManager(mock_session)
await manager.stop() # Should not raise
@pytest.mark.asyncio
async def test_context_manager(self):
"""Test async context manager usage."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
mock_session.send = AsyncMock(return_value="msg-id")
async with ConversationManager(mock_session) as manager:
await manager.queue_message("Hello", Priority.NORMAL)
assert manager.is_started
# Should be stopped after exiting context
assert not manager.is_started
@pytest.mark.asyncio
async def test_message_sends_to_session(self):
"""Test that queued messages are sent to session."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
mock_session.send = AsyncMock(return_value="msg-id")
manager = ConversationManager(mock_session)
await manager.queue_message("Hello world", Priority.NORMAL)
# Give the processor task time to run
await asyncio.sleep(0.1)
# Verify send was called
mock_session.send.assert_called()
call_args = mock_session.send.call_args[0][0]
assert call_args["prompt"] == "Hello world"
await manager.stop()
@pytest.mark.asyncio
async def test_priority_processing_order(self):
"""Test that messages are processed in priority order."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
processed_prompts = []
async def capture_send(options):
processed_prompts.append(options["prompt"])
return "msg-id"
mock_session.send = capture_send
manager = ConversationManager(mock_session)
# Queue messages in arbitrary order
await manager.queue_message("Low priority", Priority.LOW)
await manager.queue_message("Urgent!", Priority.URGENT)
await manager.queue_message("Normal", Priority.NORMAL)
# Give processor time to work
await asyncio.sleep(0.2)
await manager.stop()
# Should be processed in priority order
assert processed_prompts == ["Urgent!", "Normal", "Low priority"]
@pytest.mark.asyncio
async def test_queue_full_error(self):
"""Test that QueueFullError is raised when queue is full."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
# Use a blocking send to keep the queue from draining
send_started = asyncio.Event()
send_continue = asyncio.Event()
async def blocking_send(options):
send_started.set()
await send_continue.wait()
return "msg-id"
mock_session.send = blocking_send
manager = ConversationManager(mock_session, max_queue_depth=2)
# Queue first message - this will be picked up by processor immediately
await manager.queue_message("1", Priority.NORMAL)
# Wait for send to start (message 1 is now being processed)
await send_started.wait()
# Now queue 2 more - these should fill the queue
await manager.queue_message("2", Priority.NORMAL)
await manager.queue_message("3", Priority.NORMAL)
# This should fail since queue is full and send is blocked
with pytest.raises(QueueFullError):
await manager.queue_message("4", Priority.NORMAL)
# Unblock and cleanup
send_continue.set()
await manager.stop(timeout=1.0)
@pytest.mark.asyncio
async def test_attachments_forwarded(self):
"""Test that attachments are forwarded to session."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
mock_session.send = AsyncMock(return_value="msg-id")
manager = ConversationManager(mock_session)
attachments = [{"type": "file", "path": "/test/file.py"}]
await manager.queue_message(
"Check this file", Priority.NORMAL, attachments=attachments
)
await asyncio.sleep(0.1)
mock_session.send.assert_called()
call_args = mock_session.send.call_args[0][0]
assert call_args["attachments"] == attachments
await manager.stop()
class TestYieldWhileProcessing:
"""Tests to verify the SDK can accept yields during processing (spec requirement)."""
@pytest.mark.asyncio
async def test_yield_while_processing(self):
"""Verify that new messages can be queued while previous ones are processing."""
mock_session = MagicMock()
mock_session.session_id = "test-session"
first_processing_started = asyncio.Event()
first_processing_done = asyncio.Event()
messages_yielded = []
call_count = 0
async def slow_send(options):
nonlocal call_count
call_count += 1
messages_yielded.append(options["prompt"])
if call_count == 1:
first_processing_started.set()
# Wait for the test to queue more messages
await first_processing_done.wait()
return "msg-id"
mock_session.send = slow_send
manager = ConversationManager(mock_session)
# Queue first message
await manager.queue_message("message 1", Priority.NORMAL)
# Wait for processing to start
await first_processing_started.wait()
# These yields must succeed while msg1 is still processing
await manager.queue_message("message 2", Priority.NORMAL)
await manager.queue_message("message 3", Priority.NORMAL)
# Verify queue accepted the messages (non-blocking put)
assert manager.queue_size >= 2
# Let first processing complete
first_processing_done.set()
# Give time for all messages to process
await asyncio.sleep(0.3)
await manager.stop()
# All messages should have been processed
assert messages_yielded == ["message 1", "message 2", "message 3"]