@devries-cameron20 / t3code-1 / commits / e26a76af86
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(provider-cursor): retry invalid text generation once (#26056)

Co-authored-by: maria-rcks <maria@kuuro.net>

Afonso Ferreira committed Nov 19, 2026 at 05:57 UTC e26a76af86ed64f1957a693d450c590442643e76
2 files changed +163 -37
packages/provider-cursor/src/server/textGeneration.test.ts
+133 -9
@@ -3,10 +3,12 @@ import { ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
3 import { CursorSettings } from "../settings.ts";
4 import { describe, expect, it } from "@effect/vitest";
5 import * as Effect from "effect/Effect";
6 +import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Path from "effect/Path";
10 import * as Schema from "effect/Schema";
11 +import * as TestClock from "effect/testing/TestClock";
12 import { createModelSelection } from "@t3tools/shared/model";
13 import { beforeEach, vi } from "vite-plus/test";
14
@@ -51,11 +53,18 @@ beforeEach(() => {
53 cursorSdkMock.create.mockReset();
54 cursorSdkMock.send.mockReset();
55 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 - }));
56 + cursorSdkMock.send.mockImplementation(async (prompt) => {
57 + const run = {
58 + status: "running",
59 + cancel: cursorSdkMock.cancel,
60 + wait: async () => {
61 + const result = await cursorSdkMock.prompt(prompt, options);
62 + run.status = result.status;
63 + return result;
64 + },
65 + };
66 + return run;
67 + });
68 return {
69 close: cursorSdkMock.close,
70 [Symbol.asyncDispose]: async () => {
@@ -106,7 +115,7 @@ describe("CursorTextGeneration", () => {
115 }).pipe(Effect.provide(layerTest)),
116 );
117
109 - it.effect("continues in the temp directory when the SDK cannot sandbox", () =>
118 + it.effect("recovers invalid output after the SDK cannot sandbox", () =>
119 Effect.gen(function* () {
120 // The SDK checks sandbox support lazily, so create succeeds and send rejects.
121 cursorSdkMock.create.mockImplementationOnce(async () => ({
@@ -120,6 +129,11 @@ describe("CursorTextGeneration", () => {
129 );
130 },
131 }));
132 + cursorSdkMock.prompt.mockResolvedValueOnce({
133 + id: "invalid-output-after-sandbox-fallback",
134 + status: "finished",
135 + result: "Not JSON",
136 + });
137 const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
138 CURSOR_API_KEY: "test-cursor-key",
139 });
@@ -133,7 +147,9 @@ describe("CursorTextGeneration", () => {
147 });
148
149 expect(generated.subject).toBe("Add generated commit message");
136 - expect(cursorSdkMock.create).toHaveBeenCalledTimes(2);
150 + expect(cursorSdkMock.create).toHaveBeenCalledTimes(3);
151 + expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
152 + expect(cursorSdkMock.close).toHaveBeenCalledTimes(3);
153 expect(cursorSdkMock.create.mock.calls[0]?.[0]).toMatchObject({
154 local: { sandboxOptions: { enabled: true } },
155 });
@@ -175,9 +191,115 @@ describe("CursorTextGeneration", () => {
191
192 expect(generated.subject).toBe("Update README dummy comment with attribution and date");
193 expect(generated.body).toBe("");
194 + expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
195 }).pipe(Effect.provide(layerTest)),
196 );
197
198 + it.effect.each([
199 + { name: "invalid JSON", result: "Add a generated commit message" },
200 + {
201 + name: "a body with the wrong type",
202 + result: '{"subject":"Add generated commit message","body":[]}',
203 + },
204 + ])("retries $name with a fresh agent before returning a commit message", ({ result }) =>
205 + Effect.gen(function* () {
206 + cursorSdkMock.prompt
207 + .mockResolvedValueOnce({ id: "invalid-output", status: "finished", result })
208 + .mockImplementationOnce(async () => {
209 + expect(cursorSdkMock.close).toHaveBeenCalledOnce();
210 + return {
211 + id: "valid-output",
212 + status: "finished",
213 + result: '{"subject":"Add generated commit message","body":""}',
214 + };
215 + });
216 + const generation = yield* makeCursorTextGeneration(cursorSettings, {
217 + CURSOR_API_KEY: "test-cursor-key",
218 + });
219 + const generated = yield* generation.generateCommitMessage({
220 + cwd: process.cwd(),
221 + branch: "feature/cursor",
222 + stagedSummary: "M file.ts",
223 + stagedPatch: "diff",
224 + modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
225 + });
226 +
227 + expect(generated).toEqual({
228 + subject: "Add generated commit message",
229 + body: "",
230 + });
231 + expect(cursorSdkMock.create).toHaveBeenCalledTimes(2);
232 + expect(cursorSdkMock.close).toHaveBeenCalledTimes(2);
233 + expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
234 + }).pipe(Effect.provide(layerTest)),
235 + );
236 +
237 + it.effect("stops after a second invalid reply and preserves the validation error", () =>
238 + Effect.gen(function* () {
239 + cursorSdkMock.prompt.mockResolvedValue({
240 + id: "invalid-output",
241 + status: "finished",
242 + result: '{"subject":"Add generated commit message","body":null}',
243 + });
244 + const generation = yield* makeCursorTextGeneration(cursorSettings, {
245 + CURSOR_API_KEY: "test-cursor-key",
246 + });
247 + const failure = yield* Effect.flip(
248 + generation.generateCommitMessage({
249 + cwd: process.cwd(),
250 + branch: null,
251 + stagedSummary: "M file.ts",
252 + stagedPatch: "diff",
253 + modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
254 + }),
255 + );
256 +
257 + expect(failure.operation).toBe("generateCommitMessage");
258 + expect(failure.detail).toBe("Cursor SDK returned invalid structured output.");
259 + expect(Schema.isSchemaError(failure.cause)).toBe(true);
260 + expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
261 + }).pipe(Effect.provide(layerTest)),
262 + );
263 +
264 + it.effect("keeps both attempts inside the original deadline and cancels the pending retry", () =>
265 + Effect.gen(function* () {
266 + const firstStarted = Promise.withResolvers<void>();
267 + const retryStarted = Promise.withResolvers<void>();
268 + const firstResult = Promise.withResolvers<RunResult>();
269 + cursorSdkMock.prompt
270 + .mockImplementationOnce(() => {
271 + firstStarted.resolve();
272 + return firstResult.promise;
273 + })
274 + .mockImplementationOnce(() => {
275 + retryStarted.resolve();
276 + return new Promise(() => {});
277 + });
278 + const generation = yield* makeCursorTextGeneration(cursorSettings, {
279 + CURSOR_API_KEY: "test-cursor-key",
280 + });
281 + const request = yield* generation
282 + .generateThreadTitle({
283 + cwd: process.cwd(),
284 + message: "Fix reconnect",
285 + modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "auto"),
286 + })
287 + .pipe(Effect.flip, Effect.forkScoped);
288 +
289 + yield* Effect.promise(() => firstStarted.promise);
290 + yield* TestClock.adjust("2 minutes");
291 + firstResult.resolve({ id: "invalid-output", status: "finished", result: "Not JSON" });
292 + yield* Effect.promise(() => retryStarted.promise);
293 + yield* TestClock.adjust("1 minute");
294 +
295 + expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(2);
296 + expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
297 + expect((yield* Fiber.join(request)).detail).toBe("Cursor SDK request timed out.");
298 + expect(cursorSdkMock.close).toHaveBeenCalledTimes(2);
299 + expect(cursorSdkMock.storeDispose).toHaveBeenCalledOnce();
300 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
301 + );
302 +
303 it.effect("generates thread titles through Cursor SDK text generation", () =>
304 Effect.gen(function* () {
305 cursorSdkMock.prompt.mockResolvedValueOnce({
@@ -215,14 +337,15 @@ describe("CursorTextGeneration", () => {
337 detail: "Cursor SDK request finished with an error.",
338 },
339 { status: "cancelled", error: undefined, detail: "Cursor SDK request was cancelled." },
340 + { status: "finished", error: undefined, detail: "Cursor SDK returned empty output." },
341 ] as const)(
219 - "rejects a $status Cursor SDK run ($error.code) that includes valid title JSON",
342 + "does not retry an unsuccessful or empty $status Cursor SDK run ($error.code)",
343 ({ status, error, detail }) =>
344 Effect.gen(function* () {
345 const promptResult = {
346 id: "run-cursor-partial-title-test",
347 status,
225 - result: '{"title":"Partial title from a failed run."}',
348 + result: status === "finished" ? " " : '{"title":"Partial title from a failed run."}',
349 ...(error ? { error } : {}),
350 } satisfies RunResult;
351 cursorSdkMock.prompt.mockResolvedValueOnce(promptResult);
@@ -245,6 +368,7 @@ describe("CursorTextGeneration", () => {
368 expect(failure.message).not.toContain("Raw Cursor");
369 expect(failure.cause).toBe(error);
370 expect(cursorSdkMock.close).toHaveBeenCalledOnce();
371 + expect(cursorSdkMock.prompt).toHaveBeenCalledOnce();
372 }).pipe(Effect.provide(layerTest)),
373 );
374
packages/provider-cursor/src/server/textGeneration.ts
+30 -28
@@ -2,7 +2,6 @@ import * as FileSystem from "effect/FileSystem";
2
3 import type { AgentOptions, RunResult } from "@cursor/sdk";
4 import * as Effect from "effect/Effect";
5 -import * as Option from "effect/Option";
5 import * as Schema from "effect/Schema";
6
7 import {
@@ -187,35 +186,38 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
186 }, Effect.scoped);
187 // The SDK may reject sandboxing in create or lazily in send. Empty cwd and setting
188 // sources isolate the unsandboxed retry from user projects.
190 - const request = runPrompt(true).pipe(
191 - Effect.catchIf(cursorSandboxUnsupported, () => runPrompt(false)),
189 + const request = Effect.gen(function* () {
190 + const promptResult = yield* runPrompt(true).pipe(
191 + Effect.catchIf(cursorSandboxUnsupported, () => runPrompt(false)),
192 + );
193 + const rawResult = promptResult.result?.trim() ?? "";
194 + if (promptResult.status !== "finished" || !rawResult) {
195 + return yield* new TextGenerationError({
196 + operation,
197 + detail: cursorSdkResultDetail(promptResult),
198 + ...(promptResult.error ? { cause: promptResult.error } : {}),
199 + });
200 + }
201 +
202 + return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
203 + }).pipe(
204 + Effect.retry({
205 + times: 1,
206 + while: (cause) => isTextGenerationError(cause) && Schema.isSchemaError(cause.cause),
207 + }),
208 );
193 - const promptResult = yield* request.pipe(
194 - Effect.timeoutOption(CURSOR_TIMEOUT_MS),
195 - Effect.flatMap(
196 - Option.match({
197 - onNone: () =>
198 - Effect.fail(
199 - new TextGenerationError({
200 - operation,
201 - detail: "Cursor SDK request timed out.",
202 - }),
203 - ),
204 - onSome: (value) => Effect.succeed(value),
205 - }),
206 - ),
209 + return yield* request.pipe(
210 + Effect.timeoutOrElse({
211 + duration: CURSOR_TIMEOUT_MS,
212 + orElse: () =>
213 + Effect.fail(
214 + new TextGenerationError({
215 + operation,
216 + detail: "Cursor SDK request timed out.",
217 + }),
218 + ),
219 + }),
220 );
208 -
209 - const rawResult = promptResult.result?.trim() ?? "";
210 - if (promptResult.status !== "finished" || !rawResult) {
211 - return yield* new TextGenerationError({
212 - operation,
213 - detail: cursorSdkResultDetail(promptResult),
214 - ...(promptResult.error ? { cause: promptResult.error } : {}),
215 - });
216 - }
217 -
218 - return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
221 },
222 (effect, input) => {
223 const { operation } = input;