-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathrpc_session_state.e2e.test.ts
More file actions
822 lines (711 loc) · 34.1 KB
/
Copy pathrpc_session_state.e2e.test.ts
File metadata and controls
822 lines (711 loc) · 34.1 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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import { randomUUID } from "crypto";
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { approveAll } from "../../src/index.js";
import type { CopilotSession, SessionEvent } from "../../src/index.js";
import { createSdkTestContext } from "./harness/sdkTestContext.js";
import { waitForCondition } from "./harness/sdkTestHelper.js";
describe("Session-scoped RPC", async () => {
const { copilotClient: client, workDir } = 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();
});
// The runtime caches the /models response per (auth, base_url) for 30
// minutes (see capi_client.rs LIST_MODELS_CACHE), so within a single
// describe — where all tests share one CLI subprocess and proxy URL —
// the cache is primed by whichever test creates a session first. That
// makes any test which calls switchTo to a model not present in the
// first snapshot's models list fail silently (the runtime accepts the
// switch synchronously, then tool revalidation refetches the cached
// list, doesn't see the model, and reverts _selectedModel). Wrapping
// switchTo in its own describe gives it a dedicated subprocess + proxy
// → its own cache entry, so its snapshot's models list is authoritative.
describe("model switchTo (isolated to avoid models cache contamination)", async () => {
const { copilotClient: switchClient } = await createSdkTestContext();
it("should call session rpc model switchto", async () => {
const session = await switchClient.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-5.4",
reasoningEffort: "high",
});
const after = await session.rpc.model.getCurrent();
expect(result.modelId).toBe("gpt-5.4");
expect(after.modelId).toBe("gpt-5.4");
await session.disconnect();
});
});
it("should shutdown session with routine type", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
const shutdownEvent = waitForEvent(
session,
(event): event is Extract<SessionEvent, { type: "session.shutdown" }> =>
event.type === "session.shutdown" && event.data.shutdownType === "routine",
"session.shutdown routine event"
);
await session.rpc.shutdown({
type: "routine",
reason: "SDK E2E shutdown coverage",
});
expect((await shutdownEvent).data.shutdownType).toBe("routine");
});
it("should set and get each session mode value", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
for (const mode of ["interactive", "plan", "autopilot"] as const) {
await session.rpc.mode.set({ mode });
expect(await session.rpc.mode.get()).toBe(mode);
}
} finally {
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.each(["../escaped.txt", "../../escaped.txt", "nested/../../../escaped.txt"])(
"should reject workspace file path traversal: %s",
async (filePath) => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
await expect(
session.rpc.workspaces.createFile({
path: filePath,
content: "should not land outside workspace",
})
).rejects.toThrow(/workspace files directory/i);
await expect(session.rpc.workspaces.readFile({ path: filePath })).rejects.toThrow(
/workspace files directory/i
);
} finally {
await session.disconnect();
}
}
);
it("should create workspace file with nested path auto-creating dirs", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
const nestedPath = `nested-${randomUUID()}/subdir/file.txt`;
await session.rpc.workspaces.createFile({
path: nestedPath,
content: "nested content",
});
expect((await session.rpc.workspaces.readFile({ path: nestedPath })).content).toBe(
"nested content"
);
expect(
(await session.rpc.workspaces.listFiles()).files.some((f) => f.endsWith("file.txt"))
).toBe(true);
} finally {
await session.disconnect();
}
});
it("should report error reading nonexistent workspace file", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
await expect(
session.rpc.workspaces.readFile({
path: `never-exists-${randomUUID()}.txt`,
})
).rejects.toThrow();
} finally {
await session.disconnect();
}
});
it("should update existing workspace file with update operation", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
const filePath = `reused-${randomUUID()}.txt`;
await session.rpc.workspaces.createFile({ path: filePath, content: "v1" });
const updated = waitForEvent(
session,
(
event
): event is Extract<SessionEvent, { type: "session.workspace_file_changed" }> =>
event.type === "session.workspace_file_changed" &&
event.data.path === filePath &&
event.data.operation === "update",
`workspace_file_changed update event for ${filePath}`
);
await session.rpc.workspaces.createFile({ path: filePath, content: "v2" });
expect((await updated).data.operation).toBe("update");
expect((await session.rpc.workspaces.readFile({ path: filePath })).content).toBe("v2");
} finally {
await session.disconnect();
}
});
it.each(["", " ", "\t\n \r"])(
"should reject empty or whitespace session name",
async (emptyOrWhitespace) => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
await expect(session.rpc.name.set({ name: emptyOrWhitespace })).rejects.toThrow(
/empty/i
);
} finally {
await session.disconnect();
}
}
);
it("should emit title changed event each time name set is called", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
const titleA = `Title-A-${randomUUID()}`;
const titleB = `Title-B-${randomUUID()}`;
const first = waitForEvent(
session,
(event): event is Extract<SessionEvent, { type: "session.title_changed" }> =>
event.type === "session.title_changed" && event.data.title === titleA,
"first title_changed event"
);
await session.rpc.name.set({ name: titleA });
expect((await first).data.title).toBe(titleA);
const second = waitForEvent(
session,
(event): event is Extract<SessionEvent, { type: "session.title_changed" }> =>
event.type === "session.title_changed" && event.data.title === titleB,
"second title_changed event"
);
await session.rpc.name.set({ name: titleB });
expect((await second).data.title).toBe(titleB);
} finally {
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 call metadata snapshot, setWorkingDirectory, and recordContextChange", async () => {
const firstDirectory = createUniqueDirectory(workDir, "rpc-session-state-first");
const secondDirectory = createUniqueDirectory(workDir, "rpc-session-state-second");
const contextDirectory = createUniqueDirectory(workDir, "rpc-session-state-context");
const branch = `rpc-context-${randomUUID()}`;
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
workingDirectory: firstDirectory,
});
try {
const initialSnapshot = await session.rpc.metadata.snapshot();
expect(initialSnapshot.sessionId).toBe(session.sessionId);
expect(initialSnapshot.currentMode).toBe("interactive");
expect(initialSnapshot.selectedModel).toBe("claude-sonnet-4.5");
expect(initialSnapshot.isRemote).toBe(false);
expect(initialSnapshot.alreadyInUse).toBe(false);
expect(Date.parse(initialSnapshot.startTime)).not.toBeNaN();
expect(Date.parse(initialSnapshot.modifiedTime)).not.toBeNaN();
expect(pathsEqual(initialSnapshot.workingDirectory, firstDirectory)).toBe(true);
expect(initialSnapshot.workspace?.id).toBe(session.sessionId);
expect(initialSnapshot.workspacePath?.trim()).toBeTruthy();
const setWorkingDirectory = await session.rpc.metadata.setWorkingDirectory({
workingDirectory: secondDirectory,
});
expect(pathsEqual(setWorkingDirectory.workingDirectory, secondDirectory)).toBe(true);
await waitForCondition(
async () =>
pathsEqual(
(await session.rpc.metadata.snapshot()).workingDirectory,
secondDirectory
),
{ timeoutMessage: "Timed out waiting for metadata snapshot to reflect cwd." }
);
const contextChanged = waitForEvent(
session,
(event): event is Extract<SessionEvent, { type: "session.context_changed" }> =>
event.type === "session.context_changed" && event.data.branch === branch,
"session.context_changed event"
);
const context = {
cwd: contextDirectory,
gitRoot: firstDirectory,
branch,
repository: "github/copilot-sdk-e2e",
repositoryHost: "github.com",
hostType: "github" as const,
baseCommit: "0000000000000000000000000000000000000000",
headCommit: "1111111111111111111111111111111111111111",
};
await session.rpc.metadata.recordContextChange({ context });
const event = await contextChanged;
expect(pathsEqual(event.data.cwd, contextDirectory)).toBe(true);
expect(pathsEqual(event.data.gitRoot ?? "", firstDirectory)).toBe(true);
expect(event.data.branch).toBe(branch);
expect(event.data.repository).toBe("github/copilot-sdk-e2e");
expect(event.data.repositoryHost).toBe("github.com");
expect(event.data.hostType).toBe("github");
expect(event.data.baseCommit).toBe(context.baseCommit);
expect(event.data.headCommit).toBe(context.headCommit);
} finally {
await session.disconnect();
}
});
it("should update options and initialize session services", async () => {
const initialDirectory = createUniqueDirectory(workDir, "rpc-options-initial");
const optionsDirectory = createUniqueDirectory(workDir, "rpc-options-updated");
const featureName = `rpc-session-state-${randomUUID()}`;
const session = await client.createSession({
onPermissionRequest: approveAll,
workingDirectory: initialDirectory,
});
try {
const update = await session.rpc.options.update({
clientName: "node-sdk-rpc-session-state-e2e",
lspClientName: "node-sdk-rpc-session-state-lsp",
integrationId: `node-sdk-${randomUUID()}`,
featureFlags: { [featureName]: true },
workingDirectory: optionsDirectory,
coauthorEnabled: false,
enableStreaming: false,
askUserDisabled: true,
});
expect(update.success).toBe(true);
await waitForCondition(
async () =>
pathsEqual(
(await session.rpc.metadata.snapshot()).workingDirectory,
optionsDirectory
),
{
timeoutMessage:
"Timed out waiting for options.update workingDirectory to reach metadata snapshot.",
}
);
await expect(
session.rpc.lsp.initialize({
workingDirectory: optionsDirectory,
gitRoot: initialDirectory,
force: true,
})
).resolves.toBeNull();
await expect(
session.rpc.telemetry.setFeatureOverrides({
features: {
rpc_session_state_feature: featureName,
rpc_session_state_value: "enabled",
},
})
).resolves.toBeNull();
await expect(session.rpc.tools.initializeAndValidate()).resolves.toBeDefined();
expect(
pathsEqual(
(await session.rpc.metadata.snapshot()).workingDirectory,
optionsDirectory
)
).toBe(true);
} finally {
await session.disconnect();
}
});
it("should set reasoning effort and auto name", async () => {
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
});
try {
const reasoning = await session.rpc.model.setReasoningEffort({
reasoningEffort: "high",
});
expect(reasoning.reasoningEffort).toBe("high");
const currentModel = await session.rpc.model.getCurrent();
expect(currentModel.modelId).toBe("claude-sonnet-4.5");
expect(currentModel.reasoningEffort).toBe("high");
const autoName = `Auto Session ${randomUUID()}`;
const autoChanged = waitForEvent(
session,
(event): event is Extract<SessionEvent, { type: "session.title_changed" }> =>
event.type === "session.title_changed" && event.data.title === autoName,
"session.title_changed event after name.setAuto"
);
const autoResult = await session.rpc.name.setAuto({ summary: ` ${autoName} ` });
expect(autoResult.applied).toBe(true);
expect((await autoChanged).data.title).toBe(autoName);
expect((await session.rpc.name.get()).name).toBe(autoName);
const explicitName = `Explicit Session ${randomUUID()}`;
const explicitChanged = waitForEvent(
session,
(event): event is Extract<SessionEvent, { type: "session.title_changed" }> =>
event.type === "session.title_changed" && event.data.title === explicitName,
"session.title_changed event after explicit name.set"
);
await session.rpc.name.set({ name: explicitName });
expect((await explicitChanged).data.title).toBe(explicitName);
const ignoredAutoResult = await session.rpc.name.setAuto({
summary: `Ignored ${randomUUID()}`,
});
expect(ignoredAutoResult.applied).toBe(false);
expect((await session.rpc.name.get()).name).toBe(explicitName);
} finally {
await session.disconnect();
}
});
it("should set auth credentials", async () => {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
const login = `sdk-rpc-${randomUUID()}`;
const setCredentials = await session.rpc.gitHubAuth.setCredentials({
credentials: {
type: "user",
host: "https://github.com",
login,
copilotUser: {
analytics_tracking_id: "rpc-session-state-tracking-id",
chat_enabled: true,
copilot_plan: "individual_pro",
endpoints: {
api: "https://api.githubcopilot.test",
telemetry: "https://localhost:1/telemetry",
},
login,
},
},
});
expect(setCredentials.success).toBe(true);
const status = await session.rpc.gitHubAuth.getStatus();
expect(status.isAuthenticated).toBe(true);
expect(status.authType).toBe("user");
expect(status.host).toBe("https://github.com");
expect(status.login).toBe(login);
} finally {
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 });
expect((await session.rpc.metadata.isProcessing()).processing).toBe(false);
await session.sendAndWait({ prompt: "What is 2+2?" });
expect((await session.rpc.metadata.isProcessing()).processing).toBe(false);
const contextInfo = await session.rpc.metadata.contextInfo({
promptTokenLimit: 128_000,
outputTokenLimit: 4_096,
selectedModel: "claude-sonnet-4.5",
});
expect(contextInfo.contextInfo).not.toBeNull();
if (contextInfo.contextInfo) {
expect(contextInfo.contextInfo.modelName).toBe("claude-sonnet-4.5");
expect(contextInfo.contextInfo.promptTokenLimit).toBe(128_000);
expect(contextInfo.contextInfo.limit).toBeGreaterThanOrEqual(
contextInfo.contextInfo.promptTokenLimit
);
expect(contextInfo.contextInfo.totalTokens).toBeGreaterThan(0);
expect(contextInfo.contextInfo.systemTokens).toBeGreaterThan(0);
expect(contextInfo.contextInfo.conversationTokens).toBeGreaterThan(0);
expect(contextInfo.contextInfo.toolDefinitionsTokens).toBeGreaterThanOrEqual(0);
expect(contextInfo.contextInfo.totalTokens).toBe(
contextInfo.contextInfo.systemTokens +
contextInfo.contextInfo.conversationTokens +
contextInfo.contextInfo.toolDefinitionsTokens
);
}
const recomputed = await session.rpc.metadata.recomputeContextTokens({
modelId: "claude-sonnet-4.5",
});
expect(recomputed.systemTokenCount).toBeGreaterThan(0);
expect(recomputed.messagesTokenCount).toBeGreaterThan(0);
expect(recomputed.totalTokens).toBe(
recomputed.systemTokenCount + recomputed.messagesTokenCount
);
const result = await session.rpc.history.compact();
expect(result.success).toBe(true);
expect(result.messagesRemoved).toBeGreaterThanOrEqual(0);
if (result.contextWindow) {
expect(result.contextWindow.messagesLength).toBeGreaterThanOrEqual(0);
expect(result.contextWindow.currentTokens).toBeGreaterThanOrEqual(0);
if (result.contextWindow.conversationTokens != null) {
expect(result.contextWindow.conversationTokens).toBeGreaterThanOrEqual(0);
expect(result.contextWindow.conversationTokens).toBeLessThanOrEqual(
result.contextWindow.currentTokens
);
}
}
expect(await session.rpc.name.get()).toBeDefined();
await session.disconnect();
});
});
function createUniqueDirectory(baseDir: string, prefix: string): string {
const directory = join(baseDir, `${prefix}-${randomUUID()}`);
mkdirSync(directory, { recursive: true });
return directory;
}
function pathsEqual(left: string, right: string): boolean {
return normalizePath(left) === normalizePath(right);
}
function normalizePath(value: string): string {
return value.replace(/[\\/]+$/g, "").toLowerCase();
}
function waitForEvent<T extends SessionEvent>(
session: CopilotSession,
predicate: (event: SessionEvent) => event is T,
description: string,
timeoutMs = 15_000
): Promise<T> {
return new Promise<T>((resolve, reject) => {
let unsubscribe: () => void = () => {};
const timeout = setTimeout(() => {
unsubscribe();
reject(new Error(`Timed out waiting for ${description}`));
}, timeoutMs);
unsubscribe = session.on((event) => {
if (predicate(event)) {
clearTimeout(timeout);
unsubscribe();
resolve(event);
} else if (event.type === "session.error") {
clearTimeout(timeout);
unsubscribe();
reject(new Error(`${event.data.message}\n${event.data.stack ?? ""}`));
}
});
});
}