forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpc_session_state.e2e.test.ts
More file actions
356 lines (287 loc) · 14 KB
/
Copy pathrpc_session_state.e2e.test.ts
File metadata and controls
356 lines (287 loc) · 14 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import { randomUUID } from "crypto";
import { describe, expect, it } from "vitest";
import { approveAll } from "../../src/index.js";
import type { SessionEvent } from "../../src/index.js";
import { createSdkTestContext } from "./harness/sdkTestContext.js";
describe("Session-scoped RPC", async () => {
const { copilotClient: client } = await createSdkTestContext();
async function assertImplementedFailure(
action: () => Promise<unknown>,
method: string
): Promise<void> {
await expect(action()).rejects.toSatisfy((err: unknown) => {
const text = err instanceof Error ? `${err.message}\n${err.stack ?? ""}` : String(err);
expect(text.toLowerCase()).not.toContain(`unhandled method ${method.toLowerCase()}`);
return true;
});
}
function getConversationMessages(events: SessionEvent[]): { role: string; content: string }[] {
const messages: { role: string; content: string }[] = [];
for (const evt of events) {
if (evt.type === "user.message") {
messages.push({ role: "user", content: evt.data.content });
} else if (evt.type === "assistant.message") {
messages.push({ role: "assistant", content: evt.data.content });
}
}
return messages;
}
it("should call session rpc model getcurrent", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
});
const result = await session.rpc.model.getCurrent();
expect(result.modelId).toBeTruthy();
await session.disconnect();
});
it("should call session rpc model switchto", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
});
const before = await session.rpc.model.getCurrent();
expect(before.modelId).toBeTruthy();
const result = await session.rpc.model.switchTo({
modelId: "gpt-4.1",
reasoningEffort: "high",
});
const after = await session.rpc.model.getCurrent();
expect(result.modelId).toBe("gpt-4.1");
expect(after.modelId).toBe(before.modelId);
await session.disconnect();
});
it("should get and set session mode", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const initial = await session.rpc.mode.get();
expect(initial).toBe("interactive");
await session.rpc.mode.set({ mode: "plan" });
expect(await session.rpc.mode.get()).toBe("plan");
await session.rpc.mode.set({ mode: "interactive" });
expect(await session.rpc.mode.get()).toBe("interactive");
await session.disconnect();
});
it("should read update and delete plan", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const initial = await session.rpc.plan.read();
expect(initial.exists).toBe(false);
expect(initial.content).toBeFalsy();
const planContent = "# Test Plan\n\n- Step 1\n- Step 2";
await session.rpc.plan.update({ content: planContent });
const afterUpdate = await session.rpc.plan.read();
expect(afterUpdate.exists).toBe(true);
expect(afterUpdate.content).toBe(planContent);
await session.rpc.plan.delete();
const afterDelete = await session.rpc.plan.read();
expect(afterDelete.exists).toBe(false);
expect(afterDelete.content).toBeFalsy();
await session.disconnect();
});
it("should call workspace file rpc methods", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const initial = await session.rpc.workspaces.listFiles();
expect(initial.files).toBeDefined();
await session.rpc.workspaces.createFile({
path: "test.txt",
content: "Hello, workspace!",
});
const afterCreate = await session.rpc.workspaces.listFiles();
expect(afterCreate.files).toContain("test.txt");
const file = await session.rpc.workspaces.readFile({ path: "test.txt" });
expect(file.content).toBe("Hello, workspace!");
const workspace = await session.rpc.workspaces.getWorkspace();
expect(workspace.workspace).toBeDefined();
expect(workspace.workspace.id).toBeTruthy();
await session.disconnect();
});
it("should get and set session metadata", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
await session.rpc.name.set({ name: "SDK test session" });
const name = await session.rpc.name.get();
expect(name.name).toBe("SDK test session");
const sources = await session.rpc.instructions.getSources();
expect(sources.sources).toBeDefined();
await session.disconnect();
});
it("should fork session with persisted messages", async () => {
const sourcePrompt = "Say FORK_SOURCE_ALPHA exactly.";
const forkPrompt = "Now say FORK_CHILD_BETA exactly.";
const session = await client.createSession({ onPermissionRequest: approveAll });
const initialAnswer = await session.sendAndWait({ prompt: sourcePrompt });
expect(initialAnswer?.data.content ?? "").toContain("FORK_SOURCE_ALPHA");
const sourceConversation = getConversationMessages(await session.getEvents());
expect(
sourceConversation.some((m) => m.role === "user" && m.content === sourcePrompt)
).toBe(true);
expect(
sourceConversation.some(
(m) => m.role === "assistant" && m.content.includes("FORK_SOURCE_ALPHA")
)
).toBe(true);
const fork = await client.rpc.sessions.fork({ sessionId: session.sessionId });
expect(fork.sessionId).toBeTruthy();
expect(fork.sessionId).not.toBe(session.sessionId);
const forkedSession = await client.resumeSession(fork.sessionId, {
onPermissionRequest: approveAll,
});
const forkedConversation = getConversationMessages(await forkedSession.getEvents());
expect(forkedConversation.slice(0, sourceConversation.length)).toEqual(sourceConversation);
const forkAnswer = await forkedSession.sendAndWait({ prompt: forkPrompt });
expect(forkAnswer?.data.content ?? "").toContain("FORK_CHILD_BETA");
const sourceAfterFork = getConversationMessages(await session.getEvents());
expect(sourceAfterFork.some((m) => m.content === forkPrompt)).toBe(false);
const forkAfterPrompt = getConversationMessages(await forkedSession.getEvents());
expect(forkAfterPrompt.some((m) => m.role === "user" && m.content === forkPrompt)).toBe(
true
);
expect(
forkAfterPrompt.some(
(m) => m.role === "assistant" && m.content.includes("FORK_CHILD_BETA")
)
).toBe(true);
await forkedSession.disconnect();
await session.disconnect();
});
it("should handle forking session without persisted events", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
let fork: Awaited<ReturnType<typeof client.rpc.sessions.fork>>;
try {
fork = await client.rpc.sessions.fork({ sessionId: session.sessionId });
} catch (err: unknown) {
const text =
err instanceof Error ? `${err.message}\n${err.stack ?? ""}` : String(err);
expect(text.toLowerCase()).toContain("not found or has no persisted events");
expect(text.toLowerCase()).not.toContain("unhandled method sessions.fork");
return;
}
expect(fork.sessionId.trim()).toBeTruthy();
expect(fork.sessionId).not.toBe(session.sessionId);
const forkedSession = await client.resumeSession(fork.sessionId, {
onPermissionRequest: approveAll,
});
try {
expect(getConversationMessages(await forkedSession.getEvents())).toEqual([]);
} finally {
await forkedSession.disconnect();
}
} finally {
await session.disconnect();
}
});
it("should fork session to event id excluding boundary event", async () => {
const firstPrompt = "Say FORK_BOUNDARY_FIRST exactly.";
const secondPrompt = "Say FORK_BOUNDARY_SECOND exactly.";
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
await session.sendAndWait({ prompt: firstPrompt });
await session.sendAndWait({ prompt: secondPrompt });
const sourceEvents = await session.getEvents();
const secondUserEvent = sourceEvents.find(
(event) => event.type === "user.message" && event.data.content === secondPrompt
);
expect(secondUserEvent).toBeDefined();
const boundaryEventId = secondUserEvent!.id;
const fork = await client.rpc.sessions.fork({
sessionId: session.sessionId,
toEventId: boundaryEventId,
});
expect(fork.sessionId.trim()).toBeTruthy();
expect(fork.sessionId).not.toBe(session.sessionId);
const forkedSession = await client.resumeSession(fork.sessionId, {
onPermissionRequest: approveAll,
});
try {
const forkedEvents = await forkedSession.getEvents();
expect(forkedEvents.some((event) => event.id === boundaryEventId)).toBe(false);
const forkedConversation = getConversationMessages(forkedEvents);
expect(
forkedConversation.some((m) => m.role === "user" && m.content === firstPrompt)
).toBe(true);
expect(
forkedConversation.some((m) => m.role === "user" && m.content === secondPrompt)
).toBe(false);
} finally {
await forkedSession.disconnect();
}
} finally {
await session.disconnect();
}
});
it("should report error when forking session to unknown event id", async () => {
const sourcePrompt = "Say FORK_UNKNOWN_EVENT_OK exactly.";
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
await session.sendAndWait({ prompt: sourcePrompt });
const bogusEventId = randomUUID();
await expect(
client.rpc.sessions.fork({
sessionId: session.sessionId,
toEventId: bogusEventId,
})
).rejects.toSatisfy((err: unknown) => {
const text =
err instanceof Error ? `${err.message}\n${err.stack ?? ""}` : String(err);
expect(text.toLowerCase()).toContain(`event ${bogusEventId} not found`);
expect(text.toLowerCase()).not.toContain("unhandled method sessions.fork");
return true;
});
} finally {
await session.disconnect();
}
});
it("should call session usage and permission rpcs", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const metrics = await session.rpc.usage.getMetrics();
expect(Date.parse(metrics.sessionStartTime)).not.toBeNaN();
if (metrics.totalNanoAiu !== undefined && metrics.totalNanoAiu !== null) {
expect(metrics.totalNanoAiu).toBeGreaterThanOrEqual(0);
}
if (metrics.tokenDetails) {
for (const detail of Object.values(metrics.tokenDetails)) {
expect(detail.tokenCount).toBeGreaterThanOrEqual(0);
}
}
for (const modelMetric of Object.values(metrics.modelMetrics)) {
if (modelMetric.totalNanoAiu !== undefined && modelMetric.totalNanoAiu !== null) {
expect(modelMetric.totalNanoAiu).toBeGreaterThanOrEqual(0);
}
if (modelMetric.tokenDetails) {
for (const detail of Object.values(modelMetric.tokenDetails)) {
expect(detail.tokenCount).toBeGreaterThanOrEqual(0);
}
}
}
try {
const approve = await session.rpc.permissions.setApproveAll({ enabled: true });
expect(approve.success).toBe(true);
const reset = await session.rpc.permissions.resetSessionApprovals();
expect(reset.success).toBe(true);
} finally {
await session.rpc.permissions.setApproveAll({ enabled: false });
}
await session.disconnect();
});
it("should report implemented errors for unsupported session rpc paths", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
await assertImplementedFailure(
() => session.rpc.history.truncate({ eventId: "missing-event" }),
"session.history.truncate"
);
await assertImplementedFailure(
() => session.rpc.mcp.oauth.login({ serverName: "missing-server" }),
"session.mcp.oauth.login"
);
await session.disconnect();
});
it("should compact session history after messages", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
await session.sendAndWait({ prompt: "What is 2+2?" });
const result = await session.rpc.history.compact();
expect(result).toBeDefined();
await session.disconnect();
});
});