Open History to see the last commit
1import type { RunResult } from "@cursor/sdk";
2import { CursorSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
3import { describe, expect, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Fiber from "effect/Fiber";
7import * as TestClock from "effect/testing/TestClock";
8import * as Schema from "effect/Schema";
9import { createModelSelection } from "@t3tools/shared/model";
10import { beforeEach, vi } from "vite-plus/test";
11
12import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";
13
14const cursorSdkMock = vi.hoisted(() => ({
15 create: vi.fn<(options: unknown) => Promise<unknown>>(),
16 send: vi.fn<(prompt: string) => Promise<unknown>>(),
17 close: vi.fn(),
18 cancel: vi.fn(async () => {}),
19 prompt: vi.fn<(prompt: string, options: unknown) => Promise<RunResult>>(async () => ({
20 id: "run-cursor-text-generation-test",
21 status: "finished",
22 result:
23 '{"subject":"Add generated commit message","body":"- verify cursor sdk text generation"}',
24 })),
25}));
26
27vi.mock("../provider/cursorSdk.ts", () => ({ Agent: { create: cursorSdkMock.create } }));
28
29let hasCustomPolicy = false;
30const fsLayer = FileSystem.layerNoop({
31 exists: () => Effect.succeed(hasCustomPolicy),
32 makeTempDirectoryScoped: () => Effect.succeed("/isolated-text-generation"),
33});
34
35const decodeCursorSettings = Schema.decodeSync(CursorSettings);
36const cursorSettings = decodeCursorSettings({ enabled: true });
37
38beforeEach(() => {
39 hasCustomPolicy = false;
40 cursorSdkMock.create.mockReset();
41 cursorSdkMock.send.mockReset();
42 cursorSdkMock.create.mockImplementation(async (options) => {
43 cursorSdkMock.send.mockImplementation(async (prompt) => ({
44 status: "running",
45 cancel: cursorSdkMock.cancel,
46 wait: () => cursorSdkMock.prompt(prompt, options),
47 }));
48 return {
49 close: cursorSdkMock.close,
50 [Symbol.asyncDispose]: async () => {
51 cursorSdkMock.close();
52 },
53 send: cursorSdkMock.send,
54 };
55 });
56 cursorSdkMock.close.mockClear();
57 cursorSdkMock.cancel.mockClear();
58 cursorSdkMock.prompt.mockReset();
59 cursorSdkMock.prompt.mockResolvedValue({
60 id: "run-cursor-text-generation-test",
61 status: "finished",
62 result:
63 '{"subject":"Add generated commit message","body":"- verify cursor sdk text generation"}',
64 });
65});
66
67describe("CursorTextGeneration", () => {
68 it.effect("resolves the browser credential for every request after an account change", () =>
69 Effect.gen(function* () {
70 let apiKey = "first-browser-key";
71 const generation = yield* makeCursorTextGeneration(
72 cursorSettings,
73 {},
74 Effect.sync(() => apiKey),
75 );
76 const input = {
77 cwd: process.cwd(),
78 branch: "feature/cursor",
79 stagedSummary: "M file.ts",
80 stagedPatch: "diff",
81 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
82 };
83 yield* generation.generateCommitMessage(input);
84 expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
85 expect.objectContaining({ apiKey: "first-browser-key" }),
86 );
87 apiKey = "second-browser-key";
88 yield* generation.generateCommitMessage(input);
89 expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
90 expect.objectContaining({ apiKey: "second-browser-key" }),
91 );
92 }).pipe(Effect.provide(fsLayer)),
93 );
94
95 it.effect("uses the Cursor SDK prompt API with model parameters and API key", () =>
96 Effect.gen(function* () {
97 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
98 CURSOR_API_KEY: "test-cursor-key",
99 });
100
101 const generated = yield* textGeneration.generateCommitMessage({
102 cwd: process.cwd(),
103 branch: "feature/cursor-text-generation",
104 stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
105 stagedPatch:
106 "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
107 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
108 { id: "thinking", value: "high" },
109 { id: "contextWindow", value: "1m" },
110 { id: "fastMode", value: true },
111 ]),
112 });
113
114 expect(generated.subject).toBe("Add generated commit message");
115 expect(generated.body).toBe("- verify cursor sdk text generation");
116
117 expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(1);
118 const [prompt, options] = (
119 cursorSdkMock.prompt.mock.calls as unknown as Array<[string, unknown]>
120 )[0]!;
121 expect(prompt).toContain("Staged patch:");
122 expect(options).toEqual({
123 apiKey: "test-cursor-key",
124 mode: "plan",
125 model: {
126 id: "gpt-5.4",
127 params: [
128 { id: "thinking", value: "high" },
129 { id: "context", value: "1m" },
130 { id: "fast", value: "true" },
131 ],
132 },
133 local: {
134 cwd: "/isolated-text-generation",
135 autoReview: false,
136 sandboxOptions: { enabled: true },
137 settingSources: [],
138 enableAgentRetries: true,
139 },
140 });
141 }).pipe(Effect.provide(fsLayer)),
142 );
143
144 it.effect("continues in the temp directory when the SDK cannot sandbox", () =>
145 Effect.gen(function* () {
146 cursorSdkMock.create.mockImplementationOnce(async () => {
147 throw new Error(
148 "Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",
149 );
150 });
151 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
152 CURSOR_API_KEY: "test-cursor-key",
153 });
154
155 const generated = yield* textGeneration.generateCommitMessage({
156 cwd: process.cwd(),
157 branch: "feature/cursor-text-generation",
158 stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
159 stagedPatch: "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts",
160 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2"),
161 });
162
163 expect(generated.subject).toBe("Add generated commit message");
164 expect(cursorSdkMock.create).toHaveBeenCalledTimes(2);
165 expect(cursorSdkMock.create.mock.calls[0]?.[0]).toMatchObject({
166 local: { sandboxOptions: { enabled: true } },
167 });
168 expect(cursorSdkMock.create.mock.calls[1]?.[0]).toMatchObject({
169 local: {
170 cwd: "/isolated-text-generation",
171 autoReview: false,
172 sandboxOptions: { enabled: false },
173 settingSources: [],
174 enableAgentRetries: true,
175 },
176 });
177 }).pipe(Effect.provide(fsLayer)),
178 );
179
180 it.effect("does not retry Agent.create for errors other than an unsupported sandbox", () =>
181 Effect.gen(function* () {
182 cursorSdkMock.create.mockImplementationOnce(async () => {
183 throw new Error("Cursor SDK network down");
184 });
185 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
186 CURSOR_API_KEY: "test-cursor-key",
187 });
188
189 const error = yield* Effect.flip(
190 textGeneration.generateCommitMessage({
191 cwd: process.cwd(),
192 branch: "feature/cursor-text-generation",
193 stagedSummary: "M README.md",
194 stagedPatch: "diff --git a/README.md b/README.md",
195 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2"),
196 }),
197 );
198
199 expect(error.detail).toBe("Cursor SDK text generation failed.");
200 expect(cursorSdkMock.create).toHaveBeenCalledTimes(1);
201 }).pipe(Effect.provide(fsLayer)),
202 );
203
204 it.effect("accepts json objects with extra assistant text around them", () =>
205 Effect.gen(function* () {
206 cursorSdkMock.prompt.mockResolvedValueOnce({
207 id: "run-cursor-text-generation-test",
208 status: "finished",
209 result:
210 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
211 });
212 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
213 CURSOR_API_KEY: "test-cursor-key",
214 });
215
216 const generated = yield* textGeneration.generateCommitMessage({
217 cwd: process.cwd(),
218 branch: "feature/cursor-noisy-json",
219 stagedSummary: "M README.md",
220 stagedPatch: "diff --git a/README.md b/README.md",
221 modelSelection: {
222 instanceId: ProviderInstanceId.make("cursor"),
223 model: "composer-2",
224 },
225 });
226
227 expect(generated.subject).toBe("Update README dummy comment with attribution and date");
228 expect(generated.body).toBe("");
229 }).pipe(Effect.provide(fsLayer)),
230 );
231
232 it.effect("generates thread titles through Cursor SDK text generation", () =>
233 Effect.gen(function* () {
234 cursorSdkMock.prompt.mockResolvedValueOnce({
235 id: "run-cursor-title-generation-test",
236 status: "finished",
237 result: '{"title":"\\"Trim reconnect spinner status after resume.\\""}',
238 });
239 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
240 CURSOR_API_KEY: "test-cursor-key",
241 });
242
243 const generated = yield* textGeneration.generateThreadTitle({
244 cwd: process.cwd(),
245 message: "Fix the reconnect spinner after a resumed session.",
246 modelSelection: {
247 instanceId: ProviderInstanceId.make("cursor"),
248 model: "composer-2",
249 },
250 });
251
252 expect(generated.title).toBe("Trim reconnect spinner status after resume.");
253 }).pipe(Effect.provide(fsLayer)),
254 );
255
256 for (const status of ["error", "cancelled"] as const) {
257 it.effect(`rejects a ${status} Cursor SDK run that includes valid title JSON`, () =>
258 Effect.gen(function* () {
259 const promptResult = {
260 id: "run-cursor-partial-title-test",
261 status,
262 result: '{"title":"Partial title from a failed run."}',
263 } satisfies RunResult;
264 cursorSdkMock.prompt.mockResolvedValueOnce(promptResult);
265 const generation = yield* makeCursorTextGeneration(cursorSettings, {
266 CURSOR_API_KEY: "test-cursor-key",
267 });
268 const failure = yield* Effect.flip(
269 generation.generateThreadTitle({
270 cwd: process.cwd(),
271 message: "Fix the reconnect spinner after a resumed session.",
272 modelSelection: {
273 instanceId: ProviderInstanceId.make("cursor"),
274 model: "composer-2",
275 },
276 }),
277 );
278 expect(failure).toBeInstanceOf(TextGenerationError);
279 expect(failure.operation).toBe("generateThreadTitle");
280 expect(failure.detail).toBe(
281 status === "cancelled"
282 ? "Cursor SDK request was cancelled."
283 : "Cursor SDK request finished with an error.",
284 );
285 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
286 }).pipe(Effect.provide(fsLayer)),
287 );
288 }
289
290 it.effect("fails closed when ambient sandbox policy can expand write access", () =>
291 Effect.gen(function* () {
292 hasCustomPolicy = true;
293 const generation = yield* makeCursorTextGeneration(cursorSettings, { CURSOR_API_KEY: "key" });
294 const failure = yield* Effect.flip(
295 generation.generateThreadTitle({
296 cwd: "/real-workspace",
297 message: "Title",
298 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
299 }),
300 );
301 expect(failure.detail).toContain("custom ~/.cursor/sandbox.json");
302 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
303 }).pipe(Effect.provide(fsLayer)),
304 );
305
306 it.effect("cancels the native run when text generation times out", () =>
307 Effect.gen(function* () {
308 let started!: () => void;
309 const called = new Promise<void>((resolve) => {
310 started = resolve;
311 });
312 cursorSdkMock.prompt.mockImplementationOnce(() => {
313 started();
314 return new Promise(() => {});
315 });
316 const generation = yield* makeCursorTextGeneration(cursorSettings, { CURSOR_API_KEY: "key" });
317 const result = yield* generation
318 .generateThreadTitle({
319 cwd: "/real-workspace",
320 message: "Title",
321 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
322 })
323 .pipe(Effect.flip, Effect.forkScoped);
324 yield* Effect.promise(() => called);
325 yield* TestClock.adjust("180 seconds");
326 expect((yield* Fiber.join(result)).detail).toContain("timed out");
327 expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
328 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
329 }).pipe(Effect.provide(fsLayer), Effect.scoped),
330 );
331
332 for (const phase of ["create", "send"] as const) {
333 it.effect(`times out pending ${phase} and releases its late SDK resource`, () =>
334 Effect.gen(function* () {
335 let started!: () => void;
336 const called = new Promise<void>((resolve) => {
337 started = resolve;
338 });
339 let resolveLate!: (resource: unknown) => void;
340 const pending = new Promise<unknown>((resolve) => {
341 resolveLate = resolve;
342 });
343 const wait = vi.fn();
344 const agent = {
345 close: cursorSdkMock.close,
346 [Symbol.asyncDispose]: async () => {
347 cursorSdkMock.close();
348 },
349 send: async () => {
350 started();
351 return pending;
352 },
353 };
354 cursorSdkMock.create.mockImplementation(async () => {
355 if (phase === "create") {
356 started();
357 return pending;
358 }
359 return agent;
360 });
361 const generation = yield* makeCursorTextGeneration(cursorSettings, {
362 CURSOR_API_KEY: "key",
363 });
364 const result = yield* generation
365 .generateThreadTitle({
366 cwd: "/real-workspace",
367 message: "Title",
368 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
369 })
370 .pipe(Effect.flip, Effect.forkScoped);
371 yield* Effect.promise(() => called);
372 yield* TestClock.adjust("180 seconds");
373 expect((yield* Fiber.join(result)).detail).toContain("timed out");
374 let cleanup!: () => void;
375 const cleaned = new Promise<void>((resolve) => {
376 cleanup = resolve;
377 });
378 if (phase === "create") cursorSdkMock.close.mockImplementationOnce(cleanup);
379 else
380 cursorSdkMock.cancel.mockImplementationOnce(async () => {
381 cleanup();
382 });
383 resolveLate(
384 phase === "create" ? agent : { status: "running", cancel: cursorSdkMock.cancel, wait },
385 );
386 yield* Effect.promise(() => cleaned);
387 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
388 expect(wait).not.toHaveBeenCalled();
389 if (phase === "send") expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
390 }).pipe(Effect.provide(fsLayer), Effect.scoped),
391 );
392 }
393
394 it.effect("requires CURSOR_API_KEY before calling the SDK", () =>
395 Effect.gen(function* () {
396 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {});
397
398 const error = yield* Effect.flip(
399 textGeneration.generateCommitMessage({
400 cwd: process.cwd(),
401 branch: "feature/cursor-api-key",
402 stagedSummary: "M README.md",
403 stagedPatch: "diff --git a/README.md b/README.md",
404 modelSelection: {
405 instanceId: ProviderInstanceId.make("cursor"),
406 model: "composer-2",
407 },
408 }),
409 );
410
411 expect(error.detail).toBe("Sign in with Cursor or add CURSOR_API_KEY in provider settings.");
412 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
413 }).pipe(Effect.provide(fsLayer)),
414 );
415});