Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

textGeneration.test.ts

522 lines19.7 KB

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