-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathhooks_extended.e2e.test.ts
More file actions
337 lines (285 loc) · 12.6 KB
/
hooks_extended.e2e.test.ts
File metadata and controls
337 lines (285 loc) · 12.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { approveAll, defineTool } from "../../src/index.js";
import type {
ErrorOccurredHookInput,
PostToolUseFailureHookInput,
PostToolUseHookInput,
PreToolUseHookInput,
SessionEndHookInput,
SessionStartHookInput,
UserPromptSubmittedHookInput,
} from "../../src/types.js";
import { createSdkTestContext } from "./harness/sdkTestContext.js";
describe("Extended session hooks", async () => {
const { copilotClient: client } = await createSdkTestContext();
it("should invoke onSessionStart hook on new session", async () => {
const sessionStartInputs: SessionStartHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onSessionStart: async (input, invocation) => {
sessionStartInputs.push(input);
expect(invocation.sessionId).toBe(session.sessionId);
},
},
});
await session.sendAndWait({
prompt: "Say hi",
});
expect(sessionStartInputs.length).toBeGreaterThan(0);
expect(sessionStartInputs[0].source).toBe("new");
expect(sessionStartInputs[0].timestamp).toBeInstanceOf(Date);
expect(sessionStartInputs[0].workingDirectory).toBeDefined();
await session.disconnect();
});
it("should invoke onUserPromptSubmitted hook when sending a message", async () => {
const userPromptInputs: UserPromptSubmittedHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onUserPromptSubmitted: async (input, invocation) => {
userPromptInputs.push(input);
expect(invocation.sessionId).toBe(session.sessionId);
},
},
});
await session.sendAndWait({
prompt: "Say hello",
});
expect(userPromptInputs.length).toBeGreaterThan(0);
expect(userPromptInputs[0].prompt).toContain("Say hello");
expect(userPromptInputs[0].timestamp).toBeInstanceOf(Date);
expect(userPromptInputs[0].workingDirectory).toBeDefined();
await session.disconnect();
});
it("should invoke onSessionEnd hook when session is disconnected", async () => {
const sessionEndInputs: SessionEndHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onSessionEnd: async (input, invocation) => {
sessionEndInputs.push(input);
expect(invocation.sessionId).toBe(session.sessionId);
},
},
});
await session.sendAndWait({
prompt: "Say hi",
});
await session.disconnect();
// Wait briefly for async hook
await new Promise((resolve) => setTimeout(resolve, 100));
expect(sessionEndInputs.length).toBeGreaterThan(0);
});
it("should invoke onErrorOccurred hook when error occurs", async () => {
const errorInputs: ErrorOccurredHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onErrorOccurred: async (input, invocation) => {
errorInputs.push(input);
expect(invocation.sessionId).toBe(session.sessionId);
expect(input.timestamp).toBeInstanceOf(Date);
expect(input.workingDirectory).toBeDefined();
expect(input.error).toBeDefined();
expect(["model_call", "tool_execution", "system", "user_input"]).toContain(
input.errorContext
);
expect(typeof input.recoverable).toBe("boolean");
},
},
});
await session.sendAndWait({
prompt: "Say hi",
});
// onErrorOccurred is dispatched by the runtime for actual errors (model failures, system errors).
// In a normal session it may not fire. Verify the hook is properly wired by checking
// that the session works correctly with the hook registered.
// If the hook did fire, the assertions inside it would have run.
expect(session.sessionId).toBeDefined();
await session.disconnect();
});
it("should invoke userPromptSubmitted hook and modify prompt", async () => {
const inputs: UserPromptSubmittedHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onUserPromptSubmitted: async (input, invocation) => {
inputs.push(input);
expect(invocation.sessionId).toBeTruthy();
return { modifiedPrompt: "Reply with exactly: HOOKED_PROMPT" };
},
},
});
const response = await session.sendAndWait({ prompt: "Say something else" });
expect(inputs.length).toBeGreaterThan(0);
expect(inputs[0].prompt).toContain("Say something else");
expect(response?.data.content ?? "").toContain("HOOKED_PROMPT");
await session.disconnect();
});
it("should invoke sessionStart hook", async () => {
const inputs: SessionStartHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onSessionStart: async (input, invocation) => {
inputs.push(input);
expect(invocation.sessionId).toBeTruthy();
return { additionalContext: "Session start hook context." };
},
},
});
await session.sendAndWait({ prompt: "Say hi" });
expect(inputs.length).toBeGreaterThan(0);
expect(inputs[0].source).toBe("new");
expect(inputs[0].workingDirectory).toBeTruthy();
await session.disconnect();
});
it("should invoke sessionEnd hook", async () => {
const inputs: SessionEndHookInput[] = [];
let resolveHook!: (value: SessionEndHookInput) => void;
const hookInvoked = new Promise<SessionEndHookInput>((resolve) => {
resolveHook = resolve;
});
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onSessionEnd: async (input, invocation) => {
inputs.push(input);
expect(invocation.sessionId).toBeTruthy();
resolveHook(input);
return { sessionSummary: "session ended" };
},
},
});
await session.sendAndWait({ prompt: "Say bye" });
await session.disconnect();
let timer: NodeJS.Timeout | undefined;
try {
await Promise.race([
hookInvoked,
new Promise<SessionEndHookInput>((_, reject) => {
timer = setTimeout(() => reject(new Error("Timeout: onSessionEnd")), 10_000);
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
expect(inputs.length).toBeGreaterThan(0);
});
it("should register erroroccurred hook", async () => {
const inputs: ErrorOccurredHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
hooks: {
onErrorOccurred: async (input, invocation) => {
inputs.push(input);
expect(invocation.sessionId).toBeTruthy();
return { errorHandling: "skip" };
},
},
});
await session.sendAndWait({ prompt: "Say hi" });
// OnErrorOccurred is dispatched only by genuine runtime errors. A normal turn
// cannot deterministically trigger one; this test is registration-only.
expect(inputs.length).toBe(0);
expect(session.sessionId).toBeTruthy();
await session.disconnect();
});
it("should allow preToolUse to return modifiedArgs and suppressOutput", async () => {
const inputs: PreToolUseHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
tools: [
defineTool("echo_value", {
description: "Echoes the supplied value",
parameters: z.object({ value: z.string() }),
handler: ({ value }) => value,
}),
],
hooks: {
onPreToolUse: async (input) => {
inputs.push(input);
if (input.toolName !== "echo_value") {
return { permissionDecision: "allow" };
}
return {
permissionDecision: "allow",
modifiedArgs: { value: "modified by hook" },
suppressOutput: false,
};
},
},
});
const response = await session.sendAndWait({
prompt: "Call echo_value with value 'original', then reply with the result.",
});
expect(inputs.length).toBeGreaterThan(0);
expect(inputs.some((input) => input.toolName === "echo_value")).toBe(true);
expect(response?.data.content ?? "").toContain("modified by hook");
await session.disconnect();
});
it("should allow postToolUse to return modifiedResult", async () => {
const inputs: PostToolUseHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
availableTools: ["report_intent"],
hooks: {
onPostToolUse: async (input) => {
inputs.push(input);
if (input.toolName !== "report_intent") {
return undefined;
}
return {
modifiedResult: {
textResultForLlm: "modified by post hook",
resultType: "success",
toolTelemetry: {},
},
suppressOutput: false,
};
},
},
});
const response = await session.sendAndWait({
prompt: "Call the report_intent tool with intent 'Testing post hook', then reply done.",
});
expect(inputs.some((input) => input.toolName === "report_intent")).toBe(true);
expect(response?.data.content).toBe("Done.");
await session.disconnect();
});
it("should invoke postToolUseFailure hook for failed tool result", async () => {
const failureInputs: PostToolUseFailureHookInput[] = [];
const postToolUseInputs: PostToolUseHookInput[] = [];
const session = await client.createSession({
onPermissionRequest: approveAll,
availableTools: ["report_intent"],
hooks: {
onPostToolUse: async (input) => {
postToolUseInputs.push(input);
},
onPostToolUseFailure: async (input, invocation) => {
failureInputs.push(input);
expect(invocation.sessionId).toBe(session.sessionId);
return { additionalContext: "HOOK_FAILURE_GUIDANCE_APPLIED" };
},
},
});
const response = await session.sendAndWait({
prompt: "Call the view tool with path 'missing.txt'. If it fails, use the hook guidance to answer.",
});
expect(postToolUseInputs).toHaveLength(0);
expect(failureInputs).toHaveLength(1);
expect(failureInputs[0].toolName).toBe("view");
expect(failureInputs[0].error).toContain("does not exist");
expect((failureInputs[0].toolArgs as { path?: string }).path).toContain("missing.txt");
expect(failureInputs[0].timestamp).toBeInstanceOf(Date);
expect(failureInputs[0].workingDirectory).toBeTruthy();
expect(response?.data.content ?? "").toContain("HOOK_FAILURE_GUIDANCE_APPLIED");
await session.disconnect();
});
});