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 Layer from "effect/Layer";
8import * as Schema from "effect/Schema";
9import { createModelSelection } from "@t3tools/shared/model";
10import { beforeEach, vi } from "vite-plus/test";
11
12import { makeCursorTextGeneration } from "./textGeneration.ts";
13import * as CursorSdk from "./CursorSdk.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 storeOpen: vi.fn<(options: unknown) => Promise<unknown>>(),
21 storeDispose: 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 loadCursorSdk: () => ({
32 Agent: { create: cursorSdkMock.create },
33 createAgentPlatform: vi.fn(),
34 }),
35 loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.storeOpen } }),
36}));
37
38let hasCustomPolicy = false;
39const layerFs = FileSystem.layerNoop({
40 exists: () => Effect.succeed(hasCustomPolicy),
41 makeTempDirectoryScoped: () => Effect.succeed("/isolated-text-generation"),
42});
43const layerTest = Layer.merge(layerFs, CursorSdk.layer);
44
45const decodeCursorSettings = Schema.decodeSync(CursorSettings);
46const cursorSettings = decodeCursorSettings({ enabled: true });
47
48beforeEach(() => {
49 hasCustomPolicy = false;
50 cursorSdkMock.create.mockReset();
51 cursorSdkMock.send.mockReset();
52 cursorSdkMock.create.mockImplementation(async (options) => {
53 cursorSdkMock.send.mockImplementation(async (prompt) => ({
54 status: "running",
55 cancel: cursorSdkMock.cancel,
56 wait: () => cursorSdkMock.prompt(prompt, options),
57 }));
58 return {
59 close: cursorSdkMock.close,
60 [Symbol.asyncDispose]: async () => {
61 cursorSdkMock.close();
62 },
63 send: cursorSdkMock.send,
64 };
65 });
66 cursorSdkMock.close.mockClear();
67 cursorSdkMock.cancel.mockClear();
68 cursorSdkMock.storeDispose.mockClear();
69 cursorSdkMock.storeOpen.mockReset();
70 cursorSdkMock.storeOpen.mockResolvedValue({ dispose: cursorSdkMock.storeDispose });
71 cursorSdkMock.prompt.mockReset();
72 cursorSdkMock.prompt.mockResolvedValue({
73 id: "run-cursor-text-generation-test",
74 status: "finished",
75 result:
76 '{"subject":"Add generated commit message","body":"- verify cursor sdk text generation"}',
77 });
78});
79
80describe("CursorTextGeneration", () => {
81 it.effect("resolves the browser credential for every request after an account change", () =>
82 Effect.gen(function* () {
83 let apiKey = "first-browser-key";
84 const generation = yield* makeCursorTextGeneration(
85 cursorSettings,
86 {},
87 Effect.sync(() => apiKey),
88 );
89 const input = {
90 cwd: process.cwd(),
91 branch: "feature/cursor",
92 stagedSummary: "M file.ts",
93 stagedPatch: "diff",
94 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
95 };
96 yield* generation.generateCommitMessage(input);
97 expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
98 expect.objectContaining({ apiKey: "first-browser-key" }),
99 );
100 apiKey = "second-browser-key";
101 yield* generation.generateCommitMessage(input);
102 expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
103 expect.objectContaining({ apiKey: "second-browser-key" }),
104 );
105 }).pipe(Effect.provide(layerTest)),
106 );
107
108 it.effect("continues in the temp directory when the SDK cannot sandbox", () =>
109 Effect.gen(function* () {
110 cursorSdkMock.create.mockImplementationOnce(async () => {
111 throw new Error(
112 "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.",
113 );
114 });
115 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
116 CURSOR_API_KEY: "test-cursor-key",
117 });
118
119 const generated = yield* textGeneration.generateCommitMessage({
120 cwd: process.cwd(),
121 branch: "feature/cursor-text-generation",
122 stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
123 stagedPatch: "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts",
124 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2"),
125 });
126
127 expect(generated.subject).toBe("Add generated commit message");
128 expect(cursorSdkMock.create).toHaveBeenCalledTimes(2);
129 expect(cursorSdkMock.create.mock.calls[0]?.[0]).toMatchObject({
130 local: { sandboxOptions: { enabled: true } },
131 });
132 expect(cursorSdkMock.create.mock.calls[1]?.[0]).toMatchObject({
133 local: {
134 cwd: "/isolated-text-generation",
135 store: { dispose: cursorSdkMock.storeDispose },
136 autoReview: false,
137 sandboxOptions: { enabled: false },
138 settingSources: [],
139 enableAgentRetries: true,
140 },
141 });
142 }).pipe(Effect.provide(layerTest)),
143 );
144
145 it.effect("accepts json objects with extra assistant text around them", () =>
146 Effect.gen(function* () {
147 cursorSdkMock.prompt.mockResolvedValueOnce({
148 id: "run-cursor-text-generation-test",
149 status: "finished",
150 result:
151 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
152 });
153 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
154 CURSOR_API_KEY: "test-cursor-key",
155 });
156
157 const generated = yield* textGeneration.generateCommitMessage({
158 cwd: process.cwd(),
159 branch: "feature/cursor-noisy-json",
160 stagedSummary: "M README.md",
161 stagedPatch: "diff --git a/README.md b/README.md",
162 modelSelection: {
163 instanceId: ProviderInstanceId.make("cursor"),
164 model: "composer-2",
165 },
166 });
167
168 expect(generated.subject).toBe("Update README dummy comment with attribution and date");
169 expect(generated.body).toBe("");
170 }).pipe(Effect.provide(layerTest)),
171 );
172
173 it.effect("generates thread titles through Cursor SDK text generation", () =>
174 Effect.gen(function* () {
175 cursorSdkMock.prompt.mockResolvedValueOnce({
176 id: "run-cursor-title-generation-test",
177 status: "finished",
178 result: '{"title":"\\"Trim reconnect spinner status after resume.\\""}',
179 });
180 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
181 CURSOR_API_KEY: "test-cursor-key",
182 });
183
184 const generated = yield* textGeneration.generateThreadTitle({
185 cwd: process.cwd(),
186 message: "Fix the reconnect spinner after a resumed session.",
187 modelSelection: {
188 instanceId: ProviderInstanceId.make("cursor"),
189 model: "composer-2",
190 },
191 });
192
193 expect(generated.title).toBe("Trim reconnect spinner status after resume.");
194 }).pipe(Effect.provide(layerTest)),
195 );
196
197 it.effect.each([
198 {
199 status: "error",
200 error: { message: "Raw Cursor usage text", code: "PRO_USER_USAGE_LIMIT" },
201 detail:
202 "Cursor usage limit reached. Try again later or choose another text-generation provider.",
203 },
204 {
205 status: "error",
206 error: { message: "Raw Cursor backend text", code: "internal" },
207 detail: "Cursor SDK request finished with an error.",
208 },
209 { status: "cancelled", error: undefined, detail: "Cursor SDK request was cancelled." },
210 ] as const)(
211 "rejects a $status Cursor SDK run ($error.code) that includes valid title JSON",
212 ({ status, error, detail }) =>
213 Effect.gen(function* () {
214 const promptResult = {
215 id: "run-cursor-partial-title-test",
216 status,
217 result: '{"title":"Partial title from a failed run."}',
218 ...(error ? { error } : {}),
219 } satisfies RunResult;
220 cursorSdkMock.prompt.mockResolvedValueOnce(promptResult);
221 const generation = yield* makeCursorTextGeneration(cursorSettings, {
222 CURSOR_API_KEY: "test-cursor-key",
223 });
224 const failure = yield* Effect.flip(
225 generation.generateThreadTitle({
226 cwd: process.cwd(),
227 message: "Fix the reconnect spinner after a resumed session.",
228 modelSelection: {
229 instanceId: ProviderInstanceId.make("cursor"),
230 model: "composer-2",
231 },
232 }),
233 );
234 expect(failure).toBeInstanceOf(TextGenerationError);
235 expect(failure.operation).toBe("generateThreadTitle");
236 expect(failure.detail).toBe(detail);
237 expect(failure.message).not.toContain("Raw Cursor");
238 expect(failure.cause).toBe(error);
239 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
240 }).pipe(Effect.provide(layerTest)),
241 );
242
243 it.effect("fails closed when ambient sandbox policy can expand write access", () =>
244 Effect.gen(function* () {
245 hasCustomPolicy = true;
246 const generation = yield* makeCursorTextGeneration(cursorSettings, { CURSOR_API_KEY: "key" });
247 const failure = yield* Effect.flip(
248 generation.generateThreadTitle({
249 cwd: "/real-workspace",
250 message: "Title",
251 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
252 }),
253 );
254 expect(failure.detail).toContain("custom ~/.cursor/sandbox.json");
255 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
256 }).pipe(Effect.provide(layerTest)),
257 );
258
259 it.effect("requires CURSOR_API_KEY before calling the SDK", () =>
260 Effect.gen(function* () {
261 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {});
262
263 const error = yield* Effect.flip(
264 textGeneration.generateCommitMessage({
265 cwd: process.cwd(),
266 branch: "feature/cursor-api-key",
267 stagedSummary: "M README.md",
268 stagedPatch: "diff --git a/README.md b/README.md",
269 modelSelection: {
270 instanceId: ProviderInstanceId.make("cursor"),
271 model: "composer-2",
272 },
273 }),
274 );
275
276 expect(error.detail).toBe("Sign in with Cursor or add CURSOR_API_KEY in provider settings.");
277 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
278 }).pipe(Effect.provide(layerTest)),
279 );
280});