-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathTestHelper.cs
More file actions
233 lines (204 loc) · 8.98 KB
/
Copy pathTestHelper.cs
File metadata and controls
233 lines (204 loc) · 8.98 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
namespace GitHub.Copilot.Test.Harness;
public static class TestHelper
{
// Default tolerates CLI / replay-proxy cold start on Windows GitHub Actions
// runners, where the first test in a fixture can take ~60s before the first
// assistant message arrives. Subsequent tests in the same fixture typically
// complete in well under a second.
private static readonly TimeSpan DefaultEventTimeout = TimeSpan.FromSeconds(120);
private static readonly TimeSpan DefaultPollInterval = TimeSpan.FromMilliseconds(100);
public static async Task<AssistantMessageEvent?> GetFinalAssistantMessageAsync(
CopilotSession session,
TimeSpan? timeout = null,
bool alreadyIdle = false)
{
var tcs = new TaskCompletionSource<AssistantMessageEvent>(TaskCreationOptions.RunContinuationsAsynchronously);
using var cts = new CancellationTokenSource(timeout ?? DefaultEventTimeout);
// Both `finalAssistantMessage` and `sawIdle` are set from two threads — the
// subscription callback (CLI read loop) and CheckExistingMessagesAsync (RPC reply).
// We complete only once we've observed both, regardless of which path saw which.
var stateLock = new object();
AssistantMessageEvent? finalAssistantMessage = null;
bool sawIdle = false;
void TryComplete()
{
AssistantMessageEvent? snapshot;
bool idle;
lock (stateLock)
{
snapshot = finalAssistantMessage;
idle = sawIdle;
}
if (snapshot != null && idle) tcs.TrySetResult(snapshot);
}
using var subscription = session.On<SessionEvent>(evt =>
{
switch (evt)
{
case AssistantMessageEvent msg:
lock (stateLock) { finalAssistantMessage = msg; }
TryComplete();
break;
case SessionIdleEvent:
lock (stateLock) { sawIdle = true; }
TryComplete();
break;
case SessionErrorEvent error:
tcs.TrySetException(new Exception(error.Data.Message ?? "session error"));
break;
}
});
// Backfill from already-delivered messages so we don't lose events that arrived
// between SendAsync returning and the subscription being installed. Run it
// concurrently with the live subscription, but keep the Task observable so any
// exception is propagated through tcs (not the unobserved-task handler) and so
// we can drain it deterministically below. Pass cts.Token so the backfill is
// bounded by the same timeout as the wait itself, and so a hung GetEventsAsync
// can't block the drain in `finally`.
var backfill = CheckExistingMessagesAsync(cts.Token);
using var registration = cts.Token.Register(
static state => ((TaskCompletionSource<AssistantMessageEvent>)state!).TrySetException(
new TimeoutException("Timeout waiting for assistant message")),
tcs);
try
{
return await tcs.Task;
}
finally
{
// Drain the backfill before our `using` scopes (cts, subscription) dispose.
// Any exception was already routed through tcs above, so swallow here.
try { await backfill.ConfigureAwait(false); }
catch (Exception) { /* intentionally ignored: already propagated via tcs */ }
}
async Task CheckExistingMessagesAsync(CancellationToken cancellationToken)
{
try
{
var (existingFinal, existingIdle) = await GetExistingMessagesAsync(session, alreadyIdle, cancellationToken);
lock (stateLock)
{
// Preserve a newer message captured by the subscription in the meantime.
if (existingFinal != null && finalAssistantMessage == null)
{
finalAssistantMessage = existingFinal;
}
if (existingIdle) sawIdle = true;
}
TryComplete();
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
}
private static async Task<(AssistantMessageEvent? Final, bool SawIdle)> GetExistingMessagesAsync(CopilotSession session, bool alreadyIdle, CancellationToken cancellationToken = default)
{
var messages = (await session.GetEventsAsync(cancellationToken)).ToList();
var lastUserIdx = messages.FindLastIndex(m => m is UserMessageEvent);
var currentTurn = lastUserIdx < 0 ? messages : messages.Skip(lastUserIdx).ToList();
var error = currentTurn.OfType<SessionErrorEvent>().FirstOrDefault();
if (error != null) throw new Exception(error.Data.Message ?? "session error");
var idleIdx = alreadyIdle ? currentTurn.Count : currentTurn.FindIndex(m => m is SessionIdleEvent);
var sawIdle = alreadyIdle || idleIdx >= 0;
// Find the most recent assistant message in the turn (whether idle has arrived or not).
var searchEnd = idleIdx >= 0 ? idleIdx : currentTurn.Count;
for (var i = searchEnd - 1; i >= 0; i--)
{
if (currentTurn[i] is AssistantMessageEvent msg)
return (msg, sawIdle);
}
return (null, sawIdle);
}
public static async Task<T> GetNextEventOfTypeAsync<T>(
CopilotSession session,
TimeSpan? timeout = null) where T : SessionEvent
=> await GetNextEventOfTypeAsync<T>(session, static _ => true, timeout);
public static async Task<T> GetNextEventOfTypeAsync<T>(
CopilotSession session,
Func<T, bool> predicate,
TimeSpan? timeout = null,
string? timeoutDescription = null) where T : SessionEvent
{
var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
using var cts = new CancellationTokenSource(timeout ?? DefaultEventTimeout);
using var subscription = session.On<SessionEvent>(evt =>
{
if (evt is T matched && predicate(matched))
{
tcs.TrySetResult(matched);
}
else if (evt is SessionErrorEvent error)
{
tcs.TrySetException(new Exception(error.Data.Message ?? "session error"));
}
});
cts.Token.Register(() => tcs.TrySetException(
new TimeoutException($"Timeout waiting for {timeoutDescription ?? $"event of type '{typeof(T).Name}'"}")));
return await tcs.Task;
}
public static Task WaitForConditionAsync(
Func<bool> condition,
TimeSpan? timeout = null,
string? timeoutMessage = null,
TimeSpan? pollInterval = null)
=> WaitForConditionAsync(
() => Task.FromResult(condition()),
timeout,
timeoutMessage,
transientExceptionFilter: null,
pollInterval);
public static async Task WaitForConditionAsync(
Func<Task<bool>> condition,
TimeSpan? timeout = null,
string? timeoutMessage = null,
Func<Exception, bool>? transientExceptionFilter = null,
TimeSpan? pollInterval = null)
{
using var cts = new CancellationTokenSource(timeout ?? DefaultEventTimeout);
Exception? lastTransientException = null;
while (true)
{
try
{
if (await condition())
{
return;
}
lastTransientException = null;
}
catch (Exception ex) when (transientExceptionFilter?.Invoke(ex) == true)
{
lastTransientException = ex;
}
try
{
await Task.Delay(pollInterval ?? DefaultPollInterval, cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
break;
}
}
try
{
if (await condition())
{
return;
}
}
catch (Exception ex) when (transientExceptionFilter?.Invoke(ex) == true)
{
lastTransientException = ex;
}
throw lastTransientException is null
? new TimeoutException(timeoutMessage ?? "Timed out waiting for condition.")
: new TimeoutException(timeoutMessage ?? "Timed out waiting for condition.", lastTransientException);
}
public static bool IsTransientFileSystemException(Exception exception)
=> exception is IOException or UnauthorizedAccessException;
}