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 Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as TestClock from "effect/testing/TestClock";
12import { createModelSelection } from "@t3tools/shared/model";
13import { beforeEach, vi } from "vite-plus/test";
14
15import { makeCursorTextGeneration } from "./textGeneration.ts";
16import * as CursorSdk from "./CursorSdk.ts";
17
18const cursorSdkMock = vi.hoisted(() => ({
19 create: vi.fn<(options: unknown) => Promise<unknown>>(),
20 send: vi.fn<(prompt: string) => Promise<unknown>>(),
21 close: vi.fn(),
22 cancel: vi.fn(async () => {}),
23 storeOpen: vi.fn<(options: unknown) => Promise<unknown>>(),
24 storeDispose: vi.fn(async () => {}),
25 prompt: vi.fn<(prompt: string, options: unknown) => Promise<RunResult>>(async () => ({
26 id: "run-cursor-text-generation-test",
27 status: "finished",
28 result:
29 '{"subject":"Add generated commit message","body":"- verify cursor sdk text generation"}',
30 })),
31}));
32
33vi.mock("./sdk.ts", () => ({
34 loadCursorSdk: () => ({
35 Agent: { create: cursorSdkMock.create },
36 createAgentPlatform: vi.fn(),
37 }),
38 loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.storeOpen } }),
39}));
40
41let hasCustomPolicy = false;
42const layerFs = FileSystem.layerNoop({
43 exists: () => Effect.succeed(hasCustomPolicy),
44 makeTempDirectoryScoped: () => Effect.succeed("/isolated-text-generation"),
45});
46const layerTest = CursorSdk.layer.pipe(Layer.provideMerge(Layer.merge(layerFs, Path.layer)));
47
48const decodeCursorSettings = Schema.decodeSync(CursorSettings);
49const cursorSettings = decodeCursorSettings({ enabled: true });
50
51beforeEach(() => {
52 hasCustomPolicy = false;
53 cursorSdkMock.create.mockReset();
54 cursorSdkMock.send.mockReset();
55 cursorSdkMock.create.mockImplementation(async (options) => {
56 cursorSdkMock.send.mockImplementation(async (prompt) => {
57 const run = {
58 status: "running",
59 cancel: cursorSdkMock.cancel,
60 wait: async () => {
61 const result = await cursorSdkMock.prompt(prompt, options);
62 run.status = result.status;
63 return result;
64 },
65 };
66 return run;
67 });
68 return {
69 close: cursorSdkMock.close,
70 [Symbol.asyncDispose]: async () => {
71 cursorSdkMock.close();
72 },
73 send: cursorSdkMock.send,
74 };
75 });
76 cursorSdkMock.close.mockClear();
77 cursorSdkMock.cancel.mockClear();
78 cursorSdkMock.storeDispose.mockClear();
79 cursorSdkMock.storeOpen.mockReset();
80 cursorSdkMock.storeOpen.mockResolvedValue({ dispose: cursorSdkMock.storeDispose });
81 cursorSdkMock.prompt.mockReset();
82 cursorSdkMock.prompt.mockResolvedValue({
83 id: "run-cursor-text-generation-test",
84 status: "finished",
85 result:
86 '{"subject":"Add generated commit message","body":"- verify cursor sdk text generation"}',
87 });
88});
89
90describe("CursorTextGeneration", () => {
91 it.effect("resolves the browser credential for every request after an account change", () =>
92 Effect.gen(function* () {
93 let apiKey = "first-browser-key";
94 const generation = yield* makeCursorTextGeneration(
95 cursorSettings,
96 {},
97 Effect.sync(() => apiKey),
98 );
99 const input = {
100 cwd: process.cwd(),
101 branch: "feature/cursor",
102 stagedSummary: "M file.ts",
103 stagedPatch: "diff",
104 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
105 };
106 yield* generation.generateCommitMessage(input);
107 expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
108 expect.objectContaining({ apiKey: "first-browser-key" }),
109 );
110 apiKey = "second-browser-key";
111 yield* generation.generateCommitMessage(input);
112 expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
113 expect.objectContaining({ apiKey: "second-browser-key" }),
114 );
115 }).pipe(Effect.provide(layerTest)),
116 );
117
118 it.effect("recovers invalid output after the SDK cannot sandbox", () =>
119 Effect.gen(function* () {
120 // The SDK checks sandbox support lazily, so create succeeds and send rejects.
121 cursorSdkMock.create.mockImplementationOnce(async () => ({
122 close: cursorSdkMock.close,
123 [Symbol.asyncDispose]: async () => {
124 cursorSdkMock.close();
125 },
126 send: async () => {
127 throw new Error(
128 "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.",
129 );
130 },
131 }));
132 cursorSdkMock.prompt.mockResolvedValueOnce({
133 id: "invalid-output-after-sandbox-fallback",
134 status: "finished",
135 result: "Not JSON",
136 });
137 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
138 CURSOR_API_KEY: "test-cursor-key",
139 });
140
141 const generated = yield* textGeneration.generateCommitMessage({
142 cwd: process.cwd(),
143 branch: "feature/cursor-text-generation",
144 stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
145 stagedPatch: "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts",
146 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2"),
147 });
148
149 expect(generated.subject).toBe("Add generated commit message");
150 expect(cursorSdkMock.create).toHaveBeenCalledTimes(3);
151 for (const [options] of cursorSdkMock.create.mock.calls) {
152 expect(options).toMatchObject({ mode: "agent", tools: [] });
153 }
154 expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
155 expect(cursorSdkMock.close).toHaveBeenCalledTimes(3);
156 expect(cursorSdkMock.create.mock.calls[0]?.[0]).toMatchObject({
157 local: { sandboxOptions: { enabled: true } },
158 });
159 expect(cursorSdkMock.create.mock.calls[1]?.[0]).toMatchObject({
160 local: {
161 cwd: "/isolated-text-generation",
162 store: { dispose: cursorSdkMock.storeDispose },
163 autoReview: false,
164 sandboxOptions: { enabled: false },
165 settingSources: [],
166 enableAgentRetries: true,
167 },
168 });
169 }).pipe(Effect.provide(layerTest)),
170 );
171
172 it.effect("accepts json objects with extra assistant text around them", () =>
173 Effect.gen(function* () {
174 cursorSdkMock.prompt.mockResolvedValueOnce({
175 id: "run-cursor-text-generation-test",
176 status: "finished",
177 result:
178 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
179 });
180 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
181 CURSOR_API_KEY: "test-cursor-key",
182 });
183
184 const generated = yield* textGeneration.generateCommitMessage({
185 cwd: process.cwd(),
186 branch: "feature/cursor-noisy-json",
187 stagedSummary: "M README.md",
188 stagedPatch: "diff --git a/README.md b/README.md",
189 modelSelection: {
190 instanceId: ProviderInstanceId.make("cursor"),
191 model: "composer-2",
192 },
193 });
194
195 expect(generated.subject).toBe("Update README dummy comment with attribution and date");
196 expect(generated.body).toBe("");
197 expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
198 }).pipe(Effect.provide(layerTest)),
199 );
200
201 it.effect.each([
202 { name: "invalid JSON", result: "Add a generated commit message" },
203 {
204 name: "a body with the wrong type",
205 result: '{"subject":"Add generated commit message","body":[]}',
206 },
207 ])("retries $name with a fresh agent before returning a commit message", ({ result }) =>
208 Effect.gen(function* () {
209 cursorSdkMock.prompt
210 .mockResolvedValueOnce({ id: "invalid-output", status: "finished", result })
211 .mockImplementationOnce(async () => {
212 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
213 return {
214 id: "valid-output",
215 status: "finished",
216 result: '{"subject":"Add generated commit message","body":""}',
217 };
218 });
219 const generation = yield* makeCursorTextGeneration(cursorSettings, {
220 CURSOR_API_KEY: "test-cursor-key",
221 });
222 const generated = yield* generation.generateCommitMessage({
223 cwd: process.cwd(),
224 branch: "feature/cursor",
225 stagedSummary: "M file.ts",
226 stagedPatch: "diff",
227 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
228 });
229
230 expect(generated).toEqual({
231 subject: "Add generated commit message",
232 body: "",
233 });
234 expect(cursorSdkMock.create).toHaveBeenCalledTimes(2);
235 expect(cursorSdkMock.close).toHaveBeenCalledTimes(2);
236 expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
237 }).pipe(Effect.provide(layerTest)),
238 );
239
240 it.effect("stops after a second invalid reply and preserves the validation error", () =>
241 Effect.gen(function* () {
242 cursorSdkMock.prompt.mockResolvedValue({
243 id: "invalid-output",
244 status: "finished",
245 result: '{"subject":"Add generated commit message","body":null}',
246 });
247 const generation = yield* makeCursorTextGeneration(cursorSettings, {
248 CURSOR_API_KEY: "test-cursor-key",
249 });
250 const failure = yield* Effect.flip(
251 generation.generateCommitMessage({
252 cwd: process.cwd(),
253 branch: null,
254 stagedSummary: "M file.ts",
255 stagedPatch: "diff",
256 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
257 }),
258 );
259
260 expect(failure.operation).toBe("generateCommitMessage");
261 expect(failure.detail).toBe("Cursor SDK returned invalid structured output.");
262 expect(Schema.isSchemaError(failure.cause)).toBe(true);
263 expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
264 }).pipe(Effect.provide(layerTest)),
265 );
266
267 it.effect("keeps both attempts inside the original deadline and cancels the pending retry", () =>
268 Effect.gen(function* () {
269 const firstStarted = Promise.withResolvers<void>();
270 const retryStarted = Promise.withResolvers<void>();
271 const firstResult = Promise.withResolvers<RunResult>();
272 cursorSdkMock.prompt
273 .mockImplementationOnce(() => {
274 firstStarted.resolve();
275 return firstResult.promise;
276 })
277 .mockImplementationOnce(() => {
278 retryStarted.resolve();
279 return new Promise(() => {});
280 });
281 const generation = yield* makeCursorTextGeneration(cursorSettings, {
282 CURSOR_API_KEY: "test-cursor-key",
283 });
284 const request = yield* generation
285 .generateThreadTitle({
286 cwd: process.cwd(),
287 message: "Fix reconnect",
288 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
289 })
290 .pipe(Effect.flip, Effect.forkScoped);
291
292 yield* Effect.promise(() => firstStarted.promise);
293 yield* TestClock.adjust("2 minutes");
294 firstResult.resolve({ id: "invalid-output", status: "finished", result: "Not JSON" });
295 yield* Effect.promise(() => retryStarted.promise);
296 yield* TestClock.adjust("1 minute");
297
298 expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
299 expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
300 expect((yield* Fiber.join(request)).detail).toBe("Cursor SDK request timed out.");
301 expect(cursorSdkMock.close).toHaveBeenCalledTimes(2);
302 expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
303 }).pipe(Effect.scoped, Effect.provide(layerTest)),
304 );
305
306 it.effect("generates thread titles through Cursor SDK text generation", () =>
307 Effect.gen(function* () {
308 cursorSdkMock.prompt.mockResolvedValueOnce({
309 id: "run-cursor-title-generation-test",
310 status: "finished",
311 result: '{"title":"\\"Trim reconnect spinner status after resume.\\""}',
312 });
313 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
314 CURSOR_API_KEY: "test-cursor-key",
315 });
316
317 const generated = yield* textGeneration.generateThreadTitle({
318 cwd: process.cwd(),
319 message: "Fix the reconnect spinner after a resumed session.",
320 modelSelection: {
321 instanceId: ProviderInstanceId.make("cursor"),
322 model: "composer-2",
323 },
324 });
325
326 expect(generated.title).toBe("Trim reconnect spinner status after resume.");
327 }).pipe(Effect.provide(layerTest)),
328 );
329
330 it.effect.each([
331 {
332 status: "error",
333 error: { message: "Raw Cursor usage text", code: "PRO_USER_USAGE_LIMIT" },
334 detail:
335 "Grok Build usage limit reached. Try again later or choose another text-generation provider.",
336 },
337 {
338 status: "error",
339 error: { message: "Raw Cursor backend text", code: "internal" },
340 detail: "Cursor SDK request finished with an error.",
341 },
342 { status: "cancelled", error: undefined, detail: "Cursor SDK request was cancelled." },
343 { status: "finished", error: undefined, detail: "Cursor SDK returned empty output." },
344 ] as const)(
345 "does not retry an unsuccessful or empty $status Cursor SDK run ($error.code)",
346 ({ status, error, detail }) =>
347 Effect.gen(function* () {
348 const promptResult = {
349 id: "run-cursor-partial-title-test",
350 status,
351 result: status === "finished" ? " " : '{"title":"Partial title from a failed run."}',
352 ...(error ? { error } : {}),
353 } satisfies RunResult;
354 cursorSdkMock.prompt.mockResolvedValueOnce(promptResult);
355 const generation = yield* makeCursorTextGeneration(cursorSettings, {
356 CURSOR_API_KEY: "test-cursor-key",
357 });
358 const failure = yield* Effect.flip(
359 generation.generateThreadTitle({
360 cwd: process.cwd(),
361 message: "Fix the reconnect spinner after a resumed session.",
362 modelSelection: {
363 instanceId: ProviderInstanceId.make("cursor"),
364 model: "composer-2",
365 },
366 }),
367 );
368 expect(failure).toBeInstanceOf(TextGenerationError);
369 expect(failure.operation).toBe("generateThreadTitle");
370 expect(failure.detail).toBe(detail);
371 expect(failure.message).not.toContain("Raw Cursor");
372 expect(failure.cause).toBe(error);
373 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
374 expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
375 }).pipe(Effect.provide(layerTest)),
376 );
377
378 it.effect("fails closed when ambient sandbox policy can expand write access", () =>
379 Effect.gen(function* () {
380 hasCustomPolicy = true;
381 const generation = yield* makeCursorTextGeneration(cursorSettings, { CURSOR_API_KEY: "key" });
382 const failure = yield* Effect.flip(
383 generation.generateThreadTitle({
384 cwd: "/real-workspace",
385 message: "Title",
386 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
387 }),
388 );
389 expect(failure.detail).toContain("custom ~/.cursor/sandbox.json");
390 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
391 }).pipe(Effect.provide(layerTest)),
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(
412 "Sign in with Grok Build or add CURSOR_API_KEY in provider settings.",
413 );
414 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
415 }).pipe(Effect.provide(layerTest)),
416 );
417
418 it.effect("delegates to sdkRunner.textGenerate without loading the in-process SDK", () =>
419 Effect.gen(function* () {
420 const textGenerate = vi.fn(() =>
421 Effect.succeed({
422 id: "run-worker-title",
423 status: "finished",
424 result: JSON.stringify({ title: "Worker title" }),
425 } satisfies RunResult),
426 );
427 const generation = yield* makeCursorTextGeneration(
428 cursorSettings,
429 { CURSOR_API_KEY: "test-cursor-key" },
430 undefined,
431 undefined,
432 undefined,
433 undefined,
434 {
435 open: () => Effect.die("unused"),
436 assertComplete: Effect.void,
437 textGenerate,
438 },
439 );
440 const result = yield* generation.generateThreadTitle({
441 cwd: process.cwd(),
442 message: "Run text generation out of process",
443 modelSelection: {
444 instanceId: ProviderInstanceId.make("cursor"),
445 model: "composer-2",
446 },
447 });
448 expect(result.title).toBe("Worker title");
449 expect(textGenerate).toHaveBeenCalledOnce();
450 expect(cursorSdkMock.create).not.toHaveBeenCalled();
451 expect(cursorSdkMock.storeOpen).not.toHaveBeenCalled();
452 }).pipe(Effect.provide(layerTest)),
453 );
454});