-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathsession.test.ts
More file actions
524 lines (434 loc) · 22 KB
/
session.test.ts
File metadata and controls
524 lines (434 loc) · 22 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
import { rm } from "fs/promises";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { ParsedHttpExchange } from "../../../test/harness/replayingCapiProxy.js";
import { CopilotClient, approveAll } from "../../src/index.js";
import { createSdkTestContext, isCI } from "./harness/sdkTestContext.js";
import { getFinalAssistantMessage, getNextEventOfType } from "./harness/sdkTestHelper.js";
describe("Sessions", async () => {
const { copilotClient: client, openAiEndpoint, homeDir, env } = await createSdkTestContext();
it("should create and disconnect sessions", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "fake-test-model",
});
expect(session.sessionId).toMatch(/^[a-f0-9-]+$/);
const allEvents = await session.getMessages();
const sessionStartEvents = allEvents.filter((e) => e.type === "session.start");
expect(sessionStartEvents).toMatchObject([
{
type: "session.start",
data: { sessionId: session.sessionId, selectedModel: "fake-test-model" },
},
]);
await session.disconnect();
await expect(() => session.getMessages()).rejects.toThrow(/Session not found/);
});
// TODO: Re-enable once test harness CAPI proxy supports this test's session lifecycle
it.skip("should list sessions with context field", { timeout: 60000 }, async () => {
// Create a session — just creating it is enough for it to appear in listSessions
const session = await client.createSession({ onPermissionRequest: approveAll });
expect(session.sessionId).toMatch(/^[a-f0-9-]+$/);
// Verify it has a start event (confirms session is active)
const messages = await session.getMessages();
expect(messages.length).toBeGreaterThan(0);
// List sessions and find the one we just created
const sessions = await client.listSessions();
const ourSession = sessions.find((s) => s.sessionId === session.sessionId);
expect(ourSession).toBeDefined();
// Context may not be populated if workspace.yaml hasn't been written yet
if (ourSession?.context) {
expect(ourSession.context.cwd).toMatch(/^(\/|[A-Za-z]:)/);
}
});
// TODO: Re-enable once test harness CAPI proxy supports this test's session lifecycle
it.skip("should get session metadata by ID", { timeout: 60000 }, async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
expect(session.sessionId).toMatch(/^[a-f0-9-]+$/);
// Get metadata for the session we just created
const metadata = await client.getSessionMetadata(session.sessionId);
expect(metadata).toBeDefined();
expect(metadata!.sessionId).toBe(session.sessionId);
expect(metadata!.startTime).toBeInstanceOf(Date);
expect(metadata!.modifiedTime).toBeInstanceOf(Date);
expect(typeof metadata!.isRemote).toBe("boolean");
// Verify non-existent session returns undefined
const notFound = await client.getSessionMetadata("non-existent-session-id");
expect(notFound).toBeUndefined();
});
it("should have stateful conversation", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const assistantMessage = await session.sendAndWait({ prompt: "What is 1+1?" });
expect(assistantMessage?.data.content).toContain("2");
const secondAssistantMessage = await session.sendAndWait({
prompt: "Now if you double that, what do you get?",
});
expect(secondAssistantMessage?.data.content).toContain("4");
});
it("should create a session with appended systemMessage config", async () => {
const systemMessageSuffix = "End each response with the phrase 'Have a nice day!'";
const session = await client.createSession({
onPermissionRequest: approveAll,
systemMessage: {
mode: "append",
content: systemMessageSuffix,
},
});
const assistantMessage = await session.sendAndWait({ prompt: "What is your full name?" });
expect(assistantMessage?.data.content).toContain("GitHub");
expect(assistantMessage?.data.content).toContain("Have a nice day!");
// Also validate the underlying traffic
const traffic = await openAiEndpoint.getExchanges();
const systemMessage = getSystemMessage(traffic[0]);
expect(systemMessage).toContain("GitHub");
expect(systemMessage).toContain(systemMessageSuffix);
});
it("should create a session with replaced systemMessage config", async () => {
const testSystemMessage = "You are an assistant called Testy McTestface. Reply succinctly.";
const session = await client.createSession({
onPermissionRequest: approveAll,
systemMessage: { mode: "replace", content: testSystemMessage },
});
const assistantMessage = await session.sendAndWait({ prompt: "What is your full name?" });
expect(assistantMessage?.data.content).not.toContain("GitHub");
expect(assistantMessage?.data.content).toContain("Testy");
// Also validate the underlying traffic
const traffic = await openAiEndpoint.getExchanges();
const systemMessage = getSystemMessage(traffic[0]);
expect(systemMessage).toEqual(testSystemMessage); // Exact match
});
it("should create a session with customized systemMessage config", async () => {
const customTone = "Respond in a warm, professional tone. Be thorough in explanations.";
const appendedContent = "Always mention quarterly earnings.";
const session = await client.createSession({
onPermissionRequest: approveAll,
systemMessage: {
mode: "customize",
sections: {
tone: { action: "replace", content: customTone },
code_change_rules: { action: "remove" },
},
content: appendedContent,
},
});
const assistantMessage = await session.sendAndWait({ prompt: "Who are you?" });
expect(assistantMessage?.data.content).toBeDefined();
// Validate the system message sent to the model
const traffic = await openAiEndpoint.getExchanges();
const systemMessage = getSystemMessage(traffic[0]);
expect(systemMessage).toContain(customTone);
expect(systemMessage).toContain(appendedContent);
// The code_change_rules section should have been removed
expect(systemMessage).not.toContain("<code_change_instructions>");
});
it("should create a session with availableTools", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
availableTools: ["view", "edit"],
});
await session.sendAndWait({ prompt: "What is 1+1?" });
// It only tells the model about the specified tools and no others
const traffic = await openAiEndpoint.getExchanges();
expect(traffic[0].request.tools).toMatchObject([
{ function: { name: "view" } },
{ function: { name: "edit" } },
]);
});
it("should create a session with excludedTools", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
excludedTools: ["view"],
});
await session.sendAndWait({ prompt: "What is 1+1?" });
// It has other tools, but not the one we excluded
const traffic = await openAiEndpoint.getExchanges();
const functionNames = traffic[0].request.tools?.map(
(t) => (t as { function: { name: string } }).function.name
);
expect(functionNames).toContain("edit");
expect(functionNames).toContain("grep");
expect(functionNames).not.toContain("view");
});
// TODO: This test shows there's a race condition inside client.ts. If createSession is called
// concurrently and autoStart is on, it may start multiple child processes. This needs to be fixed.
// Right now it manifests as being unable to delete the temp directories during afterAll even though
// we stopped all the clients (one or more child processes were left orphaned).
it.skip("should handle multiple concurrent sessions", async () => {
const [s1, s2, s3] = await Promise.all([
client.createSession({ onPermissionRequest: approveAll }),
client.createSession({ onPermissionRequest: approveAll }),
client.createSession({ onPermissionRequest: approveAll }),
]);
// All sessions should have unique IDs
const distinctSessionIds = new Set([s1.sessionId, s2.sessionId, s3.sessionId]);
expect(distinctSessionIds.size).toBe(3);
// All are connected
for (const s of [s1, s2, s3]) {
expect(await s.getMessages()).toMatchObject([
{
type: "session.start",
data: { sessionId: s.sessionId },
},
]);
}
// All can be disconnected
await Promise.all([s1.disconnect(), s2.disconnect(), s3.disconnect()]);
for (const s of [s1, s2, s3]) {
await expect(() => s.getMessages()).rejects.toThrow(/Session not found/);
}
});
it("should resume a session using the same client", async () => {
// Create initial session
const session1 = await client.createSession({ onPermissionRequest: approveAll });
const sessionId = session1.sessionId;
const answer = await session1.sendAndWait({ prompt: "What is 1+1?" });
expect(answer?.data.content).toContain("2");
// Resume using the same client
const session2 = await client.resumeSession(sessionId, { onPermissionRequest: approveAll });
expect(session2.sessionId).toBe(sessionId);
const messages = await session2.getMessages();
const assistantMessages = messages.filter((m) => m.type === "assistant.message");
expect(assistantMessages[assistantMessages.length - 1].data.content).toContain("2");
// Can continue the conversation statefully
const secondAssistantMessage = await session2.sendAndWait({
prompt: "Now if you double that, what do you get?",
});
expect(secondAssistantMessage?.data.content).toContain("4");
});
it("should resume a session using a new client", async () => {
// Create initial session
const session1 = await client.createSession({ onPermissionRequest: approveAll });
const sessionId = session1.sessionId;
const answer = await session1.sendAndWait({ prompt: "What is 1+1?" });
expect(answer?.data.content).toContain("2");
// Resume using a new client
const newClient = new CopilotClient({
env,
githubToken: isCI ? "fake-token-for-e2e-tests" : undefined,
});
onTestFinished(() => newClient.forceStop());
const session2 = await newClient.resumeSession(sessionId, {
onPermissionRequest: approveAll,
});
expect(session2.sessionId).toBe(sessionId);
// TODO: There's an inconsistency here. When resuming with a new client, we don't see
// the session.idle message in the history, which means we can't use getFinalAssistantMessage.
const messages = await session2.getMessages();
expect(messages).toContainEqual(expect.objectContaining({ type: "user.message" }));
expect(messages).toContainEqual(expect.objectContaining({ type: "session.resume" }));
// Can continue the conversation statefully
const secondAssistantMessage = await session2.sendAndWait({
prompt: "Now if you double that, what do you get?",
});
expect(secondAssistantMessage?.data.content).toContain("4");
});
it("should throw error when resuming non-existent session", async () => {
await expect(
client.resumeSession("non-existent-session-id", { onPermissionRequest: approveAll })
).rejects.toThrow();
});
it("should create session with custom tool", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
tools: [
{
name: "get_secret_number",
description: "Gets the secret number",
parameters: {
type: "object",
properties: {
key: { type: "string", description: "Key" },
},
required: ["key"],
},
// Shows that raw JSON schemas still work - Zod is optional
handler: async (args: { key: string }) => {
return {
textResultForLlm: args.key === "ALPHA" ? "54321" : "unknown",
resultType: "success" as const,
};
},
},
],
});
const answer = await session.sendAndWait({
prompt: "What is the secret number for key ALPHA?",
});
expect(answer?.data.content).toContain("54321");
});
it("should resume session with a custom provider", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const sessionId = session.sessionId;
// Resume the session with a provider
const session2 = await client.resumeSession(sessionId, {
onPermissionRequest: approveAll,
provider: {
type: "openai",
baseUrl: "https://api.openai.com/v1",
apiKey: "fake-key",
},
});
expect(session2.sessionId).toBe(sessionId);
});
it("should abort a session", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
// Set up event listeners BEFORE sending to avoid race conditions
const nextToolCallStart = getNextEventOfType(session, "tool.execution_start");
const nextSessionIdle = getNextEventOfType(session, "session.idle");
await session.send({
prompt: "run the shell command 'sleep 100' (note this works on both bash and PowerShell)",
});
// Abort once we see a tool execution start
await nextToolCallStart;
await session.abort();
await nextSessionIdle;
// The session should still be alive and usable after abort
const messages = await session.getMessages();
expect(messages.length).toBeGreaterThan(0);
expect(messages.some((m) => m.type === "abort")).toBe(true);
// We should be able to send another message
const answer = await session.sendAndWait({ prompt: "What is 2+2?" });
expect(answer?.data.content).toContain("4");
});
it("should receive session events", async () => {
// Use onEvent to capture events dispatched during session creation.
// session.start is emitted during the session.create RPC; if the session
// weren't registered in the sessions map before the RPC, it would be dropped.
const earlyEvents: Array<{ type: string }> = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
onEvent: (event) => {
earlyEvents.push(event);
},
});
expect(earlyEvents.some((e) => e.type === "session.start")).toBe(true);
const receivedEvents: Array<{ type: string }> = [];
session.on((event) => {
receivedEvents.push(event);
});
// Send a message and wait for completion
const assistantMessage = await session.sendAndWait({ prompt: "What is 100+200?" });
// Should have received multiple events
expect(receivedEvents.length).toBeGreaterThan(0);
expect(receivedEvents.some((e) => e.type === "user.message")).toBe(true);
expect(receivedEvents.some((e) => e.type === "assistant.message")).toBe(true);
expect(receivedEvents.some((e) => e.type === "session.idle")).toBe(true);
// Verify the assistant response contains the expected answer
expect(assistantMessage?.data.content).toContain("300");
});
it("should create session with custom config dir", async () => {
const customConfigDir = `${homeDir}/custom-config`;
onTestFinished(async () => {
await rm(customConfigDir, { recursive: true, force: true }).catch(() => {});
});
const session = await client.createSession({
onPermissionRequest: approveAll,
configDir: customConfigDir,
});
expect(session.sessionId).toMatch(/^[a-f0-9-]+$/);
// Session should work normally with custom config dir
await session.send({ prompt: "What is 1+1?" });
const assistantMessage = await getFinalAssistantMessage(session);
expect(assistantMessage.data.content).toContain("2");
});
it("should log messages at all levels and emit matching session events", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const events: Array<{ type: string; id?: string; data?: Record<string, unknown> }> = [];
session.on((event) => {
events.push(event as (typeof events)[number]);
});
await session.log("Info message");
await session.log("Warning message", { level: "warning" });
await session.log("Error message", { level: "error" });
await session.log("Ephemeral message", { ephemeral: true });
await vi.waitFor(
() => {
const notifications = events.filter(
(e) =>
e.data &&
("infoType" in e.data || "warningType" in e.data || "errorType" in e.data)
);
expect(notifications).toHaveLength(4);
},
{ timeout: 10_000 }
);
const byMessage = (msg: string) => events.find((e) => e.data?.message === msg)!;
expect(byMessage("Info message").type).toBe("session.info");
expect(byMessage("Info message").data).toEqual({
infoType: "notification",
message: "Info message",
});
expect(byMessage("Warning message").type).toBe("session.warning");
expect(byMessage("Warning message").data).toEqual({
warningType: "notification",
message: "Warning message",
});
expect(byMessage("Error message").type).toBe("session.error");
expect(byMessage("Error message").data).toEqual({
errorType: "notification",
message: "Error message",
});
expect(byMessage("Ephemeral message").type).toBe("session.info");
expect(byMessage("Ephemeral message").data).toEqual({
infoType: "notification",
message: "Ephemeral message",
});
});
});
function getSystemMessage(exchange: ParsedHttpExchange): string | undefined {
const systemMessage = exchange.request.messages.find((m) => m.role === "system") as
| { role: "system"; content: string }
| undefined;
return systemMessage?.content;
}
describe("Send Blocking Behavior", async () => {
// Tests for Issue #17: send() should return immediately, not block until turn completes
const { copilotClient: client } = await createSdkTestContext();
it("send returns immediately while events stream in background", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
});
const events: string[] = [];
session.on((event) => {
events.push(event.type);
});
// Use a slow command so we can verify send() returns before completion
await session.send({ prompt: "Run 'sleep 2 && echo done'" });
// send() should return before turn completes (no session.idle yet)
expect(events).not.toContain("session.idle");
// Wait for turn to complete
const message = await getFinalAssistantMessage(session);
expect(message.data.content).toContain("done");
expect(events).toContain("session.idle");
expect(events).toContain("assistant.message");
});
it("sendAndWait blocks until session.idle and returns final assistant message", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const events: string[] = [];
session.on((event) => {
events.push(event.type);
});
const response = await session.sendAndWait({ prompt: "What is 2+2?" });
expect(response).toBeDefined();
expect(response?.type).toBe("assistant.message");
expect(response?.data.content).toContain("4");
expect(events).toContain("session.idle");
expect(events).toContain("assistant.message");
});
// This test validates client-side timeout behavior.
// The snapshot has no assistant response since we expect timeout before completion.
it("sendAndWait throws on timeout", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
// Use a slow command to ensure timeout triggers before completion
await expect(
session.sendAndWait({ prompt: "Run 'sleep 2 && echo done'" }, 100)
).rejects.toThrow(/Timeout after 100ms/);
});
it("should set model with reasoningEffort", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const modelChangePromise = getNextEventOfType(session, "session.model_change");
await session.setModel("gpt-4.1", { reasoningEffort: "high" });
const event = await modelChangePromise;
expect(event.data.newModel).toBe("gpt-4.1");
expect(event.data.reasoningEffort).toBe("high");
});
});