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

textGeneration.test.ts

288 lines11.0 KB

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