Skip to content

Commit 8cd2fac

Browse files
committed
fix: pass hookParams to onAfterRequest instead of empty object (CopilotKit#2124)
The onAfterRequest middleware callback was being called with an empty object `{}` instead of the available hook parameters (threadId, runId, messages, path). Extract and forward these from the hookParams that the v2 runtime provides.
1 parent ed8a8a0 commit 8cd2fac

2 files changed

Lines changed: 53 additions & 3 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { describe, it, expect, vi } from "vitest";
2+
import { CopilotRuntime } from "../copilot-runtime";
3+
4+
describe("onAfterRequest middleware (#2124)", () => {
5+
it("should pass hookParams to onAfterRequest, not an empty object", async () => {
6+
const onAfterRequest = vi.fn();
7+
8+
const runtime = new CopilotRuntime({
9+
middleware: {
10+
onAfterRequest,
11+
},
12+
});
13+
14+
// Access the internal afterRequestMiddleware function
15+
const afterRequestMw = runtime.instance.afterRequestMiddleware;
16+
expect(afterRequestMw).toBeDefined();
17+
18+
// Simulate calling the middleware with hookParams (as the v2 runtime would)
19+
const fakeHookParams = {
20+
runtime: {} as any,
21+
response: new Response("test"),
22+
path: "/api/copilotkit",
23+
messages: [{ id: "msg-1", role: "assistant", content: "Hello" }],
24+
threadId: "thread-123",
25+
runId: "run-456",
26+
};
27+
28+
await (afterRequestMw as Function)(fakeHookParams);
29+
30+
// The onAfterRequest callback should have been called
31+
expect(onAfterRequest).toHaveBeenCalledTimes(1);
32+
33+
// CRITICAL: It should NOT be called with an empty object
34+
const callArg = onAfterRequest.mock.calls[0][0];
35+
expect(callArg).not.toEqual({});
36+
37+
// It should receive the hookParams (or at least threadId/messages)
38+
expect(callArg).toHaveProperty("threadId", "thread-123");
39+
expect(callArg).toHaveProperty("runId", "run-456");
40+
});
41+
});

packages/runtime/src/lib/runtime/copilot-runtime.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -590,9 +590,18 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
590590
params?.afterRequestMiddleware?.(hookParams);
591591

592592
if (params?.middleware?.onAfterRequest) {
593-
// TODO: provide old expected params here when available
594-
// @ts-expect-error -- missing arguments.
595-
params.middleware.onAfterRequest({});
593+
params.middleware.onAfterRequest({
594+
threadId: hookParams.threadId ?? "",
595+
runId: hookParams.runId,
596+
inputMessages: (hookParams.messages ?? []).filter(
597+
(m: any) => "role" in m && m.role === "user",
598+
),
599+
outputMessages: (hookParams.messages ?? []).filter(
600+
(m: any) => "role" in m && m.role !== "user",
601+
),
602+
properties: {},
603+
url: hookParams.path,
604+
});
596605
}
597606
};
598607
}

0 commit comments

Comments
 (0)