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