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