-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathsession_config.e2e.test.ts
More file actions
454 lines (373 loc) · 17.6 KB
/
session_config.e2e.test.ts
File metadata and controls
454 lines (373 loc) · 17.6 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
import { describe, expect, it } from "vitest";
import { writeFile, mkdir } from "fs/promises";
import { join } from "path";
import { approveAll } from "../../src/index.js";
import { createSdkTestContext } from "./harness/sdkTestContext.js";
import { retry } from "./harness/sdkTestHelper.js";
describe("Session Configuration", async () => {
const { copilotClient: client, workDir, openAiEndpoint } = await createSdkTestContext();
async function waitForExchanges(minimumCount = 1) {
await retry(
`capture ${minimumCount} chat completion request(s)`,
async () => {
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBeGreaterThanOrEqual(minimumCount);
},
1_200
);
return openAiEndpoint.getExchanges();
}
it("should use workingDirectory for tool execution", async () => {
const subDir = join(workDir, "subproject");
await mkdir(subDir, { recursive: true });
await writeFile(join(subDir, "marker.txt"), "I am in the subdirectory");
const session = await client.createSession({
onPermissionRequest: approveAll,
workingDirectory: subDir,
});
const assistantMessage = await session.sendAndWait({
prompt: "Read the file marker.txt and tell me what it says",
});
expect(assistantMessage?.data.content).toContain("subdirectory");
await session.disconnect();
});
it("should create session with custom provider config", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
provider: {
baseUrl: "https://api.example.com/v1",
apiKey: "test-key",
},
});
expect(session.sessionId).toMatch(/^[a-f0-9-]+$/);
try {
await session.disconnect();
} catch {
// disconnect may fail since the provider is fake
}
});
it("should accept blob attachments", async () => {
// Write the image to disk so the model can view it if it tries
const pngBase64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
await writeFile(join(workDir, "pixel.png"), Buffer.from(pngBase64, "base64"));
const session = await client.createSession({ onPermissionRequest: approveAll });
await session.sendAndWait({
prompt: "What color is this pixel? Reply in one word.",
attachments: [
{
type: "blob",
data: pngBase64,
mimeType: "image/png",
displayName: "pixel.png",
},
],
});
await session.disconnect();
});
it("should accept message attachments", async () => {
await writeFile(join(workDir, "attached.txt"), "This file is attached");
const session = await client.createSession({ onPermissionRequest: approveAll });
await session.sendAndWait({
prompt: "Summarize the attached file",
attachments: [{ type: "file", path: join(workDir, "attached.txt") }],
});
await session.disconnect();
});
const PNG_1X1 = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64"
);
const VIEW_IMAGE_PROMPT =
"Use the view tool to look at the file test.png and describe what you see";
function hasImageUrlContent(messages: Array<{ role: string; content: unknown }>): boolean {
return messages.some(
(m) =>
m.role === "user" &&
Array.isArray(m.content) &&
m.content.some((p: { type: string }) => p.type === "image_url")
);
}
it("vision disabled then enabled via setModel", async () => {
await writeFile(join(workDir, "test.png"), PNG_1X1);
const session = await client.createSession({
onPermissionRequest: approveAll,
modelCapabilities: { supports: { vision: false } },
});
// Turn 1: vision off — no image_url expected
await session.sendAndWait({ prompt: VIEW_IMAGE_PROMPT });
const trafficAfterT1 = await openAiEndpoint.getExchanges();
const t1Messages = trafficAfterT1.flatMap((e) => e.request.messages ?? []);
expect(hasImageUrlContent(t1Messages)).toBe(false);
// Switch vision on (re-specify same model with updated capabilities)
await session.setModel("claude-sonnet-4.5", {
modelCapabilities: { supports: { vision: true } },
});
// Turn 2: vision on — image_url expected
await session.sendAndWait({ prompt: VIEW_IMAGE_PROMPT });
const trafficAfterT2 = await openAiEndpoint.getExchanges();
// Only check exchanges added after turn 1
const newExchanges = trafficAfterT2.slice(trafficAfterT1.length);
const t2Messages = newExchanges.flatMap((e) => e.request.messages ?? []);
expect(hasImageUrlContent(t2Messages)).toBe(true);
await session.disconnect();
});
it("vision enabled then disabled via setModel", async () => {
await writeFile(join(workDir, "test.png"), PNG_1X1);
const session = await client.createSession({
onPermissionRequest: approveAll,
modelCapabilities: { supports: { vision: true } },
});
// Turn 1: vision on — image_url expected
await session.sendAndWait({ prompt: VIEW_IMAGE_PROMPT });
const trafficAfterT1 = await openAiEndpoint.getExchanges();
const t1Messages = trafficAfterT1.flatMap((e) => e.request.messages ?? []);
expect(hasImageUrlContent(t1Messages)).toBe(true);
// Switch vision off
await session.setModel("claude-sonnet-4.5", {
modelCapabilities: { supports: { vision: false } },
});
// Turn 2: vision off — no image_url expected in new exchanges
await session.sendAndWait({ prompt: VIEW_IMAGE_PROMPT });
const trafficAfterT2 = await openAiEndpoint.getExchanges();
const newExchanges = trafficAfterT2.slice(trafficAfterT1.length);
const t2Messages = newExchanges.flatMap((e) => e.request.messages ?? []);
expect(hasImageUrlContent(t2Messages)).toBe(false);
await session.disconnect();
});
const PROVIDER_HEADER_NAME = "x-copilot-sdk-provider-header";
const CLIENT_NAME = "ts-public-surface-client";
function createProxyProvider(headerValue: string) {
return {
type: "openai" as const,
baseUrl: openAiEndpoint.url,
apiKey: "test-provider-key",
headers: {
[PROVIDER_HEADER_NAME]: headerValue,
},
};
}
function getHeaderString(
headers: Record<string, string | string[] | undefined> | undefined,
name: string
): string | undefined {
if (!headers) {
return undefined;
}
const matchingKey = Object.keys(headers).find(
(k) => k.toLowerCase() === name.toLowerCase()
);
if (!matchingKey) {
return undefined;
}
const value = headers[matchingKey];
if (Array.isArray(value)) {
return value.join(",");
}
return value ?? "";
}
function getSystemMessage(exchange: {
request: { messages?: Array<{ role: string; content: unknown }> };
}): string | undefined {
const sys = (exchange.request.messages ?? []).find((m) => m.role === "system") as
| { content: string }
| undefined;
return sys?.content;
}
function getToolNames(exchange: {
request: { tools?: Array<{ function: { name: string } }> };
}): string[] {
return (exchange.request.tools ?? []).map((t) => t.function.name);
}
it("should apply instructionDirectories on session create", async () => {
const projectDir = join(workDir, "instruction-create-project");
const instructionDir = join(workDir, "extra-create-instructions");
const instructionFilesDir = join(instructionDir, ".github", "instructions");
const sentinel = "TS_CREATE_INSTRUCTION_DIRECTORIES_SENTINEL";
await mkdir(projectDir, { recursive: true });
await mkdir(instructionFilesDir, { recursive: true });
await writeFile(
join(instructionFilesDir, "extra.instructions.md"),
`Always include ${sentinel}.`
);
const session = await client.createSession({
onPermissionRequest: approveAll,
workingDirectory: projectDir,
instructionDirectories: [instructionDir],
});
await session.sendAndWait({ prompt: "What is 1+1?" });
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBeGreaterThan(0);
const sys = getSystemMessage(exchanges[exchanges.length - 1]);
expect(sys).toContain(sentinel);
await session.disconnect();
});
it("should apply instructionDirectories on session resume", async () => {
const projectDir = join(workDir, "instruction-resume-project");
const instructionDir = join(workDir, "extra-resume-instructions");
const instructionFilesDir = join(instructionDir, ".github", "instructions");
const sentinel = "TS_RESUME_INSTRUCTION_DIRECTORIES_SENTINEL";
await mkdir(projectDir, { recursive: true });
await mkdir(instructionFilesDir, { recursive: true });
await writeFile(
join(instructionFilesDir, "extra.instructions.md"),
`Always include ${sentinel}.`
);
const session1 = await client.createSession({
onPermissionRequest: approveAll,
workingDirectory: projectDir,
});
const session2 = await client.resumeSession(session1.sessionId, {
onPermissionRequest: approveAll,
workingDirectory: projectDir,
instructionDirectories: [instructionDir],
});
await session2.sendAndWait({ prompt: "What is 1+1?" });
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBeGreaterThan(0);
const sys = getSystemMessage(exchanges[exchanges.length - 1]);
expect(sys).toContain(sentinel);
await session2.disconnect();
await session1.disconnect();
});
it("should forward clientName in user-agent", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
clientName: CLIENT_NAME,
});
await session.sendAndWait({ prompt: "What is 1+1?" });
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBeGreaterThan(0);
const userAgent = getHeaderString(exchanges[0].requestHeaders, "user-agent");
expect(userAgent).toBeDefined();
expect(userAgent).toContain(CLIENT_NAME);
await session.disconnect();
});
it("should forward custom provider headers on create", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
provider: createProxyProvider("create-provider-header"),
});
const message = await session.sendAndWait({ prompt: "What is 1+1?" });
expect(message?.data.content ?? "").toContain("2");
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBeGreaterThan(0);
const auth = getHeaderString(exchanges[0].requestHeaders, "authorization");
expect(auth).toContain("Bearer test-provider-key");
const customHeader = getHeaderString(exchanges[0].requestHeaders, PROVIDER_HEADER_NAME);
expect(customHeader).toContain("create-provider-header");
await session.disconnect();
});
it("should forward custom provider headers on resume", async () => {
const session1 = await client.createSession({ onPermissionRequest: approveAll });
const sessionId = session1.sessionId;
const session2 = await client.resumeSession(sessionId, {
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
provider: createProxyProvider("resume-provider-header"),
});
const message = await session2.sendAndWait({ prompt: "What is 2+2?" });
expect(message?.data.content ?? "").toContain("4");
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBeGreaterThan(0);
const lastExchange = exchanges[exchanges.length - 1];
const auth = getHeaderString(lastExchange.requestHeaders, "authorization");
expect(auth).toContain("Bearer test-provider-key");
const customHeader = getHeaderString(lastExchange.requestHeaders, PROVIDER_HEADER_NAME);
expect(customHeader).toContain("resume-provider-header");
await session2.disconnect();
});
it("should forward provider wire model", async () => {
// Verifies that ProviderConfig.wireModel overrides the model name sent to
// the provider API, while SessionConfig.model still drives runtime
// configuration lookup (capabilities, prompts, reasoning behavior).
// maxOutputTokens is also set here to confirm the SDK accepts it without
// serialization errors; the CLI does not echo it as `max_tokens` on the
// OpenAI-style wire request, so we don't assert on it directly (see unit
// tests for serialization coverage).
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
provider: {
type: "openai",
baseUrl: openAiEndpoint.url,
apiKey: "test-provider-key",
wireModel: "test-wire-model",
maxOutputTokens: 1024,
},
});
await session.sendAndWait({ prompt: "What is 1+1?" });
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBe(1);
expect(exchanges[0].request.model).toBe("test-wire-model");
await session.disconnect();
});
it("should use provider model id as wire model", async () => {
// ProviderConfig.modelId drives both the runtime resolved model AND the wire
// model when wireModel is not specified. SessionConfig.model is intentionally
// omitted so that modelId is the only model source.
const session = await client.createSession({
onPermissionRequest: approveAll,
provider: {
type: "openai",
baseUrl: openAiEndpoint.url,
apiKey: "test-provider-key",
modelId: "claude-sonnet-4.5",
},
});
await session.sendAndWait({ prompt: "What is 1+1?" });
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBe(1);
expect(exchanges[0].request.model).toBe("claude-sonnet-4.5");
await session.disconnect();
});
it("should apply workingDirectory on session resume", async () => {
const subDir = join(workDir, "resume-subproject");
await mkdir(subDir, { recursive: true });
await writeFile(join(subDir, "resume-marker.txt"), "I am in the resume working directory");
const session1 = await client.createSession({ onPermissionRequest: approveAll });
const sessionId = session1.sessionId;
const session2 = await client.resumeSession(sessionId, {
onPermissionRequest: approveAll,
workingDirectory: subDir,
});
const message = await session2.sendAndWait({
prompt: "Read the file resume-marker.txt and tell me what it says",
});
expect(message?.data.content ?? "").toContain("resume working directory");
await session2.disconnect();
});
it("should apply systemMessage on session resume", async () => {
const session1 = await client.createSession({ onPermissionRequest: approveAll });
const sessionId = session1.sessionId;
const resumeInstruction = "End the response with RESUME_SYSTEM_MESSAGE_SENTINEL.";
const session2 = await client.resumeSession(sessionId, {
onPermissionRequest: approveAll,
systemMessage: { mode: "append", content: resumeInstruction },
});
const message = await session2.sendAndWait({ prompt: "What is 1+1?" });
expect(message?.data.content ?? "").toContain("RESUME_SYSTEM_MESSAGE_SENTINEL");
const exchanges = await openAiEndpoint.getExchanges();
expect(exchanges.length).toBeGreaterThan(0);
const sys = getSystemMessage(exchanges[exchanges.length - 1]);
expect(sys).toContain(resumeInstruction);
await session2.disconnect();
});
it("should apply availableTools on session resume", async () => {
const session1 = await client.createSession({ onPermissionRequest: approveAll });
const sessionId = session1.sessionId;
const session2 = await client.resumeSession(sessionId, {
onPermissionRequest: approveAll,
availableTools: ["view"],
});
try {
await session2.send({ prompt: "What is 1+1?" });
const exchanges = await waitForExchanges();
const toolNames = getToolNames(exchanges[exchanges.length - 1]);
expect(toolNames).toEqual(["view"]);
} finally {
await session2.disconnect();
}
});
});