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