Skip to content

Commit 0f5e27b

Browse files
committed
fix(provider-cursor): retry invalid text generation once
1 parent dc84b09 commit 0f5e27b

2 files changed

Lines changed: 191 additions & 18 deletions

File tree

‎packages/provider-cursor/src/server/textGeneration.test.ts‎

Lines changed: 173 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import { ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
33
import { CursorSettings } from "../settings.ts";
44
import { describe, expect, it } from "@effect/vitest";
55
import * as Effect from "effect/Effect";
6+
import * as Fiber from "effect/Fiber";
67
import * as FileSystem from "effect/FileSystem";
78
import * as Layer from "effect/Layer";
89
import * as Schema from "effect/Schema";
10+
import * as TestClock from "effect/testing/TestClock";
911
import { createModelSelection } from "@t3tools/shared/model";
1012
import { beforeEach, vi } from "vite-plus/test";
1113

@@ -48,11 +50,18 @@ beforeEach(() => {
4850
cursorSdkMock.create.mockReset();
4951
cursorSdkMock.send.mockReset();
5052
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-
}));
53+
cursorSdkMock.send.mockImplementation(async (prompt) => {
54+
const run = {
55+
status: "running",
56+
cancel: cursorSdkMock.cancel,
57+
wait: async () => {
58+
const result = await cursorSdkMock.prompt(prompt, options);
59+
run.status = result.status;
60+
return result;
61+
},
62+
};
63+
return run;
64+
});
5665
return {
5766
close: cursorSdkMock.close,
5867
[Symbol.asyncDispose]: async () => {
@@ -165,9 +174,123 @@ describe("CursorTextGeneration", () => {
165174

166175
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
167176
expect(generated.body).toBe("");
177+
expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
178+
}).pipe(Effect.provide(layerTest)),
179+
);
180+
181+
it.effect.each([
182+
{ name: "invalid JSON", result: "Add a generated commit message" },
183+
{
184+
name: "a body with the wrong type",
185+
result: '{"subject":"Add generated commit message","body":[],"branch":"generated-message"}',
186+
},
187+
{ name: "a missing branch", result: '{"subject":"Add generated commit message","body":""}' },
188+
])("retries $name with a fresh agent before returning a commit message", ({ result }) =>
189+
Effect.gen(function* () {
190+
cursorSdkMock.prompt
191+
.mockResolvedValueOnce({ id: "invalid-output", status: "finished", result })
192+
.mockImplementationOnce(async () => {
193+
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
194+
return {
195+
id: "valid-output",
196+
status: "finished",
197+
result:
198+
'{"subject":"Add generated commit message","body":"","branch":"generated-message"}',
199+
};
200+
});
201+
const generation = yield* makeCursorTextGeneration(cursorSettings, {
202+
CURSOR_API_KEY: "test-cursor-key",
203+
});
204+
const generated = yield* generation.generateCommitMessage({
205+
cwd: process.cwd(),
206+
branch: "feature/cursor",
207+
stagedSummary: "M file.ts",
208+
stagedPatch: "diff",
209+
includeBranch: true,
210+
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
211+
});
212+
213+
expect(generated).toEqual({
214+
subject: "Add generated commit message",
215+
body: "",
216+
branch: "feature/generated-message",
217+
});
218+
expect(cursorSdkMock.create).toHaveBeenCalledTimes(2);
219+
expect(cursorSdkMock.send.mock.calls[1]).toEqual(cursorSdkMock.send.mock.calls[0]);
220+
expect(cursorSdkMock.close).toHaveBeenCalledTimes(2);
221+
expect(cursorSdkMock.cancel).not.toHaveBeenCalled();
222+
expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
168223
}).pipe(Effect.provide(layerTest)),
169224
);
170225

226+
it.effect("stops after a second invalid reply and preserves the validation error", () =>
227+
Effect.gen(function* () {
228+
cursorSdkMock.prompt.mockResolvedValue({
229+
id: "invalid-output",
230+
status: "finished",
231+
result: '{"subject":"Add generated commit message","body":null}',
232+
});
233+
const generation = yield* makeCursorTextGeneration(cursorSettings, {
234+
CURSOR_API_KEY: "test-cursor-key",
235+
});
236+
const failure = yield* Effect.flip(
237+
generation.generateCommitMessage({
238+
cwd: process.cwd(),
239+
branch: null,
240+
stagedSummary: "M file.ts",
241+
stagedPatch: "diff",
242+
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
243+
}),
244+
);
245+
246+
expect(failure.operation).toBe("generateCommitMessage");
247+
expect(failure.detail).toBe("Cursor SDK returned invalid structured output.");
248+
expect(Schema.isSchemaError(failure.cause)).toBe(true);
249+
expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
250+
expect(cursorSdkMock.close).toHaveBeenCalledTimes(2);
251+
expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
252+
}).pipe(Effect.provide(layerTest)),
253+
);
254+
255+
it.effect("keeps both attempts inside the original deadline and cancels the pending retry", () =>
256+
Effect.gen(function* () {
257+
const firstStarted = Promise.withResolvers<void>();
258+
const retryStarted = Promise.withResolvers<void>();
259+
const firstResult = Promise.withResolvers<RunResult>();
260+
cursorSdkMock.prompt
261+
.mockImplementationOnce(() => {
262+
firstStarted.resolve();
263+
return firstResult.promise;
264+
})
265+
.mockImplementationOnce(() => {
266+
retryStarted.resolve();
267+
return new Promise(() => {});
268+
});
269+
const generation = yield* makeCursorTextGeneration(cursorSettings, {
270+
CURSOR_API_KEY: "test-cursor-key",
271+
});
272+
const request = yield* generation
273+
.generateThreadTitle({
274+
cwd: process.cwd(),
275+
message: "Fix reconnect",
276+
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
277+
})
278+
.pipe(Effect.flip, Effect.forkScoped);
279+
280+
yield* Effect.promise(() => firstStarted.promise);
281+
yield* TestClock.adjust("2 minutes");
282+
firstResult.resolve({ id: "invalid-output", status: "finished", result: "Not JSON" });
283+
yield* Effect.promise(() => retryStarted.promise);
284+
yield* TestClock.adjust("1 minute");
285+
286+
expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
287+
expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
288+
expect((yield* Fiber.join(request)).detail).toBe("Cursor SDK request timed out.");
289+
expect(cursorSdkMock.close).toHaveBeenCalledTimes(2);
290+
expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
291+
}).pipe(Effect.scoped, Effect.provide(layerTest)),
292+
);
293+
171294
it.effect("generates thread titles through Cursor SDK text generation", () =>
172295
Effect.gen(function* () {
173296
cursorSdkMock.prompt.mockResolvedValueOnce({
@@ -192,6 +315,50 @@ describe("CursorTextGeneration", () => {
192315
}).pipe(Effect.provide(layerTest)),
193316
);
194317

318+
it.effect.each([undefined, "", " "])("does not retry empty output (%s)", (result) =>
319+
Effect.gen(function* () {
320+
cursorSdkMock.prompt.mockResolvedValueOnce({
321+
id: "empty-output",
322+
status: "finished",
323+
...(result === undefined ? {} : { result }),
324+
});
325+
const generation = yield* makeCursorTextGeneration(cursorSettings, {
326+
CURSOR_API_KEY: "test-cursor-key",
327+
});
328+
const failure = yield* Effect.flip(
329+
generation.generateThreadTitle({
330+
cwd: process.cwd(),
331+
message: "Fix reconnect",
332+
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
333+
}),
334+
);
335+
336+
expect(failure.detail).toBe("Cursor SDK returned empty output.");
337+
expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
338+
}).pipe(Effect.provide(layerTest)),
339+
);
340+
341+
it.effect("does not retry an SDK request rejection", () =>
342+
Effect.gen(function* () {
343+
cursorSdkMock.prompt.mockRejectedValueOnce(new Error("SDK request failed"));
344+
const generation = yield* makeCursorTextGeneration(cursorSettings, {
345+
CURSOR_API_KEY: "test-cursor-key",
346+
});
347+
const failure = yield* Effect.flip(
348+
generation.generateThreadTitle({
349+
cwd: process.cwd(),
350+
message: "Fix reconnect",
351+
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
352+
}),
353+
);
354+
355+
expect(failure.detail).toBe("Cursor SDK text generation failed.");
356+
expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
357+
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
358+
expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
359+
}).pipe(Effect.provide(layerTest)),
360+
);
361+
195362
it.effect.each(["error", "cancelled"] as const)(
196363
"rejects a %s Cursor SDK run that includes valid title JSON",
197364
(status) =>
@@ -223,6 +390,7 @@ describe("CursorTextGeneration", () => {
223390
: "Cursor SDK request finished with an error.",
224391
);
225392
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
393+
expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
226394
}).pipe(Effect.provide(layerTest)),
227395
);
228396

‎packages/provider-cursor/src/server/textGeneration.ts‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,24 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
156156
)
157157
: Effect.void,
158158
);
159-
return yield* Effect.tryPromise(() => run.wait());
160-
}).pipe(Effect.scoped);
161-
const promptResult = yield* request.pipe(
159+
const promptResult = yield* Effect.tryPromise(() => run.wait());
160+
const rawResult = promptResult.result?.trim() ?? "";
161+
if (promptResult.status !== "finished" || !rawResult) {
162+
return yield* new TextGenerationError({
163+
operation,
164+
detail: cursorSdkResultDetail(promptResult),
165+
});
166+
}
167+
168+
return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
169+
}).pipe(
170+
Effect.scoped,
171+
Effect.retry({
172+
times: 1,
173+
while: (cause) => isTextGenerationError(cause) && Schema.isSchemaError(cause.cause),
174+
}),
175+
);
176+
return yield* request.pipe(
162177
Effect.timeoutOption(CURSOR_TIMEOUT_MS),
163178
Effect.flatMap(
164179
Option.match({
@@ -173,16 +188,6 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
173188
}),
174189
),
175190
);
176-
177-
const rawResult = promptResult.result?.trim() ?? "";
178-
if (promptResult.status !== "finished" || !rawResult) {
179-
return yield* new TextGenerationError({
180-
operation,
181-
detail: cursorSdkResultDetail(promptResult),
182-
});
183-
}
184-
185-
return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
186191
},
187192
(effect, input) => {
188193
const { operation } = input;

0 commit comments

Comments
 (0)