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(["error", "cancelled"] as const)(
198 "rejects a %s Cursor SDK run that includes valid title JSON",
199 (status) =>
200 Effect.gen(function* () {
201 const promptResult = {
202 id: "run-cursor-partial-title-test",
203 status,
204 result: '{"title":"Partial title from a failed run."}',
205 } satisfies RunResult;
206 cursorSdkMock.prompt.mockResolvedValueOnce(promptResult);
207 const generation = yield* makeCursorTextGeneration(cursorSettings, {
208 CURSOR_API_KEY: "test-cursor-key",
209 });
210 const failure = yield* Effect.flip(
211 generation.generateThreadTitle({
212 cwd: process.cwd(),
213 message: "Fix the reconnect spinner after a resumed session.",
214 modelSelection: {
215 instanceId: ProviderInstanceId.make("cursor"),
216 model: "composer-2",
217 },
218 }),
219 );
220 expect(failure).toBeInstanceOf(TextGenerationError);
221 expect(failure.operation).toBe("generateThreadTitle");
222 expect(failure.detail).toBe(
223 status === "cancelled"
224 ? "Cursor SDK request was cancelled."
225 : "Cursor SDK request finished with an error.",
226 );
227 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
228 }).pipe(Effect.provide(layerTest)),
229 );
230
231 it.effect("fails closed when ambient sandbox policy can expand write access", () =>
232 Effect.gen(function* () {
233 hasCustomPolicy = true;
234 const generation = yield* makeCursorTextGeneration(cursorSettings, { CURSOR_API_KEY: "key" });
235 const failure = yield* Effect.flip(
236 generation.generateThreadTitle({
237 cwd: "/real-workspace",
238 message: "Title",
239 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
240 }),
241 );
242 expect(failure.detail).toContain("custom ~/.cursor/sandbox.json");
243 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
244 }).pipe(Effect.provide(layerTest)),
245 );
246
247 it.effect("requires CURSOR_API_KEY before calling the SDK", () =>
248 Effect.gen(function* () {
249 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {});
250
251 const error = yield* Effect.flip(
252 textGeneration.generateCommitMessage({
253 cwd: process.cwd(),
254 branch: "feature/cursor-api-key",
255 stagedSummary: "M README.md",
256 stagedPatch: "diff --git a/README.md b/README.md",
257 modelSelection: {
258 instanceId: ProviderInstanceId.make("cursor"),
259 model: "composer-2",
260 },
261 }),
262 );
263
264 expect(error.detail).toBe("Sign in with Cursor or add CURSOR_API_KEY in provider settings.");
265 expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
266 }).pipe(Effect.provide(layerTest)),
267 );
268});