Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

dedupe cursor client test scaffolding

Raine Virta8aa2b25a16c0
diff --git a/src/providers/cursor/client.test.ts b/src/providers/cursor/client.test.ts
index 0cb7aab..95aa4e1 100644
--- a/src/providers/cursor/client.test.ts
+++ b/src/providers/cursor/client.test.ts
@@ -6,98 +6,158 @@ import { decodeCursorStream, encodeConnectFrame, runCursorAgent } from "./client
import {
decodeFrameJson,
fakeProtoMerged as fakeProto,
- frame,
fakeCursorCtx,
+ frame,
jsonBytes,
streamFromChunks,
} from "./cursor-test-helpers.ts";
+type CursorRunOptions = Omit<Parameters<typeof runCursorAgent>[0], "ctx" | "proto" | "openRunStream">;
+type CursorClientMessage = Record<string, any>;
+
+function buildRunOptions(overrides: Partial<CursorRunOptions> = {}): CursorRunOptions {
+ return {
+ prompt: "hello",
+ mode: "AGENT_MODE_AGENT",
+ conversationId: "conversation",
+ model: { modelId: "composer-2.5" },
+ auth: { accessToken: "token", source: "test" },
+ ...overrides,
+ };
+}
+
+function buildServerExecFrame(
+ id: number,
+ execId: string | undefined,
+ message: { case: string; value: Record<string, any> },
+): Uint8Array {
+ const serverMessage = {
+ id,
+ ...(execId === undefined ? {} : { execId }),
+ message,
+ };
+
+ return frame({
+ message: {
+ case: "execServerMessage",
+ value: serverMessage,
+ },
+ });
+}
+
+function buildServerKvFrame(
+ id: number,
+ message: { case: string; value: Record<string, any> },
+): Uint8Array {
+ return frame({
+ message: {
+ case: "kvServerMessage",
+ value: {
+ id,
+ message,
+ },
+ },
+ });
+}
+
+function buildServerInteractionQueryFrame(
+ id: number,
+ query: { case: string; value: Record<string, any> },
+): Uint8Array {
+ return frame({
+ message: {
+ case: "interactionQuery",
+ value: {
+ id,
+ query,
+ },
+ },
+ });
+}
+
+function buildServerStreamCloseFrame(): Uint8Array {
+ return encodeConnectFrame(jsonBytes({}), 2);
+}
+
+function assertHeartbeatMessage(messages: CursorClientMessage[], index: number) {
+ expect(messages[index]).toEqual({ execClientControlMessage: { heartbeat: {} } });
+}
+
+function assertStreamCloseMessage(messages: CursorClientMessage[], index: number, id?: number) {
+ expect(messages[index]).toEqual({
+ execClientControlMessage: {
+ streamClose: id === undefined ? {} : { id },
+ },
+ });
+}
+
+async function runCursorAgentWithFrames(
+ serverFrames: Uint8Array[],
+ runOptions: Partial<CursorRunOptions> = {},
+): Promise<{ upstream: ReadableStream<Uint8Array>; sentFrames: Uint8Array[] }> {
+ const sentFrames: Uint8Array[] = [];
+
+ const upstream = await runCursorAgent({
+ ...buildRunOptions(runOptions),
+ ctx: fakeCursorCtx(),
+ proto: fakeProto,
+ openRunStream: async () => ({
+ readable: streamFromChunks(serverFrames),
+ status: Promise.resolve({ status: 200 }),
+ async write(frame) {
+ sentFrames.push(frame);
+ },
+ close() {},
+ }),
+ });
+
+ return { upstream, sentFrames };
+}
+
+function decodeSentFrames(sentFrames: Uint8Array[]): CursorClientMessage[] {
+ return sentFrames.map((frameBytes) => decodeFrameJson(frameBytes) as CursorClientMessage);
+}
+
describe("Cursor protocol client", () => {
it("acks exec setup and KV messages on the HTTP/2 Run stream", async () => {
- const sentFrames: Uint8Array[] = [];
-
- const upstream = await runCursorAgent({
- prompt: "hello",
- mode: "AGENT_MODE_AGENT",
- conversationId: "conversation",
- model: { modelId: "composer-2.5" },
- auth: { accessToken: "token", source: "test" },
- ctx: fakeCursorCtx(),
- proto: fakeProto,
- openRunStream: async () => ({
- readable: streamFromChunks([
- frame({
- message: {
- case: "execServerMessage",
- value: { id: 0, message: { case: "requestContextArgs", value: {} } },
- },
- }),
- frame({
- message: {
- case: "kvServerMessage",
- value: { id: 0, message: { case: "setBlobArgs", value: {} } },
- },
- }),
- frame({
- message: {
- case: "kvServerMessage",
- value: { id: 2, message: { case: "getBlobArgs", value: {} } },
- },
- }),
- encodeConnectFrame(jsonBytes({}), 2),
- ]),
- status: Promise.resolve({ status: 200 }),
- async write(frame) {
- sentFrames.push(frame);
- },
- close() {},
- }),
- });
+ const { upstream, sentFrames } = await runCursorAgentWithFrames([
+ buildServerExecFrame(0, undefined, { case: "requestContextArgs", value: {} }),
+ buildServerKvFrame(0, { case: "setBlobArgs", value: {} }),
+ buildServerKvFrame(2, { case: "getBlobArgs", value: {} }),
+ buildServerStreamCloseFrame(),
+ ]);
await drain(upstream);
- const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
+ const clientMessages = decodeSentFrames(sentFrames);
expect(clientMessages[0]?.runRequest.conversationId).toBe("conversation");
expect(clientMessages[0]?.runRequest.clientSupportsInlineImages).toBe(true);
- expect(clientMessages[1]).toEqual({ execClientControlMessage: { heartbeat: {} } });
+ assertHeartbeatMessage(clientMessages, 1);
expect(clientMessages[2]?.execClientMessage.requestContextResult.success.requestContext).toBeDefined();
expect(clientMessages[2]?.execClientMessage.requestContextResult.success.requestContext.webSearchEnabled).toBe(true);
expect(clientMessages[2]?.execClientMessage.requestContextResult.success.requestContext.webFetchEnabled).toBe(true);
- expect(clientMessages[3]).toEqual({ execClientControlMessage: { streamClose: {} } });
+ assertStreamCloseMessage(clientMessages, 3);
expect(clientMessages[4]).toEqual({ kvClientMessage: { setBlobResult: {} } });
expect(clientMessages[5]).toEqual({ kvClientMessage: { getBlobResult: {}, id: 2 } });
});
it("sends selected images in the Cursor run request", async () => {
- const sentFrames: Uint8Array[] = [];
-
- const upstream = await runCursorAgent({
- prompt: "describe image",
- mode: "AGENT_MODE_AGENT",
- conversationId: "conversation",
- model: { modelId: "composer-2.5" },
- selectedImages: [
- {
- data: "aGVsbG8=",
- uuid: "image-id",
- path: "claude-image-1.png",
- mimeType: "image/png",
- },
- ],
- auth: { accessToken: "token", source: "test" },
- ctx: fakeCursorCtx(),
- proto: fakeProto,
- openRunStream: async () => ({
- readable: streamFromChunks([encodeConnectFrame(jsonBytes({}), 2)]),
- status: Promise.resolve({ status: 200 }),
- async write(frame) {
- sentFrames.push(frame);
- },
- close() {},
- }),
- });
+ const { upstream, sentFrames } = await runCursorAgentWithFrames(
+ [buildServerStreamCloseFrame()],
+ {
+ prompt: "describe image",
+ selectedImages: [
+ {
+ data: "aGVsbG8=",
+ uuid: "image-id",
+ path: "claude-image-1.png",
+ mimeType: "image/png",
+ },
+ ],
+ },
+ );
await drain(upstream);
- const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
+ const clientMessages = decodeSentFrames(sentFrames);
expect(clientMessages[0]?.runRequest.action.userMessageAction.userMessage.selectedContext).toEqual({
selectedImages: [
{
@@ -112,48 +172,24 @@ describe("Cursor protocol client", () => {
});
it("approves Cursor web search and web fetch interaction queries", async () => {
- const sentFrames: Uint8Array[] = [];
-
- const upstream = await runCursorAgent({
- prompt: "search the web",
- mode: "AGENT_MODE_AGENT",
- conversationId: "conversation",
- model: { modelId: "composer-2.5" },
- auth: { accessToken: "token", source: "test" },
- ctx: fakeCursorCtx(),
- proto: fakeProto,
- openRunStream: async () => ({
- readable: streamFromChunks([
- frame({
- message: {
- case: "interactionQuery",
- value: { id: 11, query: { case: "webSearchRequestQuery", value: { args: { searchTerm: "cursor" } } } },
- },
- }),
- frame({
- message: {
- case: "interactionQuery",
- value: { id: 12, query: { case: "webFetchRequestQuery", value: { args: { url: "https://example.com" } } } },
- },
- }),
- frame({
- message: {
- case: "interactionQuery",
- value: { id: 13, query: { case: "generateImageRequestQuery", value: {} } },
- },
- }),
- encodeConnectFrame(jsonBytes({}), 2),
- ]),
- status: Promise.resolve({ status: 200 }),
- async write(frame) {
- sentFrames.push(frame);
- },
- close() {},
- }),
- });
+ const { upstream, sentFrames } = await runCursorAgentWithFrames(
+ [
+ buildServerInteractionQueryFrame(11, {
+ case: "webSearchRequestQuery",
+ value: { args: { searchTerm: "cursor" } },
+ }),
+ buildServerInteractionQueryFrame(12, {
+ case: "webFetchRequestQuery",
+ value: { args: { url: "https://example.com" } },
+ }),
+ buildServerInteractionQueryFrame(13, { case: "generateImageRequestQuery", value: {} }),
+ buildServerStreamCloseFrame(),
+ ],
+ { prompt: "search the web" },
+ );
await drain(upstream);
- const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
+ const clientMessages = decodeSentFrames(sentFrames);
expect(clientMessages).toContainEqual({
interactionResponse: { id: 11, webSearchRequestResponse: { approved: {} } },
});
@@ -164,44 +200,21 @@ describe("Cursor protocol client", () => {
});
it("answers Cursor readArgs with file content and closes the exec stream", async () => {
- const sentFrames: Uint8Array[] = [];
const dir = await mkdtemp(join(tmpdir(), "cursor-read-"));
const file = join(dir, "SKILL.md");
await writeFile(file, "hello\nworld\n", "utf8");
- const upstream = await runCursorAgent({
- prompt: "hello",
- mode: "AGENT_MODE_AGENT",
- conversationId: "conversation",
- model: { modelId: "composer-2.5" },
- auth: { accessToken: "token", source: "test" },
- ctx: fakeCursorCtx(),
- proto: fakeProto,
- openRunStream: async () => ({
- readable: streamFromChunks([
- frame({
- message: {
- case: "execServerMessage",
- value: {
- id: 7,
- execId: "exec-read",
- message: { case: "readArgs", value: { path: file } },
- },
- },
- }),
- encodeConnectFrame(jsonBytes({}), 2),
- ]),
- status: Promise.resolve({ status: 200 }),
- async write(frame) {
- sentFrames.push(frame);
- },
- close() {},
+ const { upstream, sentFrames } = await runCursorAgentWithFrames([
+ buildServerExecFrame(7, "exec-read", {
+ case: "readArgs",
+ value: { path: file },
}),
- });
+ buildServerStreamCloseFrame(),
+ ]);
await drain(upstream);
- const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
- expect(clientMessages[1]).toEqual({ execClientControlMessage: { heartbeat: {} } });
+ const clientMessages = decodeSentFrames(sentFrames);
+ assertHeartbeatMessage(clientMessages, 1);
expect(clientMessages[2]).toEqual({
execClientMessage: {
id: 7,
@@ -216,55 +229,29 @@ describe("Cursor protocol client", () => {
},
},
});
- expect(clientMessages[3]).toEqual({ execClientControlMessage: { streamClose: { id: 7 } } });
+ assertStreamCloseMessage(clientMessages, 3, 7);
});
it("answers Cursor writeArgs by writing the file and closing the exec stream", async () => {
- const sentFrames: Uint8Array[] = [];
const dir = await mkdtemp(join(tmpdir(), "cursor-write-"));
const file = join(dir, "history", "findings.md");
- const upstream = await runCursorAgent({
- prompt: "hello",
- mode: "AGENT_MODE_AGENT",
- conversationId: "conversation",
- model: { modelId: "composer-2.5" },
- auth: { accessToken: "token", source: "test" },
- ctx: fakeCursorCtx(),
- proto: fakeProto,
- openRunStream: async () => ({
- readable: streamFromChunks([
- frame({
- message: {
- case: "execServerMessage",
- value: {
- id: 10,
- execId: "exec-write",
- message: {
- case: "writeArgs",
- value: {
- path: file,
- fileText: "finding one\nfinding two\n",
- returnFileContentAfterWrite: true,
- },
- },
- },
- },
- }),
- encodeConnectFrame(jsonBytes({}), 2),
- ]),
- status: Promise.resolve({ status: 200 }),
- async write(frame) {
- sentFrames.push(frame);
+ const { upstream, sentFrames } = await runCursorAgentWithFrames([
+ buildServerExecFrame(10, "exec-write", {
+ case: "writeArgs",
+ value: {
+ path: file,
+ fileText: "finding one\nfinding two\n",
+ returnFileContentAfterWrite: true,
},
- close() {},
}),
- });
+ buildServerStreamCloseFrame(),
+ ]);
await drain(upstream);
- const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
+ const clientMessages = decodeSentFrames(sentFrames);
expect(await readFile(file, "utf8")).toBe("finding one\nfinding two\n");
- expect(clientMessages[1]).toEqual({ execClientControlMessage: { heartbeat: {} } });
+ assertHeartbeatMessage(clientMessages, 1);
expect(clientMessages[2]).toEqual({
execClientMessage: {
id: 10,
@@ -279,56 +266,30 @@ describe("Cursor protocol client", () => {
},
},
});
- expect(clientMessages[3]).toEqual({ execClientControlMessage: { streamClose: { id: 10 } } });
+ assertStreamCloseMessage(clientMessages, 3, 10);
});
it("answers Cursor grepArgs with glob file matches and closes the exec stream", async () => {
- const sentFrames: Uint8Array[] = [];
const dir = await mkdtemp(join(tmpdir(), "cursor-grep-"));
await writeFile(join(dir, "README.md"), "hello\n", "utf8");
await writeFile(join(dir, "notes.txt"), "hello\n", "utf8");
- const upstream = await runCursorAgent({
- prompt: "hello",
- mode: "AGENT_MODE_AGENT",
- conversationId: "conversation",
- model: { modelId: "composer-2.5" },
- auth: { accessToken: "token", source: "test" },
- ctx: fakeCursorCtx(),
- proto: fakeProto,
- openRunStream: async () => ({
- readable: streamFromChunks([
- frame({
- message: {
- case: "execServerMessage",
- value: {
- id: 8,
- execId: "exec-grep",
- message: {
- case: "grepArgs",
- value: {
- pattern: "",
- path: dir,
- glob: "**/README*",
- outputMode: "files_with_matches",
- },
- },
- },
- },
- }),
- encodeConnectFrame(jsonBytes({}), 2),
- ]),
- status: Promise.resolve({ status: 200 }),
- async write(frame) {
- sentFrames.push(frame);
+ const { upstream, sentFrames } = await runCursorAgentWithFrames([
+ buildServerExecFrame(8, "exec-grep", {
+ case: "grepArgs",
+ value: {
+ pattern: "",
+ path: dir,
+ glob: "**/README*",
+ outputMode: "files_with_matches",
},
- close() {},
}),
- });
+ buildServerStreamCloseFrame(),
+ ]);
await drain(upstream);
- const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
- expect(clientMessages[1]).toEqual({ execClientControlMessage: { heartbeat: {} } });
+ const clientMessages = decodeSentFrames(sentFrames);
+ assertHeartbeatMessage(clientMessages, 1);
expect(clientMessages[2]).toEqual({
execClientMessage: {
id: 8,
@@ -350,60 +311,33 @@ describe("Cursor protocol client", () => {
},
},
});
- expect(clientMessages[3]).toEqual({ execClientControlMessage: { streamClose: { id: 8 } } });
+ assertStreamCloseMessage(clientMessages, 3, 8);
});
it("answers Cursor shellStreamArgs with stream events and closes the exec stream", async () => {
- const sentFrames: Uint8Array[] = [];
-
- const upstream = await runCursorAgent({
- prompt: "hello",
- mode: "AGENT_MODE_AGENT",
- conversationId: "conversation",
- model: { modelId: "composer-2.5" },
- auth: { accessToken: "token", source: "test" },
- ctx: fakeCursorCtx(),
- proto: fakeProto,
- openRunStream: async () => ({
- readable: streamFromChunks([
- frame({
- message: {
- case: "execServerMessage",
- value: {
- id: 9,
- execId: "exec-shell",
- message: {
- case: "shellStreamArgs",
- value: {
- command: "printf stdout; printf stderr >&2",
- workingDirectory: process.cwd(),
- timeout: 5000,
- },
- },
- },
- },
- }),
- encodeConnectFrame(jsonBytes({}), 2),
- ]),
- status: Promise.resolve({ status: 200 }),
- async write(frame) {
- sentFrames.push(frame);
+ const { upstream, sentFrames } = await runCursorAgentWithFrames([
+ buildServerExecFrame(9, "exec-shell", {
+ case: "shellStreamArgs",
+ value: {
+ command: "printf stdout; printf stderr >&2",
+ workingDirectory: process.cwd(),
+ timeout: 5000,
},
- close() {},
}),
- });
+ buildServerStreamCloseFrame(),
+ ]);
let trace = "";
for await (const event of decodeCursorStream(upstream, fakeProto)) {
if (event.type === "text_delta") trace += event.text;
}
- const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
- expect(clientMessages[1]).toEqual({ execClientControlMessage: { heartbeat: {} } });
+ const clientMessages = decodeSentFrames(sentFrames);
+ assertHeartbeatMessage(clientMessages, 1);
expect(clientMessages.some((message) => message.execClientMessage?.shellStream?.start)).toBe(true);
expect(clientMessages.some((message) => message.execClientMessage?.shellStream?.stdout?.data === "stdout")).toBe(true);
expect(clientMessages.some((message) => message.execClientMessage?.shellStream?.stderr?.data === "stderr")).toBe(true);
expect(clientMessages.some((message) => message.execClientMessage?.shellStream?.exit?.code === 0)).toBe(true);
- expect(clientMessages.at(-1)).toEqual({ execClientControlMessage: { streamClose: { id: 9 } } });
+ assertStreamCloseMessage(clientMessages, clientMessages.length - 1, 9);
expect(trace).toContain("Bash(printf stdout; printf stderr >&2)");
expect(trace).toContain("stdout");
expect(trace).toContain("stderr");